public String priceBeco(
      Ctx ctx, int WindowNo, GridTab mTab, GridField mField, Object value, Object oldValue) {
    System.out.println("pricebeco ... ");
    try {
      BigDecimal precio = (BigDecimal) mField.getValue();

      String priceRuleSQL =
          "select xx_lowrank,xx_highrank,xx_termination,xx_increase,xx_infinitevalue from xx_vme_pricerule order by (xx_lowrank)";
      PreparedStatement priceRulePstmt = DB.prepareStatement(priceRuleSQL, null);
      ResultSet priceRuleRs = priceRulePstmt.executeQuery();

      Integer precioInt = precio.intValue();
      BigDecimal precioBig = new BigDecimal(precioInt);
      while (priceRuleRs.next()) {
        if (precioBig.compareTo(priceRuleRs.getBigDecimal("xx_lowrank")) >= 0
            && precioBig.compareTo(priceRuleRs.getBigDecimal("xx_highrank")) <= 0) {
          Integer incremento = priceRuleRs.getInt("xx_increase");

          for (Integer i = priceRuleRs.getInt("xx_lowrank") - 1;
              i <= priceRuleRs.getInt("xx_highrank");
              i = i + incremento) {
            BigDecimal var = new BigDecimal(i);

            if (precioBig.compareTo(var) <= 0) {
              BigDecimal beco = var;

              BigDecimal terminacion = priceRuleRs.getBigDecimal("xx_termination");
              if (terminacion.intValue() == 0) {
                beco = var.add(terminacion);
              } else {
                var = var.divide(new BigDecimal(10));
                Integer aux = var.intValue() * 10;
                beco = new BigDecimal(aux).add(terminacion);
              }
              // mTab.setValue("PriceList", beco);
              priceRuleRs.close();
              priceRulePstmt.close();

              if (beco.compareTo(precio) == 0) {
                return priceBandBeco(ctx, WindowNo, mTab, mField, value, oldValue);
                // return"";
              } else {
                mTab.setValue("PriceList", beco);
                return "";
                // return "Precio Beco Sugerido "+beco.toString();
              }
            }
          }
        }
      }
      priceRuleRs.close();
      priceRulePstmt.close();

      return priceBandBeco(ctx, WindowNo, mTab, mField, value, oldValue);
      // return "";
    } catch (Exception e) {
      return e.getMessage();
    }
  }
Beispiel #2
0
  private Integer getLastPage() {
    BigDecimal bd =
        new BigDecimal(TOTAL_RECORDS)
            .divide(new BigDecimal(Utils.PAGE_SIZE))
            .setScale(0, BigDecimal.ROUND_HALF_UP);

    return bd.intValue() > 0 ? bd.intValue() : 1;
  }
 public static final int objectToInt(Object o) {
   if (o instanceof Number) return ((Number) o).intValue();
   try {
     if (o == null) return -1;
     else {
       BigDecimal bigDecimal = new BigDecimal(o.toString());
       bigDecimal.intValue();
       return bigDecimal.intValue();
     }
   } catch (Exception e) {
     e.printStackTrace();
     return -1;
   }
 }
Beispiel #4
0
 public static int getDecimais(final double numero, final int casas) {
   final BigDecimal numeroArredondado =
       BigDecimal.valueOf(numero).setScale(casas, RoundingMode.HALF_UP);
   final BigDecimal decimais =
       numeroArredondado.subtract(BigDecimal.valueOf(numeroArredondado.intValue()));
   return decimais.multiply(BigDecimal.TEN.pow(casas)).intValue();
 }
