Beispiel #1
0
  /**
   * Is Period Open for Doc Base Type
   *
   * @param DocBaseType document base type
   * @param dateAcct accounting date
   * @return error message or null
   */
  public String isOpen(String DocBaseType, Timestamp dateAcct) {
    if (!isActive()) {
      s_log.warning("Period not active: " + getName());
      return "@C_Period_ID@ <> @IsActive@";
    }

    MAcctSchema as = MClient.get(getCtx(), getAD_Client_ID()).getAcctSchema();
    if (as != null && as.isAutoPeriodControl()) {
      if (!as.isAutoPeriodControlOpen(dateAcct)) return "@PeriodClosed@ - @AutoPeriodControl@";
      //	We are OK
      Timestamp today = new Timestamp(System.currentTimeMillis());
      if (isInPeriod(today) && as.getC_Period_ID() != getC_Period_ID()) {
        as.setC_Period_ID(getC_Period_ID());
        as.save();
      }
      return null;
    }

    //	Standard Period Control
    if (DocBaseType == null) {
      log.warning(getName() + " - No DocBaseType");
      return "@NotFound@ @DocBaseType@";
    }
    MPeriodControl pc = getPeriodControl(DocBaseType);
    if (pc == null) {
      log.warning(getName() + " - Period Control not found for " + DocBaseType);
      return "@NotFound@ @C_PeriodControl_ID@: " + DocBaseType;
    }
    log.fine(getName() + ": " + DocBaseType);
    if (pc.isOpen()) return null;
    return "@PeriodClosed@ - @C_PeriodControl_ID@ (" + DocBaseType + ", " + dateAcct + ")";
  } //	isOpen
Beispiel #2
0
 /**
  * Get Lookup Data for Field in context
  *
  * @param AD_Field_ID field
  * @param context context
  * @param refresh requery
  * @return lookup pair array
  */
 public ArrayList<NamePair> getLookupData(
     int windowNo, int AD_Field_ID, Map<String, String> context, boolean refresh) {
   UIField field = getField(AD_Field_ID, windowNo);
   if (field == null) {
     log.warning("Cannot find AD_Field_ID=" + AD_Field_ID);
     return null;
   }
   CContext ctx = new CContext(m_context.entrySet());
   ctx.addWindow(windowNo, context);
   if (field.isLookup() || field.isButtonLookup()) return field.getAllLookupData(ctx, windowNo);
   else log.warning("No Lookup: " + field.getColumnName());
   return null;
 } // getLookupData
 /**
  * ************************************************************************ Create Missing
  * Document Types
  *
  * @param ctx context
  * @param AD_Client_ID client
  * @param sp server process
  * @param trx transaction
  */
 public static void createDocumentTypes(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trx) {
   s_log.info("AD_Client_ID=" + AD_Client_ID);
   String sql =
       "SELECT rl.Value, rl.Name "
           + "FROM AD_Ref_List rl "
           + "WHERE rl.AD_Reference_ID=183"
           + " AND rl.IsActive='Y' AND NOT EXISTS "
           + " (SELECT * FROM C_DocType dt WHERE dt.AD_Client_ID=? AND rl.Value=dt.DocBaseType)";
   PreparedStatement pstmt = null;
   ResultSet rs = null;
   try {
     pstmt = DB.prepareStatement(sql, trx);
     pstmt.setInt(1, AD_Client_ID);
     rs = pstmt.executeQuery();
     while (rs.next()) {
       String name = rs.getString(2);
       String value = rs.getString(1);
       s_log.config(name + "=" + value);
       MDocType dt = new MDocType(ctx, value, name, trx);
       if (dt.save()) {
         if (sp != null) sp.addLog(0, null, null, name);
         else s_log.fine(name);
       } else {
         if (sp != null) sp.addLog(0, null, null, "Not created: " + name);
         else s_log.warning("Not created: " + name);
       }
     }
   } catch (Exception e) {
     s_log.log(Level.SEVERE, sql, e);
   } finally {
     DB.closeResultSet(rs);
     DB.closeStatement(pstmt);
   }
 } //	createDocumentTypes
Beispiel #4
0
 public void commitChanges() {
   Object oo = getValue();
   if (m_rangeSet) {
     String error = null;
     if (oo instanceof Integer) {
       Integer ii = (Integer) oo;
       if (ii < m_minValue) {
         error = oo + " < " + m_minValue;
         oo = new Integer(m_minValue.intValue());
       } else if (ii > m_maxValue) {
         error = oo + " > " + m_maxValue;
         oo = new Integer(m_maxValue.intValue());
       }
     } else if (oo instanceof BigDecimal) {
       BigDecimal bd = (BigDecimal) oo;
       if (bd.doubleValue() < m_minValue) {
         error = oo + " < " + m_minValue;
         oo = new BigDecimal(m_minValue);
       } else if (bd.doubleValue() > m_maxValue) {
         error = oo + " > " + m_maxValue;
         oo = new BigDecimal(m_maxValue);
       }
     }
     if (error != null) log.warning(error);
   }
   try {
     fireVetoableChange(m_columnName, m_initialText, oo);
     fireActionPerformed();
   } catch (PropertyVetoException pve) {
   }
 }