Beispiel #5
0
 /** Converte um bigDecimal para inteiro. */
 public static int toInt(final BigDecimal number) {
   if (number == null) {
     return 0;
   } else {
     return number.intValue();
   }
 }
  /**
   * Factory method: create a dateTime value given a date and a time.
   *
   * @param date the date
   * @param time the time
   * @return the dateTime with the given components. If either component is null, returns null
   * @throws XPathException if the timezones are both present and inconsistent
   */
  public static DateTimeValue makeDateTimeValue(DateValue date, TimeValue time)
      throws XPathException {
    if (date == null || time == null) {
      return null;
    }
    DayTimeDurationValue tz1 = (DayTimeDurationValue) date.getComponent(Component.TIMEZONE);
    DayTimeDurationValue tz2 = (DayTimeDurationValue) time.getComponent(Component.TIMEZONE);
    boolean zoneSpecified = (tz1 != null || tz2 != null);
    if (tz1 != null && tz2 != null && !tz1.equals(tz2)) {
      XPathException err = new XPathException("Supplied date and time are in different timezones");
      err.setErrorCode("FORG0008");
      throw err;
    }

    DateTimeValue v = new DateTimeValue();
    v.year = (int) ((Int64Value) date.getComponent(Component.YEAR_ALLOWING_ZERO)).longValue();
    v.month = (byte) ((Int64Value) date.getComponent(Component.MONTH)).longValue();
    v.day = (byte) ((Int64Value) date.getComponent(Component.DAY)).longValue();
    v.hour = (byte) ((Int64Value) time.getComponent(Component.HOURS)).longValue();
    v.minute = (byte) ((Int64Value) time.getComponent(Component.MINUTES)).longValue();
    final BigDecimal secs = ((DecimalValue) time.getComponent(Component.SECONDS)).getDecimalValue();
    v.second = (byte) secs.intValue();
    v.microsecond = secs.multiply(BigDecimal.valueOf(1000000)).intValue() % 1000000;
    if (zoneSpecified) {
      if (tz1 == null) {
        tz1 = tz2;
      }
      v.setTimezoneInMinutes((int) (tz1.getLengthInMicroseconds() / 60000000));
    }
    v.typeLabel = BuiltInAtomicType.DATE_TIME;
    return v;
  }
Beispiel #7
0
 public int getInt(String key) {
   Object temp = get(key);
   int rv = -1;
   if (temp == null) rv = -1;
   else if (temp instanceof Integer) {
     Integer i = (Integer) temp;
     rv = i.intValue();
   }
   if (temp instanceof Long) {
     Long l = (Long) temp;
     long v = l.longValue();
     rv = (int) v;
   } else if (temp instanceof BigDecimal) {
     BigDecimal bd = (BigDecimal) temp;
     rv = bd.intValue();
   } else if (temp instanceof Double) {
     Double d = (Double) temp;
     double v = d.doubleValue();
     rv = (int) v;
   } else if (temp instanceof Float) {
     Float f = (Float) temp;
     float v = f.floatValue();
     rv = (int) v;
   } else if (temp instanceof Short) {
     Short s = (Short) temp;
     short v = s.shortValue();
     rv = (int) v;
   } else if (temp instanceof Byte) {
     Byte b = (Byte) temp;
     byte v = b.byteValue();
     rv = (int) v;
   }
   return rv;
 }
Beispiel #8
0
 /**
  * Return Editor value
  *
  * @return value value (big decimal or integer)
  */
 public Object getValue() {
   if (m_text == null || m_text.getText() == null || m_text.getText().length() == 0) return null;
   String value = m_text.getText();
   //	return 0 if text deleted
   if (value == null || value.length() == 0) {
     if (!m_modified) return null;
     if (m_displayType == DisplayType.Integer) return new Integer(0);
     return Env.ZERO;
   }
   if (value.equals(".") || value.equals(",") || value.equals("-")) value = "0";
   // arboleda - solve bug [ 1759771 ] Parse exception when you enter ".." in a numeric field
   if (value.equals("..")) {
     value = "0";
     m_text.setText(".");
   }
   try {
     Number number = m_format.parse(value);
     value = number.toString(); // 	converts it to US w/o thousands
     BigDecimal bd = new BigDecimal(value);
     if (m_displayType == DisplayType.Integer) return new Integer(bd.intValue());
     if (bd.signum() == 0) return bd;
     return bd.setScale(m_format.getMaximumFractionDigits(), BigDecimal.ROUND_HALF_UP);
   } catch (Exception e) {
     log.log(Level.SEVERE, "Value=" + value, e);
   }
   m_text.setText(m_format.format(0));
   if (m_displayType == DisplayType.Integer) return new Integer(0);
   return Env.ZERO;
 } //	getValue
Beispiel #9
0
  /**
   * @see
   *     org.kuali.kfs.pdp.dataaccess.PaymentGroupDao#getDisbursementNumbersByDisbursementType(java.lang.Integer,
   *     java.lang.String, java.lang.String)
   */
  public List<Integer> getDisbursementNumbersByDisbursementTypeAndBankCode(
      Integer pid, String disbursementType, String bankCode) {
    if (LOG.isDebugEnabled()) {
      LOG.debug("getDisbursementNumbersByDisbursementType() started");
    }

    List<Integer> results = new ArrayList<Integer>();

    Criteria criteria = new Criteria();
    criteria.addEqualTo(PdpPropertyConstants.PaymentGroup.PAYMENT_GROUP_PROCESS_ID, pid);
    criteria.addEqualTo(
        PdpPropertyConstants.PaymentGroup.PAYMENT_GROUP_DISBURSEMENT_TYPE_CODE, disbursementType);
    criteria.addEqualTo(PdpPropertyConstants.PaymentGroup.PAYMENT_GROUP_BANK_CODE, bankCode);

    String[] fields =
        new String[] {PdpPropertyConstants.PaymentGroup.PAYMENT_GROUP_DISBURSEMENT_NBR};

    ReportQueryByCriteria rq =
        QueryFactory.newReportQuery(PaymentGroup.class, fields, criteria, true);
    rq.addOrderBy(PdpPropertyConstants.PaymentGroup.PAYMENT_GROUP_DISBURSEMENT_NBR, true);

    Iterator i = getPersistenceBrokerTemplate().getReportQueryIteratorByQuery(rq);
    while (i.hasNext()) {
      Object[] data = (Object[]) i.next();
      BigDecimal d = (BigDecimal) data[0];
      results.add(new Integer(d.intValue()));
    }
    return results;
  }
 public byte[] getBytes() {
   synchronized (objectMutex) {
     IoBuffer buffer = bufferPool.allocate(4, false).order(ByteOrder.LITTLE_ENDIAN);
     buffer.putInt(percent.intValue());
     return buffer.array();
   }
 }
Beispiel #11
0
 /* 60:   */
 /* 61:   */ public void setVirtual(BigDecimal virtual) /* 62:   */ {
   /* 63:49 */ if (virtual.intValue() == 1) {
     /* 64:50 */ this.virtual = true;
     /* 65:   */ } else {
     /* 66:52 */ this.virtual = false;
     /* 67:   */ }
   /* 68:   */ }
  private void doLastOp() {
    isRestart = true;
    if (lastOp == '\0' || stack.size() == 1) {
      return;
    }

    String valTwo = stack.pop();
    String valOne = stack.pop();
    switch (lastOp) {
      case '+':
        stack.push(new BigDecimal(valOne).add(new BigDecimal(valTwo)).toPlainString());
        break;
      case '-':
        stack.push(new BigDecimal(valOne).subtract(new BigDecimal(valTwo)).toPlainString());
        break;
      case '*':
        stack.push(new BigDecimal(valOne).multiply(new BigDecimal(valTwo)).toPlainString());
        break;
      case '/':
        BigDecimal d2 = new BigDecimal(valTwo);
        if (d2.intValue() == 0) {
          stack.push("0.0");
        } else {
          stack.push(
              new BigDecimal(valOne).divide(d2, 2, BigDecimal.ROUND_HALF_UP).toPlainString());
        }
        break;
      default:
        break;
    }
    setDisplay(stack.peek());
    if (isInEquals) {
      stack.push(valTwo);
    }
  }