Beispiel #5
0
  /**
   * Get Field Lookup Value Direct
   *
   * @param windowNo Window
   * @param AD_Field_ID
   * @param keyValues array of id values
   * @param cache
   * @return list of display values
   */
  public ArrayList<NamePair> getLookupValueDirect(
      int AD_Field_ID, ArrayList<String> keyValues, boolean cache) {
    int windowNo = 0; // No Context
    ArrayList<NamePair> displayValues = new ArrayList<NamePair>();
    UIField field = getField(AD_Field_ID, windowNo);

    // if (cache && field.isLookup())
    // field.getLookup().removeAllElements();
    if (field == null) log.warning("Cannot find AD_Field_ID=" + AD_Field_ID);
    //
    for (int i = 0; i < keyValues.size(); i++) {
      String key = keyValues.get(i);
      String value = null;
      if (field != null) value = field.getLookupDisplay(m_context, windowNo, key, cache);
      if (value == null) {
        /*
         * if(key == null) value = ""; else value = "<" + key + ">";
         */
        value = "";
      }
      NamePair pp = new ValueNamePair(key, value);
      displayValues.add(pp);
    }
    return displayValues;
  } // getLookupValueDirect
  /**
   * Get Dependent Access
   *
   * @param whereColumnName column
   * @param includes ids to include
   * @param excludes ids to exclude
   * @return where clause starting with AND or ""
   */
  private static final String getDependentAccess(
      final String whereColumnName, final List<Integer> includes, final List<Integer> excludes) {
    if (includes.size() == 0 && excludes.size() == 0) {
      return "";
    }
    if (includes.size() != 0 && excludes.size() != 0) {
      logger.warning("Mixing Include and Excluse rules - Will not return values");
    }

    final StringBuilder where = new StringBuilder(" AND ");
    if (includes.size() == 1) {
      where.append(whereColumnName).append("=").append(includes.get(0));
    } else if (includes.size() > 1) {
      where.append(whereColumnName).append(" IN (");
      for (int ii = 0; ii < includes.size(); ii++) {
        if (ii > 0) {
          where.append(",");
        }
        where.append(includes.get(ii));
      }
      where.append(")");
    } else if (excludes.size() == 1) {
      where.append(whereColumnName).append("<>").append(excludes.get(0));
    } else if (excludes.size() > 1) {
      where.append(whereColumnName).append(" NOT IN (");
      for (int ii = 0; ii < excludes.size(); ii++) {
        if (ii > 0) {
          where.append(",");
        }
        where.append(excludes.get(ii));
      }
      where.append(")");
    }
    return where.toString();
  } // getDependentAccess
Beispiel #7
0
 /**
  * Justificativa da Inutilização
  *
  * @param xJust
  */
 public void setxJust(String xJust) {
   xJust = RemoverAcentos.remover(xJust);
   //
   if (xJust != null && xJust.length() > 255) {
     log.warning("Motivo do cancelamento truncado para 255 caracteres");
     xJust = xJust.substring(0, 255);
   }
   //
   this.xJust = xJust;
 } //	setxJust
Beispiel #8
0
 /**
  * ************************************************************************ Start: not started ->
  * running
  *
  * @return true if set to running
  */
 public boolean start() {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isNotStarted()) {
     m_state = STATE_Running;
     log.info("starting ...");
     return true;
   }
   String msg = "start failed: Not Not Started (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	start
Beispiel #9
0
 /**
  * Complete: running -> completed
  *
  * @return true if set to completed
  */
 public boolean complete() {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isRunning()) {
     m_state = STATE_Completed;
     log.info("completing ...");
     return true;
   }
   String msg = "complete failed: Not Running (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	complete
Beispiel #10
0
 /**
  * Terminate: open -> terminated
  *
  * @return true if set to terminated
  */
 public boolean terminate() // 	raises CannotStop, NotRunning
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isOpen()) {
     m_state = STATE_Terminated;
     log.info("terminating ...");
     return true;
   }
   String msg = "terminate failed: Not Open (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	terminate
Beispiel #11
0
 /**
  * Resume: suspended -> running
  *
  * @return true if set to sunning
  */
 public boolean resume() // 	raises CannotResume, NotRunning, NotSuspended
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isSuspended()) {
     m_state = STATE_Running;
     log.info("resuming ...");
     return true;
   }
   String msg = "resume failed: Not Suspended (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	resume
Beispiel #12
0
 /**
  * Suspend: running -> suspended
  *
  * @return true if suspended
  */
 public boolean suspend() // 	raises CannotSuspend, NotRunning, AlreadySuspended
     {
   if (log == null) log = CLogger.getCLogger(getClass());
   if (isRunning()) {
     m_state = STATE_Suspended;
     log.info("suspending ...");
     return true;
   }
   String msg = "suspend failed: Not Running (" + getState() + ")";
   if (m_throwException) throw new IllegalStateException(msg);
   log.warning(msg);
   return false;
 } //	suspend
 /**
  * Add class name to class import list
  *
  * @param className
  */
 private void addImportClass(String className) {
   if (className == null
       || (className.startsWith("java.lang.") && !className.startsWith("java.lang.reflect."))
       || className.startsWith(packageName + ".")) return;
   for (String name : s_importClasses) {
     if (className.equals(name)) return;
   }
   if (className.equals("byte[]")) {
     log.warning("Invalid type - " + className);
     return;
   }
   s_importClasses.add(className);
 }