Beispiel #13
0
  /**
   * Adds an all-in-one computer (combined with four freely customizable parts) to the cart.
   *
   * @param article requested all-in-one computer
   * @param number the amount of requested articles
   * @param cart contains a fresh initialized cart
   * @param success notification about adding an article to the cart
   * @return redirect to template "allinone"
   */
  @RequestMapping(value = "/cart2", method = RequestMethod.POST)
  public String addcomp(
      @RequestParam("pid") Computer article,
      @RequestParam("number") int number,
      @ModelAttribute Cart cart,
      RedirectAttributes success) {

    Optional<InventoryItem> item = inventory.findByProductIdentifier(article.getIdentifier());

    Quantity quantity = item.map(InventoryItem::getQuantity).orElse(NONE);
    BigDecimal amount1 = quantity.getAmount();
    int i = amount1.intValue();
    int amount = number;
    if (number <= 0) {
      amount = 1;
    }
    if (number >= i) {
      amount = i;
    }

    cart.addOrUpdateItem(article, Quantity.of(amount));
    cart.addOrUpdateItem(article.getProzessor().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getGraka().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getHdd().get(0), Quantity.of(amount));
    cart.addOrUpdateItem(article.getRam().get(0), Quantity.of(amount));

    article.getGraka().clear();
    article.getHdd().clear();
    article.getProzessor().clear();
    article.getRam().clear();

    success.addFlashAttribute(
        "success", "Der Artikel wurde erfolgreich Ihrem Warenkorb hinzugefügt.");
    return "redirect:allinone";
  }
 // If the Decision Table model was pre-5.4 Numeric data-types were always stored as
 // BigDecimals. This function attempts to set the correct DTCellValue property based
 // on the *true* data type.
 private void convertDTCellValueFromNumeric(DataType.DataTypes dataType, DTCellValue52 dcv) {
   // Generic type NUMERIC was always stored as a BigDecimal
   final BigDecimal value = (BigDecimal) dcv.getNumericValue();
   switch (dataType) {
     case NUMERIC_BIGDECIMAL:
       dcv.setNumericValue(value == null ? null : value);
       break;
     case NUMERIC_BIGINTEGER:
       dcv.setNumericValue(value == null ? null : value.toBigInteger());
       break;
     case NUMERIC_BYTE:
       dcv.setNumericValue(value == null ? null : value.byteValue());
       break;
     case NUMERIC_DOUBLE:
       dcv.setNumericValue(value == null ? null : value.doubleValue());
       break;
     case NUMERIC_FLOAT:
       dcv.setNumericValue(value == null ? null : value.floatValue());
       break;
     case NUMERIC_INTEGER:
       dcv.setNumericValue(value == null ? null : value.intValue());
       break;
     case NUMERIC_LONG:
       dcv.setNumericValue(value == null ? null : value.longValue());
       break;
     case NUMERIC_SHORT:
       dcv.setNumericValue(value == null ? null : value.shortValue());
       break;
   }
 }
  protected void convertNumberToInt() throws IOException, JsonParseException {
    // First, converting from long ought to be easy
    if ((_numTypesValid & NR_LONG) != 0) {
      // Let's verify it's lossless conversion by simple roundtrip
      int result = (int) _numberLong;
      if (((long) result) != _numberLong) {
        _reportError("Numeric value (" + getText() + ") out of range of int");
      }
      _numberInt = result;
    } else if ((_numTypesValid & NR_BIGINT) != 0) {
      // !!! Should check for range...
      _numberInt = _numberBigInt.intValue();
    } else if ((_numTypesValid & NR_DOUBLE) != 0) {
      // Need to check boundaries
      if (_numberDouble < MIN_INT_D || _numberDouble > MAX_INT_D) {
        reportOverflowInt();
      }
      _numberInt = (int) _numberDouble;
    } else if ((_numTypesValid & NR_BIGDECIMAL) != 0) {
      if (BD_MIN_INT.compareTo(_numberBigDecimal) > 0
          || BD_MAX_INT.compareTo(_numberBigDecimal) < 0) {
        reportOverflowInt();
      }
      _numberInt = _numberBigDecimal.intValue();
    } else {
      _throwInternal(); // should never get here
    }

    _numTypesValid |= NR_INT;
  }
 // 密码加密
 private static String Encryption(String oldPwd) {
   String newPwd = "0";
   BigDecimal oldPwdBD = new BigDecimal(oldPwd);
   BigDecimal tempYPwd = oldPwdBD.multiply(new BigDecimal("135791"));
   int tempYPwdLen = tempYPwd.toString().length();
   String tempTPwd = "";
   if (tempYPwdLen >= 12) {
     tempTPwd = tempYPwd.toString().substring(1, 7);
   } else if (tempYPwdLen < 12 && tempYPwdLen >= 5) {
     tempTPwd = tempYPwd.toString().substring(0, tempYPwd.toString().length() - 5);
   } else {
     tempTPwd = tempYPwd.toString();
   }
   BigDecimal tempTPwdBD = new BigDecimal(tempTPwd);
   BigDecimal tempZPwdBD = tempTPwdBD.add(oldPwdBD);
   if (tempZPwdBD.intValue() < 1000000) {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   } else {
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("1000000"));
     tempZPwdBD = tempZPwdBD.subtract(new BigDecimal("135791"));
     newPwd = tempZPwdBD.abs().toString();
   }
   // 如果netPwd最后获取的是0,则加密后的密码为999888
   if (newPwd.equals("0")) {
     return "999888";
   } else {
     StringBuilder tempNewPwd = new StringBuilder();
     for (int x = 0; x < 6 - newPwd.length(); x++) {
       tempNewPwd.append("0");
     }
     tempNewPwd.append(newPwd);
     return tempNewPwd.toString();
   }
 }
Beispiel #17
0
 private String stringValue(Double valueIndex) {
   String recordOut = "";
   BigDecimal bdValue = new BigDecimal(valueIndex).setScale(3, RoundingMode.HALF_EVEN);
   switch (bdValue.intValue()) {
     case 1:
       recordOut = "Monday (1)";
       break;
     case 2:
       recordOut = "Tuesday (2)";
       break;
     case 3:
       recordOut = "Wednesday (3)";
       break;
     case 4:
       recordOut = "Thursday (4)";
       break;
     case 5:
       recordOut = "Friday (5)";
       break;
     case 6:
       recordOut = "Saturday (6)";
       break;
     case 0:
       recordOut = "Sunday (7)";
       break;
   }
   return recordOut;
 }
 /**
  * Refund a transaction
  *
  * @param transactionId recurly transaction id
  * @param amount amount to refund, null for full refund
  */
 public void refundTransaction(final String transactionId, @Nullable final BigDecimal amount) {
   String url = Transactions.TRANSACTIONS_RESOURCE + "/" + transactionId;
   if (amount != null) {
     url = url + "?amount_in_cents=" + (amount.intValue() * 100);
   }
   doDELETE(url);
 }
 public WOActionResults rechercherLesPreEtudiants() {
   setLeEtudiant(null);
   try {
     // if (component.qbe().allKeys().count() > 0) {
     EOSortOrdering nomPatronymiqueOrdering =
         EOSortOrdering.sortOrderingWithKey(
             EOPreEtudiant.TO_PRE_INDIVIDU_KEY + "." + EOPreIndividu.NOM_PATRONYMIQUE_KEY,
             EOSortOrdering.CompareCaseInsensitiveAscending);
     EOSortOrdering prenomOrdering =
         EOSortOrdering.sortOrderingWithKey(
             EOPreEtudiant.TO_PRE_INDIVIDU_KEY + "." + EOPreIndividu.PRENOM_KEY,
             EOSortOrdering.CompareCaseInsensitiveAscending);
     NSArray<EOSortOrdering> sortOrderings =
         new NSArray<EOSortOrdering>(
             new EOSortOrdering[] {nomPatronymiqueOrdering, prenomOrdering});
     BigDecimal etudNumeroBG = (BigDecimal) component.qbe().valueForKey("etudNumero");
     preEtudiants =
         FinderPreEtudiant.getPreEtudiants(
             edc,
             etudNumeroBG == null ? null : new Integer(etudNumeroBG.intValue()),
             (String) component.qbe().valueForKey("etudCodeIne"),
             (String) component.qbe().valueForKey("nomPatronymique"),
             (String) component.qbe().valueForKey("prenom"),
             (NSTimestamp) component.qbe().valueForKey("dNaissance"),
             sortOrderings);
     if (preEtudiants == null || preEtudiants.count() == 0) {
       component.session().addSimpleInfoMessage("Pfff...", "Aucun pré-étudiant trouvé...");
     }
     // }
   } catch (CtrlInscriptionException e) {
     component.session().addSimpleErrorMessage("Erreur", e.getMessage());
   }
   return null;
 }