Beispiel #14
0
  /**
   * Find Period of Date based on Client Calendar, it need not be a standard period (used in MRP)
   *
   * @param ctx context
   * @param C_Calendar_ID calendar
   * @param Date date
   * @param trx trx
   * @return active Period or null
   */
  public static MPeriod getPeriod(Ctx ctx, int C_Calendar_ID, Timestamp Date, Trx trx) {
    if (Date == null) {
      s_log.warning("No Date");
      return null;
    }
    if (C_Calendar_ID == 0) {
      s_log.warning("No Calendar");
      return null;
    }

    //	Get it from DB
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    MPeriod retValue = null;
    String sql =
        "SELECT * FROM C_Period "
            + "WHERE C_Year_ID IN "
            + "(SELECT C_Year_ID FROM C_Year WHERE C_Calendar_ID=?)"
            + " AND ? BETWEEN TRUNC(StartDate,'DD') AND TRUNC(EndDate,'DD')"
            + " AND IsActive='Y' ";
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, C_Calendar_ID);
      pstmt.setTimestamp(2, TimeUtil.getDay(Date));
      rs = pstmt.executeQuery();
      if (rs.next()) {
        retValue = new MPeriod(ctx, rs, trx);
      }
    } catch (SQLException e) {
      s_log.log(Level.SEVERE, "DateAcct=" + Date, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    if (retValue == null)
      s_log.warning("No Period for " + Date + " (C_Calendar_ID=" + C_Calendar_ID + ")");
    return retValue;
  } //	getPeriod
  /**
   * Receive notification of the end of an element.
   *
   * @param uri namespace
   * @param localName simple name
   * @param qName qualified name
   * @throws SAXException
   */
  public void endElement(String uri, String localName, String qName) throws SAXException {
    //	Log.trace(Log.l6_Database+1, "TranslationHandler.endElement", qName);
    if (qName.equals(Translation.XML_TAG)
        || qName.equals(Translation.XML_TAG2)
        || qName.equals(Translation.XML_TAG3)) {

    } else if (qName.equals(Translation.XML_ROW_TAG)) {
      //	Set section
      if (m_sql.length() > 0) m_sql.append(",");
      m_sql.append("Updated=").append(DB.TO_DATE(m_time, false));
      if (!m_isBaseLanguage) {
        if (m_trl != null && ("Y".equals(m_trl) || "N".equals(m_trl)))
          m_sql.append(",IsTranslated='").append(m_trl).append("'");
        else m_sql.append(",IsTranslated='Y'");
      }
      //	Where section
      m_sql.append(" WHERE ");
      if (m_curUUID != null) {
        StringBuilder sql =
            new StringBuilder("SELECT ")
                .append(m_TableName)
                .append("_ID")
                .append(" FROM ")
                .append(m_TableName)
                .append(" WHERE ")
                .append(m_TableName)
                .append("_UU =?");
        int ID = DB.getSQLValueEx(null, sql.toString(), m_curUUID);
        m_sql.append(m_TableName).append("_ID=").append(ID);
      } else {
        m_sql.append(m_TableName).append("_ID=").append(m_curID);
      }
      if (!m_isBaseLanguage) m_sql.append(" AND AD_Language='").append(m_AD_Language).append("'");
      if (m_AD_Client_ID >= 0) m_sql.append(" AND AD_Client_ID=").append(m_AD_Client_ID);
      //	Update section
      m_sql.insert(0, m_updateSQL);

      //	Execute
      int no = DB.executeUpdate(m_sql.toString(), null);
      if (no == 1) {
        if (log.isLoggable(Level.FINE)) log.fine(m_sql.toString());
        m_updateCount++;
      } else if (no == 0) log.warning("Not Found - " + m_sql.toString());
      else log.severe("Update Rows=" + no + " (Should be 1) - " + m_sql.toString());
    } else if (qName.equals(Translation.XML_VALUE_TAG)) {
      if (m_sql.length() > 0) m_sql.append(",");
      m_sql.append(m_curColumnName).append("=").append(DB.TO_STRING(m_curValue.toString()));
    }
  } //	endElement
Beispiel #16
0
 /**
  * Get Field
  *
  * @param AD_Field_ID id
  * @param windowNo relative windowNo
  * @return field or null
  */
 public UIField getField(int AD_Field_ID, int windowNo) {
   Integer key = Integer.valueOf(AD_Field_ID);
   UIField field = m_fields.get(key);
   if (field == null) {
     UIFieldVOFactory fieldFactory = new UIFieldVOFactory();
     UIFieldVO vo = fieldFactory.get(m_context, AD_Field_ID);
     // m_context.setSOTrx(windowNo, isSOTrx);
     if (vo != null) {
       field = new UIField(vo);
       field.initialize(m_context, windowNo);
       log.warning("Loaded directly: " + field); // SOTrx may not
       // be correct
       m_fields.put(key, field); // save in cache
     }
   } // create new
   return field;
 } // getField
Beispiel #17
0
  /**
   * Field Changed
   *
   * @param windowNo relative window
   * @param AD_Field_ID field
   * @param AD_Tab_ID tab
   * @param oldValue old field value
   * @param newValue new field value
   * @param context record context
   * @return Field Change VO
   */
  public ChangeVO fieldChanged(
      int windowNo,
      int AD_Field_ID,
      int AD_Tab_ID,
      String oldValue,
      String newValue,
      Map<String, String> context) {
    // Same Values
    if (oldValue == null || oldValue.equals(Null.NULLString)) oldValue = "";
    if (newValue == null || newValue.equals(Null.NULLString)) newValue = "";
    if (oldValue.equals(newValue)) return null;
    //
    UITab tab = getTab(AD_Tab_ID);
    if (tab == null) {
      log.config("Not found AD_Tab_ID=" + AD_Tab_ID);
      return null;
    }
    UIField field = getField(AD_Field_ID, windowNo);
    if (field == null) {
      log.warning("Cannot find AD_Field_ID=" + AD_Field_ID);
      return null;
    }

    CContext ctx = new CContext(m_context.entrySet());
    ctx.addWindow(windowNo, context);
    CContext origCtx = new CContext(m_context.entrySet());
    origCtx.addWindow(windowNo, context);
    ChangeVO change = null;
    try {
      // reset the thread active flag, in case the thread is reused later on
      CThreadUtil.setCalloutActive(false);
      change =
          tab.fieldChanged(
              origCtx, ctx, new ArrayList<UIField>(5), windowNo, field, oldValue, newValue);
      CThreadUtil.setCalloutActive(false);
      ctx.setContext(windowNo, field.getColumnName(), change.newConfirmedFieldValue);
    } catch (Exception e) {
      log.severe("fieldChange error:" + field.getColumnName() + e.getMessage());
    } finally {
      CThreadUtil.setCalloutActive(false);
    }

    return change;
  } // fieldChanged
Beispiel #18
0
 /**
  * Get Field Lookup Value Direct
  *
  * @param windowNo Window
  * @param AD_Field_ID
  * @param keyValues array of id values
  * @param cache
  * @return list of display values
  */
 public ArrayList<String> getLookupValueOnlyDirect(
     int AD_Field_ID, ArrayList<String> keyValues, boolean cache) {
   int windowNo = 0; // No Context
   ArrayList<String> displayValues = new ArrayList<String>();
   UIField field = getField(AD_Field_ID, windowNo);
   if (field == null) log.warning("Cannot find AD_Field_ID=" + AD_Field_ID);
   //
   for (int i = 0; i < keyValues.size(); i++) {
     String key = keyValues.get(i);
     String value = null;
     if (field != null) value = field.getLookupDisplay(m_context, windowNo, key, cache);
     if (value == null) {
       /*
        * if(key == null) value = ""; else value = "<" + key + ">";
        */
       value = "";
     }
     displayValues.add(value);
   }
   return displayValues;
 } // getLookupValueDirect
  /** Create Grid */
  private void createGrid() {
    if (attributeCombo1 == null || m_setting) return; // 	init
    int indexAttr1 = attributeCombo1.getSelectedIndex();
    int indexAttr2 = attributeCombo2.getSelectedIndex();
    if (indexAttr1 == indexAttr2) {
      log.warning("Same Attribute Selected");
      tabbedPane.setSelectedIndex(0);
      return;
    }
    m_setting = true;
    m_M_PriceList_Version_ID = 0;
    KeyNamePair pl = (KeyNamePair) pickPriceList.getSelectedItem();
    if (pl != null) m_M_PriceList_Version_ID = pl.getKey();
    m_M_Warehouse_ID = 0;
    KeyNamePair wh = (KeyNamePair) pickWarehouse.getSelectedItem();
    if (wh != null) m_M_Warehouse_ID = wh.getKey();

    //	x dimension
    int cols = 2;
    MAttributeValue[] xValues = null;
    if (indexAttr1 > 0) xValues = m_attributes[indexAttr1 - 1].getMAttributeValues();
    if (xValues != null) {
      cols = xValues.length;
      log.info("X - " + m_attributes[indexAttr1 - 1].getName() + " #" + xValues.length);
    }

    //	y dimension
    int rows = 2;
    MAttributeValue[] yValues = null;
    if (indexAttr2 > 0) yValues = m_attributes[indexAttr2 - 1].getMAttributeValues();
    if (yValues != null) {
      rows = yValues.length;
      log.info("Y - " + m_attributes[indexAttr2 - 1].getName() + " #" + yValues.length);
    }

    //
    gridPanel.removeAll();
    CPanel grid = new CPanel(new GridLayout(rows, cols, 5, 5));
    gridPanel.add(modePanel, BorderLayout.NORTH);
    gridPanel.add(new CScrollPane(grid), BorderLayout.CENTER);
    //
    log.info("Rows=" + rows + " - Cols=" + cols);
    for (int row = 0; row < rows; row++) {
      for (int col = 0; col < cols; col++) {
        MAttributeValue xValue = null;
        if (xValues != null) xValue = xValues[col];
        MAttributeValue yValue = null;
        if (yValues != null) yValue = yValues[row];
        //	log.fine("Row=" + row + " - Col=" + col);
        //
        if (row == 0 && col == 0) {
          CPanel descr = new CPanel(new GridLayout(2, 1, 0, 0));
          if (xValues != null)
            descr.add(new JLabel(m_attributes[indexAttr1 - 1].getName(), JLabel.TRAILING));
          if (yValues != null) descr.add(new JLabel(m_attributes[indexAttr2 - 1].getName()));
          grid.add(descr);
        } else if (row == 0) // 	column labels
        {
          if (xValue != null) {
            grid.add(new JLabel(xValue.getName(), JLabel.TRAILING));
          } else grid.add(new JLabel());
        } else if (col == 0) // 	row labels
        {
          if (yValue != null) grid.add(new JLabel(yValue.getName()));
          else grid.add(new JLabel());
        } else {
          grid.add(getGridElement(xValue, yValue));
        }
      }
    }
    //
    tabbedPane.setSelectedIndex(1);
    m_setting = false;
    m_frame.pack();
  } //	createGrid
  /**
   * Stream invoice
   *
   * @param request request
   * @param response response
   * @return "" or error message
   */
  private String streamInvoice(HttpServletRequest request, HttpServletResponse response) {
    int MIN_SIZE = 2000; // 	if not created size is 1015

    //	Get Invoice ID
    int C_Invoice_ID = WebUtil.getParameterAsInt(request, "Invoice_ID");
    if (C_Invoice_ID == 0) {
      log.fine("No ID)");
      return "No Invoice ID";
    }

    //	Get Invoice
    Properties ctx = JSPEnv.getCtx(request);
    MInvoice invoice = new MInvoice(ctx, C_Invoice_ID, null);
    if (invoice.getC_Invoice_ID() != C_Invoice_ID) {
      if (log.isLoggable(Level.FINE)) log.fine("Invoice not found - ID=" + C_Invoice_ID);
      return "Invoice not found";
    }
    //	Get WebUser & Compare with invoice
    HttpSession session = request.getSession(true);
    WebUser wu = (WebUser) session.getAttribute(WebUser.NAME);
    if (wu.getC_BPartner_ID() != invoice.getC_BPartner_ID()) {
      log.warning(
          "Invoice from BPartner - C_Invoice_ID="
              + C_Invoice_ID
              + " - BP_Invoice="
              + invoice.getC_BPartner_ID()
              + " = BP_Web="
              + wu.getC_BPartner_ID());
      return "Your invoice not found";
    }

    //	Check Directory
    String dirName = ctx.getProperty("documentDir", ".");
    try {
      File dir = new File(dirName);
      if (!dir.exists()) dir.mkdir();
    } catch (Exception ex) {
      log.log(Level.SEVERE, "Could not create directory " + dirName, ex);
      return "Streaming error - directory";
    }
    //	Check if Invoice already created
    String fileName = invoice.getPDFFileName(dirName);
    File file = new File(fileName);
    if (file.exists() && file.isFile() && file.length() > MIN_SIZE) {
      if (log.isLoggable(Level.INFO))
        log.info("Existing: " + file + " - " + new Timestamp(file.lastModified()));
    } else {
      if (log.isLoggable(Level.INFO)) log.info("New: " + fileName);
      file = invoice.createPDF(file);
      if (file != null) {
        invoice.setDatePrinted(new Timestamp(System.currentTimeMillis()));
        invoice.saveEx();
      }
    }
    //	Issue Error
    if (file == null || !file.exists() || file.length() < MIN_SIZE) {
      log.warning("File does not exist - " + file);
      return "Streaming error - file";
    }

    //	Send PDF
    try {
      int bufferSize = 2048; // 	2k Buffer
      int fileLength = (int) file.length();
      //
      response.setContentType("application/pdf");
      response.setBufferSize(bufferSize);
      response.setContentLength(fileLength);
      //
      if (log.isLoggable(Level.FINE)) log.fine(file.getAbsolutePath() + ", length=" + fileLength);
      long time = System.currentTimeMillis(); // 	timer start
      //
      FileInputStream in = new FileInputStream(file);
      ServletOutputStream out = response.getOutputStream();
      byte[] buffer = new byte[bufferSize];
      double totalSize = 0;
      int count = 0;
      do {
        count = in.read(buffer, 0, bufferSize);
        if (count > 0) {
          totalSize += count;
          out.write(buffer, 0, count);
        }
      } while (count != -1);
      out.flush();
      out.close();
      //
      in.close();
      time = System.currentTimeMillis() - time;
      double speed = (totalSize / 1024) / ((double) time / 1000);
      if (log.isLoggable(Level.FINE))
        log.fine("Length=" + totalSize + " - " + time + " ms - " + speed + " kB/sec");
    } catch (IOException ex) {
      log.log(Level.SEVERE, ex.toString());
      return "Streaming error";
    }

    return null;
  } //	streamInvoice
Beispiel #21
0
  /**
   * Load Activities
   *
   * @return int
   */
  public int loadActivities() {
    long start = System.currentTimeMillis();

    int MAX_ACTIVITIES_IN_LIST =
        MSysConfig.getIntValue("MAX_ACTIVITIES_IN_LIST", 200, Env.getAD_Client_ID(Env.getCtx()));

    model = new ListModelTable();

    ArrayList<MWFActivity> list = new ArrayList<MWFActivity>();
    String sql =
        "SELECT * FROM AD_WF_Activity a "
            + "WHERE a.Processed='N' AND a.WFState='OS' AND ("
            //	Owner of Activity
            + " a.AD_User_ID=?" //	#1
            //	Invoker (if no invoker = all)
            + " OR EXISTS (SELECT * FROM AD_WF_Responsible r WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID"
            + " AND COALESCE(r.AD_User_ID,0)=0 AND COALESCE(r.AD_Role_ID,0)=0 AND (a.AD_User_ID=? OR a.AD_User_ID IS NULL))" //	#2
            // Responsible User
            + " OR EXISTS (SELECT * FROM AD_WF_Responsible r WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID"
            + " AND r.AD_User_ID=?)" //	#3
            //	Responsible Role
            + " OR EXISTS (SELECT * FROM AD_WF_Responsible r INNER JOIN AD_User_Roles ur ON (r.AD_Role_ID=ur.AD_Role_ID)"
            + " WHERE a.AD_WF_Responsible_ID=r.AD_WF_Responsible_ID AND ur.AD_User_ID=?)" //	#4
            //
            + ") ORDER BY a.Priority DESC, Created";
    int AD_User_ID = Env.getAD_User_ID(Env.getCtx());
    MRole role = MRole.get(Env.getCtx(), Env.getAD_Role_ID(Env.getCtx()));
    sql = role.addAccessSQL(sql, "a", true, false);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
      pstmt = DB.prepareStatement(sql, null);
      pstmt.setInt(1, AD_User_ID);
      pstmt.setInt(2, AD_User_ID);
      pstmt.setInt(3, AD_User_ID);
      pstmt.setInt(4, AD_User_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        MWFActivity activity = new MWFActivity(Env.getCtx(), rs, null);
        list.add(activity);
        List<Object> rowData = new ArrayList<Object>();
        rowData.add(activity.getPriority());
        rowData.add(activity.getNodeName());
        rowData.add(activity.getSummary());
        model.add(rowData);
        if (list.size() > MAX_ACTIVITIES_IN_LIST && MAX_ACTIVITIES_IN_LIST > 0) {
          log.warning("More then 200 Activities - ignored");
          break;
        }
      }
    } catch (Exception e) {
      log.log(Level.SEVERE, sql, e);
    } finally {
      DB.close(rs, pstmt);
      rs = null;
      pstmt = null;
    }
    m_activities = new MWFActivity[list.size()];
    list.toArray(m_activities);
    //
    log.fine("#" + m_activities.length + "(" + (System.currentTimeMillis() - start) + "ms)");
    m_index = 0;

    String[] columns =
        new String[] {
          Msg.translate(Env.getCtx(), "Priority"),
          Msg.translate(Env.getCtx(), "AD_WF_Node_ID"),
          Msg.translate(Env.getCtx(), "Summary")
        };

    WListItemRenderer renderer = new WListItemRenderer(Arrays.asList(columns));
    ListHeader header = new ListHeader();
    header.setWidth("30px");
    renderer.setListHeader(0, header);
    renderer.addTableValueChangeListener(listbox);
    model.setNoColumns(columns.length);
    listbox.setModel(model);
    listbox.setItemRenderer(renderer);
    listbox.repaint();
    listbox.setFixedLayout(true);

    return m_activities.length;
  } //	loadActivities
  /**
   * Create Period Controls
   *
   * @param ctx context
   * @param AD_Client_ID client
   * @param sp server process
   * @param trx transaction
   */
  public static void createPeriodControls(Ctx ctx, int AD_Client_ID, SvrProcess sp, Trx trx) {
    s_log.info("AD_Client_ID=" + AD_Client_ID);

    //	Delete Duplicates
    String sql =
        "DELETE FROM C_PeriodControl "
            + "WHERE (C_Period_ID, DocBaseType) IN "
            + "(SELECT C_Period_ID, DocBaseType "
            + "FROM C_PeriodControl pc2 "
            + "GROUP BY C_Period_ID, DocBaseType "
            + "HAVING COUNT(*) > 1)"
            + " AND C_PeriodControl_ID NOT IN "
            + "(SELECT MIN(C_PeriodControl_ID) "
            + "FROM C_PeriodControl pc3 "
            + "GROUP BY C_Period_ID, DocBaseType)";
    int no = DB.executeUpdate(trx, sql);
    s_log.info("Duplicates deleted #" + no);

    //	Insert Missing
    sql =
        "SELECT DISTINCT p.AD_Client_ID, p.C_Period_ID, dbt.DocBaseType "
            + "FROM C_Period p, "
            + "C_DocBaseType dbt "
            + "WHERE p.AD_Client_ID=? "
            + " AND NOT EXISTS"
            + " (SELECT * FROM C_PeriodControl pc "
            + "WHERE pc.C_Period_ID=p.C_Period_ID AND pc.DocBaseType=dbt.DocBaseType)"
            + " AND (dbt.AD_Client_ID = 0 OR p.AD_Client_ID = dbt.AD_Client_ID)";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    int counter = 0;
    try {
      pstmt = DB.prepareStatement(sql, trx);
      pstmt.setInt(1, AD_Client_ID);
      rs = pstmt.executeQuery();
      while (rs.next()) {
        int Client_ID = rs.getInt(1);
        int C_Period_ID = rs.getInt(2);
        String DocBaseType = rs.getString(3);
        s_log.config(
            "AD_Client_ID="
                + Client_ID
                + ", C_Period_ID="
                + C_Period_ID
                + ", DocBaseType="
                + DocBaseType);
        //
        MPeriodControl pc = new MPeriodControl(ctx, Client_ID, C_Period_ID, DocBaseType, trx);
        if (pc.save()) {
          counter++;
          s_log.fine(pc.toString());
        } else s_log.warning("Not saved: " + pc);
      }
    } catch (Exception e) {
      s_log.log(Level.SEVERE, sql, e);
    } finally {
      DB.closeResultSet(rs);
      DB.closeStatement(pstmt);
    }
    if (sp != null) sp.addLog(0, null, new BigDecimal(counter), "@C_PeriodControl_ID@ @Created@");
    s_log.info("Inserted #" + counter);
  } //	createPeriodControls