Beispiel #20
0
  /**
   * Find the maximum transactionLedgerEntrySequenceNumber in the entry table for a specific
   * transaction. This is used to make sure that rows added have a unique primary key.
   *
   * @param t the transaction to check
   * @return the max sequence number
   */
  public int getMaxSequenceNumber(Transaction t) {
    LOG.debug("getSequenceNumber() ");

    Criteria crit = new Criteria();
    crit.addEqualTo(UNIVERISITY_FISCAL_YEAR, t.getUniversityFiscalYear());
    crit.addEqualTo(CHART_OF_ACCOUNTS_CODE, t.getChartOfAccountsCode());
    crit.addEqualTo(ACCOUNT_NUMBER, t.getAccountNumber());
    crit.addEqualTo(SUB_ACCOUNT_NUMBER, t.getSubAccountNumber());
    crit.addEqualTo(FINANCIAL_OBJECT_CODE, t.getFinancialObjectCode());
    crit.addEqualTo(FINANCIAL_SUB_OBJECT_CODE, t.getFinancialSubObjectCode());
    crit.addEqualTo(FINANCIAL_BALANCE_TYPE_CODE, t.getFinancialBalanceTypeCode());
    crit.addEqualTo(FINANCIAL_OBJECT_TYPE_CODE, t.getFinancialObjectTypeCode());
    crit.addEqualTo(UNIVERISTY_FISCAL_PERIOD_CODE, t.getUniversityFiscalPeriodCode());
    crit.addEqualTo(FINANCIAL_DOCUMENT_TYPE_CODE, t.getFinancialDocumentTypeCode());
    crit.addEqualTo(FINANCIAL_SYSTEM_ORIGINATION_CODE, t.getFinancialSystemOriginationCode());
    crit.addEqualTo(KFSPropertyConstants.DOCUMENT_NUMBER, t.getDocumentNumber());

    ReportQueryByCriteria q = QueryFactory.newReportQuery(Entry.class, crit);
    q.setAttributes(new String[] {"max(transactionLedgerEntrySequenceNumber)"});

    Iterator iter = getPersistenceBrokerTemplate().getReportQueryIteratorByQuery(q);
    // would this work better? max = (BigDecimal)
    // getPersistenceBrokerTemplate().getObjectByQuery(q);
    BigDecimal max = null;
    while (iter.hasNext()) {
      Object[] data = (Object[]) iter.next();
      max = (BigDecimal) data[0]; // Don't know why OJB returns a BigDecimal, but it does
    }
    if (max == null) {
      return 0;
    } else {
      return max.intValue();
    }
  }
  public BigDecimal PrecioBecoRebaja(BigDecimal entrada) {
    C_OrderCallout precio = new C_OrderCallout();
    // BigDecimal entrada = new BigDecimal(99);

    BigDecimal salida = precio.priceBeco(entrada);

    // System.out.println("SALIDA NORMAL"+salida);

    BigDecimal rebaja = new BigDecimal(0);
    int i = entrada.intValue();
    boolean flag = false;
    while (flag == false)
    // for(int i=0;i<entrada.intValue();i++)
    {
      if ((precio.priceBeco(new BigDecimal(i)).compareTo(salida) == 0)) {
        // System.out.println("entro");
        // rebaja = precio.priceBeco(new BigDecimal(i));
        i--;
      } else {
        rebaja = precio.priceBeco(new BigDecimal(i));
        flag = true;
      }
    }
    return rebaja;
    // System.out.println("SALIDA REBAJA " + rebaja);
  }
Beispiel #22
0
  private Object mapper(ResultSet rs, Class clz) throws Exception {
    Field[] fs = clz.getDeclaredFields();
    Object obj = clz.newInstance();
    for (Field f : fs) {
      String name = f.getName();
      f.setAccessible(true);
      Class type = f.getType();
      Object val = rs.getObject(name);
      if (val == null) {
        continue;
      }
      if (val instanceof BigDecimal) {

        BigDecimal tmp = (BigDecimal) val;
        if (type.getName().endsWith("Long")) {
          val = tmp.longValue();
        } else if (type.getName().endsWith("Integer")) {
          val = tmp.intValue();
        } else if (type.getName().endsWith("Short")) {
          val = tmp.shortValue();
        } else if (type.getName().endsWith("Double")) {
          val = tmp.doubleValue();
        } else {
        }
      }
      f.set(obj, val);
    }
    return obj;
  }
  public Integer nextId() {
    Integer id;
    log.debug("Consiguiendo la siguiente secuencia");
    try {
      String sql = "select max(id.dfaId) + 1  as dfaId from FacDfaDetalleFactura";
      Query query = getSession().createQuery(sql);

      Object obj = query.uniqueResult();
      if (obj instanceof Integer) {
        Integer value = (Integer) obj;
        id = value;
      } else if (obj instanceof BigDecimal) {
        BigDecimal value = (BigDecimal) obj;
        id = new Integer(value.intValue());
      } else {
        id = new Integer(0);
      }
      getSession().flush();
      getSession().clear();
    } catch (RuntimeException re) {
      log.error("Secuencia fallida", re);
      throw re;
    }
    return id;
  }
Beispiel #24
0
 private void sendPropertyUpdate(
     Map<String, Object> configurationParameters, HashMap<String, Object> deviceProperties) {
   try {
     Device device = getMaxCubeBridgeHandler().getDevice(maxDeviceSerial);
     rfAddress = device.getRFAddress();
     int roomId = device.getRoomId();
     BigDecimal tempComfort =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_COMFORT_TEMP, deviceProperties.get(PROPERTY_THERMO_COMFORT_TEMP));
     BigDecimal tempEco =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_ECO_TEMP, deviceProperties.get(PROPERTY_THERMO_ECO_TEMP));
     BigDecimal tempSetpointMax =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_MAX_TEMP_SETPOINT,
                 deviceProperties.get(PROPERTY_THERMO_MAX_TEMP_SETPOINT));
     BigDecimal tempSetpointMin =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_MIN_TEMP_SETPOINT,
                 deviceProperties.get(PROPERTY_THERMO_MIN_TEMP_SETPOINT));
     BigDecimal tempOffset =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_OFFSET_TEMP, deviceProperties.get(PROPERTY_THERMO_OFFSET_TEMP));
     BigDecimal tempOpenWindow =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_WINDOW_OPEN_TEMP,
                 deviceProperties.get(PROPERTY_THERMO_WINDOW_OPEN_TEMP));
     BigDecimal durationOpenWindow =
         (BigDecimal)
             configurationParameters.getOrDefault(
                 PROPERTY_THERMO_WINDOW_OPEN_DURATION,
                 deviceProperties.get(PROPERTY_THERMO_WINDOW_OPEN_DURATION));
     S_ConfigCommand cmd =
         new S_ConfigCommand(
             rfAddress,
             roomId,
             tempComfort.doubleValue(),
             tempEco.doubleValue(),
             tempSetpointMax.doubleValue(),
             tempSetpointMin.doubleValue(),
             tempOffset.doubleValue(),
             tempOpenWindow.doubleValue(),
             durationOpenWindow.intValue());
     bridgeHandler.queueCommand(
         new SendCommand(maxDeviceSerial, cmd, "Update Thermostat Properties"));
     sendCCommand();
   } catch (NullPointerException e) {
     logger.warn(
         "MAX! Cube LAN gateway bridge handler not found. Cannot handle update without bridge.");
   } catch (Exception e) {
     logger.debug("Exception occurred during execution: {}", e.getMessage(), e);
   }
 }