Beispiel #23
0
  /**
   * Save LOB. see also org.compiere.session.ServerBean#updateLOB
   *
   * @param trxName trx name
   * @return true if saved
   */
  public boolean save(String trxName) {
    if (m_value == null
        || (!(m_value instanceof String || m_value instanceof byte[]))
        || (m_value instanceof String && m_value.toString().length() == 0)
        || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) {
      StringBuffer sql =
          new StringBuffer("UPDATE ")
              .append(m_tableName)
              .append(" SET ")
              .append(m_columnName)
              .append("=null WHERE ")
              .append(m_whereClause);
      int no = DB.executeUpdate(sql.toString(), trxName);
      log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value);
      if (no == 0) log.warning("[" + trxName + "] - not updated - " + sql);
      return true;
    }

    StringBuffer sql =
        new StringBuffer("UPDATE ")
            .append(m_tableName)
            .append(" SET ")
            .append(m_columnName)
            .append("=? WHERE ")
            .append(m_whereClause);
    //

    log.fine("[" + trxName + "] - Local - " + m_value);
    //	Connection
    Trx trx = null;
    if (trxName != null) trx = Trx.get(trxName, false);
    Connection con = null;
    //	Create Connection
    if (trx != null) con = trx.getConnection();
    if (con == null) con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED);
    if (con == null) {
      log.log(Level.SEVERE, "Could not get Connection");
      return false;
    }

    PreparedStatement pstmt = null;
    boolean success = true;
    try {
      pstmt = con.prepareStatement(sql.toString());
      if (DisplayType.isText(m_displayType)) pstmt.setString(1, (String) m_value);
      else pstmt.setBytes(1, (byte[]) m_value);
      int no = pstmt.executeUpdate();
      if (no != 1) {
        log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql);
        success = false;
      }
    } catch (Throwable e) {
      log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e);
      success = false;
    } finally {
      DB.close(pstmt);
      pstmt = null;
    }

    //	Success - commit local trx
    if (success) {
      if (trx != null) {
        trx = null;
        con = null;
      } else {
        try {
          con.commit();
        } catch (Exception e) {
          log.log(Level.SEVERE, "[" + trxName + "] - commit ", e);
          success = false;
        } finally {
          try {
            con.close();
          } catch (SQLException e) {
          }
          con = null;
        }
      }
    }
    //	Error - roll back
    if (!success) {
      log.severe("[" + trxName + "] - rollback");
      if (trx != null) {
        trx.rollback();
        trx = null;
        con = null;
      } else {
        try {
          con.rollback();
        } catch (Exception ee) {
          log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee);
        } finally {
          try {
            con.close();
          } catch (SQLException e) {
          }
          con = null;
        }
      }
    }

    return success;
  } //	save
  /**
   * Get Cached Connection
   *
   * @param connection info
   * @param autoCommit true if autocommit connection
   * @param transactionIsolation Connection transaction level
   * @return connection or null
   * @throws Exception
   */
  @Override
  public Connection getCachedConnection(
      CConnection connection, boolean autoCommit, int transactionIsolation) throws Exception {
    Connection conn = null;
    Exception exception = null;
    try {
      if (m_ds == null) getDataSource(connection);

      //
      try {
        conn = m_ds.getConnection();
        if (conn != null) {
          if (conn.getTransactionIsolation() != transactionIsolation)
            conn.setTransactionIsolation(transactionIsolation);
          if (conn.getAutoCommit() != autoCommit) conn.setAutoCommit(autoCommit);
          //                      conn.setDefaultRowPrefetch(20);     //  10 default - reduces round
          // trips
        }
      } catch (Exception e) {
        exception = e;
        conn = null;
        if (DBException.isInvalidUserPassError(e)) {
          // log might cause infinite loop since it will try to acquire database connection again
          /*
          log.severe("Cannot connect to database: "
              + getConnectionURL(connection)
              + " - UserID=" + connection.getDbUid());
          */
          System.err.println(
              "Cannot connect to database: "
                  + getConnectionURL(connection)
                  + " - UserID="
                  + connection.getDbUid());
        }
      }

      if (conn == null && exception != null) {
        // log might cause infinite loop since it will try to acquire database connection again
        /*
        log.log(Level.SEVERE, exception.toString());
        log.fine(toString()); */
        System.err.println(exception.toString());
      }
    } catch (Exception e) {
      exception = e;
    }

    try {
      if (conn != null) {
        int numConnections = m_ds.getNumBusyConnections();
        if (numConnections >= m_maxbusyconnections && m_maxbusyconnections > 0) {
          log.warning(getStatus());
          // hengsin: make a best effort to reclaim leak connection
          Runtime.getRuntime().runFinalization();
        }
      }
    } catch (Exception ex) {

    }
    if (exception != null) throw exception;
    return conn;
  } //  getCachedConnection
  /**
   * Add Attribute Line
   *
   * @param attribute attribute
   * @param product product level attribute
   * @param readOnly value is read only
   */
  private void addAttributeLine(final MAttribute attribute) {
    final boolean product = m_productWindow;
    final boolean readOnly = false;

    log.fine(attribute + ", Product=" + product + ", R/O=" + readOnly);
    CLabel label = new CLabel(attribute.getName());
    if (product) {
      label.setFont(new Font(label.getFont().getFontName(), Font.BOLD, label.getFont().getSize()));
    }
    if (attribute.getDescription() != null) {
      label.setToolTipText(attribute.getDescription());
    }

    centerPanel.add(label, new ALayoutConstraint(m_row++, 0));
    //
    final int attributeSetInstanceId = asiTemplate.getM_AttributeSetInstance_ID();
    final int attributeId = attribute.getM_Attribute_ID();
    final MAttributeInstance instance = attribute.getMAttributeInstance(attributeSetInstanceId);
    if (MAttribute.ATTRIBUTEVALUETYPE_List.equals(attribute.getAttributeValueType())) {
      InterfaceWrapperHelper.setDynAttribute(
          attribute, Env.DYNATTR_WindowNo, attributeContext.getWindowNo());
      InterfaceWrapperHelper.setDynAttribute(
          attribute, Env.DYNATTR_TabNo, attributeContext.getTabNo()); // tabNo

      final I_M_AttributeValue[] values =
          attribute.getMAttributeValues(getSOTrx()); // optional = null
      final CComboBox<I_M_AttributeValue> editor = new CComboBox<>(values);
      boolean found = false;
      if (instance != null && instance.getM_AttributeValue_ID() > 0) {
        for (int i = 0; i < values.length; i++) {
          if (values[i] != null
              && values[i].getM_AttributeValue_ID() == instance.getM_AttributeValue_ID()) {
            editor.setSelectedIndex(i);
            found = true;
            break;
          }
        }
        if (found)
          log.fine(
              "Attribute=" + attribute.getName() + " #" + values.length + " - found: " + instance);
        else
          log.warning(
              "Attribute="
                  + attribute.getName()
                  + " #"
                  + values.length
                  + " - NOT found: "
                  + instance);
      } // setComboBox
      else {
        log.fine("Attribute=" + attribute.getName() + " #" + values.length + " no instance");
      }
      label.setLabelFor(editor);
      centerPanel.add(editor, null);
      if (readOnly) editor.setEnabled(false);
      else attributeId2editor.put(attributeId, editor);
    } else if (MAttribute.ATTRIBUTEVALUETYPE_Number.equals(attribute.getAttributeValueType())) {
      final VNumber editor =
          new VNumber(
              attribute.getName(), // ColumnName
              attribute.isMandatory(), // mandatory
              false, // IsReadOnly
              true, // IsUpdateable
              DisplayType.Number, // DisplayType
              attribute.getName() // Title
              );
      if (instance != null) {
        if (InterfaceWrapperHelper.isNull(instance, I_M_AttributeInstance.COLUMNNAME_ValueNumber)) {
          editor.setValue(null);
        } else {
          editor.setValue(instance.getValueNumber());
        }
      } else {
        // better don't set a default value
        // editor.setValue(Env.ZERO);
      }
      label.setLabelFor(editor);
      centerPanel.add(editor, null);
      if (readOnly) editor.setEnabled(false);
      else attributeId2editor.put(attributeId, editor);
    } else if (MAttribute.ATTRIBUTEVALUETYPE_Date.equals(attribute.getAttributeValueType())) {
      final VDate editor =
          new VDate(
              attribute.getName(), // columnName
              attribute.isMandatory(), // mandatory
              false, // isReadOnly
              true, // isUpdateable
              DisplayType.Date, // displayType
              attribute.getName() // title
              );
      if (instance != null) editor.setValue(instance.getValueDate());
      label.setLabelFor(editor);
      centerPanel.add(editor, null);
      if (readOnly) editor.setEnabled(false);
      else attributeId2editor.put(attributeId, editor);
    } else
    // Text Field
    {
      VString editor =
          new VString(
              attribute.getName(), // ColumnName
              attribute.isMandatory(), // mandatory
              false, // isReadOnly
              true, // isUpdateable
              20, // displayLength
              INSTANCE_VALUE_LENGTH, // fieldLength
              null, // VFormat
              null // ObscureType
              );
      if (instance != null) editor.setText(instance.getValue());
      label.setLabelFor(editor);
      centerPanel.add(editor, null);
      if (readOnly) editor.setEnabled(false);
      else attributeId2editor.put(attributeId, editor);
    }

    //
    // Add our attribute to the list of attributes
    m_attributes.add(attribute);
  } // addAttributeLine