Beispiel #25
0
  /**
   * Converter from a numeric object to Integer. Input is checked to be within range represented by
   * the given number type.
   */
  static Integer convertToInt(SessionInterface session, Object a, int type) {

    int value;

    if (a instanceof Integer) {
      if (type == Types.SQL_INTEGER) {
        return (Integer) a;
      }

      value = ((Integer) a).intValue();
    } else if (a instanceof Long) {
      long temp = ((Long) a).longValue();

      if (Integer.MAX_VALUE < temp || temp < Integer.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = (int) temp;
    } else if (a instanceof BigDecimal) {
      BigDecimal bd = ((BigDecimal) a);

      if (bd.compareTo(MAX_INT) > 0 || bd.compareTo(MIN_INT) < 0) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = bd.intValue();
    } else if (a instanceof Double || a instanceof Float) {
      double d = ((Number) a).doubleValue();

      if (session instanceof Session) {
        if (!((Session) session).database.sqlConvertTruncate) {
          d = java.lang.Math.rint(d);
        }
      }

      if (Double.isInfinite(d)
          || Double.isNaN(d)
          || d >= (double) Integer.MAX_VALUE + 1
          || d <= (double) Integer.MIN_VALUE - 1) {
        throw Error.error(ErrorCode.X_22003);
      }

      value = (int) d;
    } else {
      throw Error.error(ErrorCode.X_42561);
    }

    if (type == Types.TINYINT) {
      if (Byte.MAX_VALUE < value || value < Byte.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }
    } else if (type == Types.SQL_SMALLINT) {
      if (Short.MAX_VALUE < value || value < Short.MIN_VALUE) {
        throw Error.error(ErrorCode.X_22003);
      }
    }

    return Integer.valueOf(value);
  }
Beispiel #26
0
  public static List<Map<String, BigDecimal>> getPackageSplit(
      DispatchContext dctx, List<Map<String, Object>> shippableItemInfo, BigDecimal maxWeight) {
    // create the package list w/ the first package
    List<Map<String, BigDecimal>> packages = FastList.newInstance();

    if (UtilValidate.isNotEmpty(shippableItemInfo)) {
      for (Map<String, Object> itemInfo : shippableItemInfo) {
        long pieces = ((Long) itemInfo.get("piecesIncluded")).longValue();
        BigDecimal totalQuantity = (BigDecimal) itemInfo.get("quantity");
        BigDecimal totalWeight = (BigDecimal) itemInfo.get("weight");
        String productId = (String) itemInfo.get("productId");

        // sanity check
        if (pieces < 1) {
          pieces = 1; // can NEVER be less than one
        }
        BigDecimal weight = totalWeight.divide(BigDecimal.valueOf(pieces), generalRounding);
        for (int z = 1; z <= totalQuantity.intValue(); z++) {
          BigDecimal partialQty =
              pieces > 1
                  ? BigDecimal.ONE.divide(BigDecimal.valueOf(pieces), generalRounding)
                  : BigDecimal.ONE;
          for (long x = 0; x < pieces; x++) {
            if (weight.compareTo(maxWeight) >= 0) {
              Map<String, BigDecimal> newPackage = FastMap.newInstance();
              newPackage.put(productId, partialQty);
              packages.add(newPackage);
            } else if (totalWeight.compareTo(BigDecimal.ZERO) > 0) {
              // create the first package
              if (packages.size() == 0) {
                packages.add(FastMap.<String, BigDecimal>newInstance());
              }

              // package loop
              boolean addedToPackage = false;
              for (Map<String, BigDecimal> packageMap : packages) {
                if (!addedToPackage) {
                  BigDecimal packageWeight =
                      calcPackageWeight(dctx, packageMap, shippableItemInfo, weight);
                  if (packageWeight.compareTo(maxWeight) <= 0) {
                    BigDecimal qty = packageMap.get(productId);
                    qty = UtilValidate.isEmpty(qty) ? BigDecimal.ZERO : qty;
                    packageMap.put(productId, qty.add(partialQty));
                    addedToPackage = true;
                  }
                }
              }
              if (!addedToPackage) {
                Map<String, BigDecimal> packageMap = FastMap.newInstance();
                packageMap.put(productId, partialQty);
                packages.add(packageMap);
              }
            }
          }
        }
      }
    }
    return packages;
  }
Beispiel #27
0
  public static Integer converBDToInteger(BigDecimal value) {

    if (value == null) {
      return null;
    } else {
      return value.intValue();
    }
  }
Beispiel #28
0
  /**
   * Czas wyrazony w minutach
   *
   * @return
   */
  public int durationInMinutes() {
    if (duration == null) throw new IllegalStateException("Nie wykonano obliczen");

    BigDecimal periodInMillis = new BigDecimal(MINUTE_IN_MILLIS);

    BigDecimal resp = duration.divide(periodInMillis, 0, BigDecimal.ROUND_DOWN);
    return resp.intValue();
  }
Beispiel #29
0
 private synchronized void setBalance(BigDecimal balance) {
   if (balance == null)
     throw new BalanceIsNotValidException("The balance is not given in the file or is negative");
   else if (balance.intValue() < 0) throw new BalanceIsNotEnoughException();
   else if (balance.intValue() > getUpperBound().intValue())
     throw new UpperBoundExceedException("The balance is bigger than upperbound!");
   else this.balance = balance;
 }
Beispiel #30
0
 /** Evaluate the result of power computation */
 @Override
 public String pow(String[] args) {
   BigDecimal number1, number2, result;
   number1 = new BigDecimal(args[0]);
   number2 = new BigDecimal(args[1]);
   result = number1.pow(number2.intValue());
   return result.toString();
 }