List of usage examples for java.math BigDecimal floatValue
@Override public float floatValue()
From source file:org.openhab.binding.km200.internal.KM200Comm.java
/** * This function parses the receviced JSON Data and return the right state * */// w w w . j a va 2 s. com public State parseJSONData(String decodedData, String type, String item, KM200BindingProvider provider) { JSONObject nodeRoot = null; State state = null; Class<? extends Item> itemType = provider.getItemType(item); String service = checkParameterReplacement(provider, item); KM200CommObject object = device.serviceMap.get(service); logger.debug("parseJSONData service: {}, data: {}", service, decodedData); /* Now parsing of the JSON String depending on its type and the type of binding item */ try { if (decodedData.length() > 0) { nodeRoot = new JSONObject(decodedData); } else { logger.warn("Get empty reply"); return null; } switch (type) { case "stringValue": /* Check whether the type is a single value containing a string value */ logger.debug("initDevice: type string value: {}", decodedData); String sVal = nodeRoot.getString("value"); device.serviceMap.get(service).setValue(sVal); /* SwitchItem Binding */ if (itemType.isAssignableFrom(SwitchItem.class)) { if (provider.getParameter(item).containsKey("on")) { if (sVal.equals(provider.getParameter(item).get("off"))) { state = OnOffType.OFF; } else if (sVal.equals(provider.getParameter(item).get("on"))) { state = OnOffType.ON; } } else { logger.warn("Switch-Item only on configured on/off string values: {}", decodedData); return null; } /* NumberItem Binding */ } else if (itemType.isAssignableFrom(NumberItem.class)) { try { state = new DecimalType(Float.parseFloat(sVal)); } catch (NumberFormatException e) { logger.error( "Conversion of the string value to Decimal wasn't possible, data: {} error: {}", decodedData, e); return null; } /* DateTimeItem Binding */ } else if (itemType.isAssignableFrom(DateTimeItem.class)) { try { state = new DateTimeType(sVal); } catch (IllegalArgumentException e) { logger.error( "Conversion of the string value to DateTime wasn't possible, data: {} error: {}", decodedData, e); return null; } /* StringItem Binding */ } else if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(sVal); } else { logger.warn("Bindingtype not supported for string values: {}", itemType.getClass()); return null; } return state; case "floatValue": /* Check whether the type is a single value containing a float value */ logger.debug("state of type float value: {}", decodedData); BigDecimal bdVal = nodeRoot.getBigDecimal("value"); device.serviceMap.get(service).setValue(bdVal); /* NumberItem Binding */ if (itemType.isAssignableFrom(NumberItem.class)) { state = new DecimalType(bdVal.floatValue()); /* StringItem Binding */ } else if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(bdVal.toString()); } else { logger.warn("Bindingtype not supported for float values: {}", itemType.getClass()); return null; } return state; case "switchProgram": /* Check whether the type is a switchProgram */ KM200SwitchProgramService sPService = null; logger.debug("state of type switchProgram: {}", decodedData); /* Get the KM200SwitchProgramService class object with all specific parameters */ if (object.getVirtual() == 0) { sPService = ((KM200SwitchProgramService) object.getValueParameter()); } else { sPService = ((KM200SwitchProgramService) device.serviceMap.get(object.getParent()) .getValueParameter()); } /* Update the switches insode the KM200SwitchProgramService */ sPService.updateSwitches(nodeRoot); /* the parsing of switch program-services have to be outside, using json in strings */ if (object.getVirtual() == 1) { return this.getVirtualState(object, itemType, service); } else { /* if access to the parent non virtual service the return the switchPoints jsonarray */ if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(nodeRoot.getJSONArray("switchPoints").toString()); } else { logger.warn( "Bindingtype not supported for switchProgram, only json over strings supported: {}", itemType.getClass()); return null; } return state; } case "errorList": /* Check whether the type is a errorList */ KM200ErrorService eService = null; logger.debug("state of type errorList: {}", decodedData); /* Get the KM200ErrorService class object with all specific parameters */ if (object.getVirtual() == 0) { eService = ((KM200ErrorService) object.getValueParameter()); } else { eService = ((KM200ErrorService) device.serviceMap.get(object.getParent()).getValueParameter()); } /* Update the switches insode the KM200SwitchProgramService */ eService.updateErrors(nodeRoot); /* the parsing of switch program-services have to be outside, using json in strings */ if (object.getVirtual() == 1) { return this.getVirtualState(object, itemType, service); } else { /* if access to the parent non virtual service the return the switchPoints jsonarray */ if (itemType.isAssignableFrom(StringItem.class)) { state = new StringType(nodeRoot.getJSONArray("values").toString()); } else { logger.warn( "Bindingtype not supported for error list, only json over strings is supported: {}", itemType.getClass()); return null; } return state; } case "yRecording": /* Check whether the type is a yRecording */ logger.info("state of: type yRecording is not supported yet: {}", decodedData); /* have to be completed */ break; case "systeminfo": /* Check whether the type is a systeminfo */ logger.info("state of: type systeminfo is not supported yet: {}", decodedData); /* have to be completed */ break; case "arrayData": /* Check whether the type is a arrayData */ logger.info("state of: type arrayData is not supported yet: {}", decodedData); /* have to be completed */ break; } } catch (JSONException e) { logger.error("Parsingexception in JSON, data: {} error: {} ", decodedData, e.getMessage()); } return null; }
From source file:edu.ku.brc.specify.config.Scriptlet.java
/** * Formats a BigDecimal to a string with "N","S","E", "W". * @param bdValue the float value// ww w.j a v a 2 s. c o m * @param isLat whether it is a lat or lon * @return Formats a float to a string with "N","S","E", "W" */ public String getDirChar(final BigDecimal bdValue, final boolean isLat) { if (bdValue == null) { return ""; } String key; if (isLat) { key = bdValue.floatValue() > 0.0 ? SCRPLT_N : SCRPLT_S; } else { key = bdValue.floatValue() > 0.0 ? SCRPLT_E : SCRPLT_W; } return UIRegistry.getResourceString(key); }
From source file:fr.bmartel.speedtest.SpeedTestTask.java
/** * get a download/upload report.//from ww w . j av a 2 s.c om * * @param mode speed test mode requested * @return speed test report */ public SpeedTestReport getReport(final SpeedTestMode mode) { BigDecimal temporaryPacketSize = BigDecimal.ZERO; BigDecimal totalPacketSize = BigDecimal.ZERO; switch (mode) { case DOWNLOAD: temporaryPacketSize = new BigDecimal(mDownloadTemporaryPacketSize); totalPacketSize = mDownloadPckSize; break; case UPLOAD: temporaryPacketSize = new BigDecimal(mUploadTempFileSize); totalPacketSize = mUploadFileSize; break; default: break; } long currentTime; if (mTimeEnd == 0) { currentTime = System.currentTimeMillis(); } else { currentTime = mTimeEnd; } BigDecimal transferRateOps = BigDecimal.ZERO; final int scale = mSocketInterface.getDefaultScale(); final RoundingMode roundingMode = mSocketInterface.getDefaultRoundingMode(); if (shallCalculateTransferRate(currentTime, mode)) { transferRateOps = temporaryPacketSize.divide(new BigDecimal(currentTime - mTimeStart) .divide(SpeedTestConst.MILLIS_DIVIDER, scale, roundingMode), scale, roundingMode); } final BigDecimal transferRateBitps = transferRateOps.multiply(SpeedTestConst.BIT_MULTIPLIER); BigDecimal percent = BigDecimal.ZERO; SpeedTestReport report; if (mRepeatWrapper.isRepeat()) { report = mRepeatWrapper.getRepeatReport(scale, roundingMode, mode, currentTime, transferRateOps); } else { if (totalPacketSize != BigDecimal.ZERO) { percent = temporaryPacketSize.multiply(SpeedTestConst.PERCENT_MAX).divide(totalPacketSize, scale, roundingMode); } report = new SpeedTestReport(mode, percent.floatValue(), mTimeStart, currentTime, temporaryPacketSize.longValueExact(), totalPacketSize.longValueExact(), transferRateOps, transferRateBitps, 1); } return report; }
From source file:org.zuinnote.hadoop.office.format.common.converter.ExcelConverterSimpleSpreadSheetCellDAO.java
/** * Translate a data row according to the currently defined schema. * //from w w w. ja v a 2s . com * @param dataRow cells containing data * @return an array of objects of primitive datatypes (boolean, int, byte, etc.) * containing the data of datarow, null if dataRow does not fit into * schema. Note: single elements can be null depending on the original * Excel * */ public Object[] getDataAccordingToSchema(SpreadSheetCellDAO[] dataRow) { if (dataRow == null) { return new Object[this.schemaRow.size()]; } if (dataRow.length > this.schemaRow.size()) { LOG.warn("Data row is larger than schema. Will return String for everything that is not specified. "); } List<Object> returnList = new ArrayList<>(); for (int i = 0; i < this.schemaRow.size(); i++) { // fill up with schema rows returnList.add(null); } for (int i = 0; i < dataRow.length; i++) { SpreadSheetCellDAO currentCell = dataRow[i]; if (currentCell != null) { // determine real position int j = new CellAddress(currentCell.getAddress()).getColumn(); if (j >= returnList.size()) { // fill up for (int x = returnList.size(); x <= j; x++) { returnList.add(null); } } GenericDataType applyDataType = null; if (j >= this.schemaRow.size()) { LOG.warn("No further schema row for column defined: " + String.valueOf(j) + ". Will assume String."); } else { applyDataType = this.schemaRow.get(j); } if (applyDataType == null) { returnList.set(j, currentCell.getFormattedValue()); } else if (applyDataType instanceof GenericStringDataType) { returnList.set(j, currentCell.getFormattedValue()); } else if (applyDataType instanceof GenericBooleanDataType) { if (!"".equals(currentCell.getFormattedValue())) { if (currentCell.getFormattedValue().equalsIgnoreCase("true") || currentCell.getFormattedValue().equalsIgnoreCase("false")) { returnList.set(j, Boolean.valueOf(currentCell.getFormattedValue())); } } } else if (applyDataType instanceof GenericTimestampDataType) { if (!"".equals(currentCell.getFormattedValue())) { boolean timestampFound = false; if (this.dateTimeFormat != null) { // check first dateTimeFormat Date theDate = this.dateTimeFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, new java.sql.Timestamp(theDate.getTime())); timestampFound = true; } else { returnList.set(j, null); LOG.warn( "Could not identify timestamp using Date.parse using provided dateTime format. Trying Timestamp.valueOf. Original value: " + currentCell.getFormattedValue()); } } if (!timestampFound) { try { returnList.set(j, java.sql.Timestamp.valueOf(currentCell.getFormattedValue())); timestampFound = true; } catch (IllegalArgumentException e) { returnList.set(j, null); LOG.warn( "Could not identify timestamp using TimeStamp.valueOf. Trying last resort Date parsing. Original value: " + currentCell.getFormattedValue()); } } if (!timestampFound) { Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, new java.sql.Timestamp(theDate.getTime())); } else { returnList.set(j, null); LOG.warn( "Could not identify timestamp using Date.parse using provided date format"); } } } } else if (applyDataType instanceof GenericDateDataType) { if (!"".equals(currentCell.getFormattedValue())) { Date theDate = this.dateFormat.parse(currentCell.getFormattedValue(), new ParsePosition(0)); if (theDate != null) { returnList.set(j, theDate); } else { returnList.set(j, null); } } } else if (applyDataType instanceof GenericNumericDataType) { if (!"".equals(currentCell.getFormattedValue())) { BigDecimal bd = null; try { if (!"".equals(currentCell.getFormattedValue())) { // check scientific notation if (currentCell.getFormattedValue().toUpperCase().contains("E")) { // parse scientific notation // remove any characters that could cause issues String sanitizedCellContent = currentCell.getFormattedValue().replace(",", "."); bd = new BigDecimal(sanitizedCellContent); } else { bd = (BigDecimal) this.decimalFormat.parse(currentCell.getFormattedValue()); } } } catch (ParseException p) { LOG.warn( "Could not parse decimal in spreadsheet cell, although type was detected as decimal"); } if (bd != null) { BigDecimal bdv = bd.stripTrailingZeros(); if (applyDataType instanceof GenericByteDataType) { returnList.set(j, (byte) bdv.byteValueExact()); } else if (applyDataType instanceof GenericShortDataType) { returnList.set(j, (short) bdv.shortValueExact()); } else if (applyDataType instanceof GenericIntegerDataType) { returnList.set(j, (int) bdv.intValueExact()); } else if (applyDataType instanceof GenericLongDataType) { returnList.set(j, (long) bdv.longValueExact()); } else if (applyDataType instanceof GenericDoubleDataType) { returnList.set(j, (double) bdv.doubleValue()); } else if (applyDataType instanceof GenericFloatDataType) { returnList.set(j, (float) bdv.floatValue()); } else if (applyDataType instanceof GenericBigDecimalDataType) { returnList.set(j, bd); } else { returnList.set(j, null); } } } } else { returnList.set(j, null); LOG.warn("Could not convert object in spreadsheet cellrow. Did you add a new datatype?"); } } } Object[] result = new Object[returnList.size()]; returnList.toArray(result); return result; }
From source file:model.experiments.stickyprices.StickyPricesCSVPrinter.java
private static void woodMonopolistSweep(final BigDecimal minimumP, final BigDecimal maximumP, final BigDecimal minimumI, final BigDecimal maximumI, final BigDecimal increment, final int runsPerParameterCombination) throws IOException { CSVWriter writer = new CSVWriter(new FileWriter(Paths.get("runs", "rawdata", "monoSweep.csv").toFile())); writer.writeNext(new String[] { "P", "I", "distance", "variance", "success" }); BigDecimal currentP = minimumP; while (currentP.compareTo(maximumP) <= 0) { BigDecimal currentI = minimumI; while (currentI.compareTo(maximumI) <= 0) { SummaryStatistics averageSquaredDistance = new SummaryStatistics(); SummaryStatistics averageVariance = new SummaryStatistics(); int successes = 0; for (int run = 0; run < runsPerParameterCombination; run++) { //create the run MacroII macroII = new MacroII(run); MonopolistScenario scenario = new MonopolistScenario(macroII); macroII.setScenario(scenario); //set the demand scenario.setDemandIntercept(102); scenario.setDemandSlope(2); scenario.setDailyWageSlope(1); scenario.setDailyWageIntercept(0); scenario.setAskPricingStrategy(SimpleFlowSellerPID.class); scenario.setWorkersToBeRehiredEveryDay(true); scenario.setControlType( MonopolistScenario.MonopolistScenarioIntegratedControlEnum.MARGINAL_PLANT_CONTROL); scenario.setBuyerDelay(0); //start it and have one step macroII.start();//from w w w . j av a 2s .co m macroII.schedule.step(macroII); //now set the right parameters final SalesDepartment salesDepartment = scenario.getMonopolist() .getSalesDepartment(UndifferentiatedGoodType.GENERIC); final SimpleFlowSellerPID strategy = new SimpleFlowSellerPID(salesDepartment, currentP.floatValue(), currentI.floatValue(), 0f, 0, salesDepartment.getMarket(), salesDepartment.getRandom().nextInt(100), salesDepartment.getFirm().getModel()); // strategy.setInitialPrice(102); //start them all at the same price, otherwise you advantage the slow by being so slow initially that they end up being right later salesDepartment.setAskPricingStrategy(strategy); //and make it learned! salesDepartment.setPredictorStrategy(new FixedDecreaseSalesPredictor(2)); final HumanResources hr = scenario.getMonopolist().getHRs().iterator().next(); hr.setPredictor(new FixedIncreasePurchasesPredictor(1)); float totalDistance = 0; SummaryStatistics prices = new SummaryStatistics(); //run the model double price = 0; double quantity = 0; for (int i = 0; i < 1000; i++) { macroII.schedule.step(macroII); price = strategy.getTargetPrice(); quantity = salesDepartment.getTodayInflow(); totalDistance += Math .pow(Math.min(price - (102 - 2 * quantity), price - (102 - 2 * quantity - 1)), 2); prices.addValue(price); } //Model over, now compute statistics averageSquaredDistance.addValue(Math.sqrt(totalDistance)); averageVariance.addValue(prices.getVariance()); if (price <= 68 && price >= 67) successes++; // System.out.println(salesDepartment.getLatestObservation(SalesDataType.LAST_ASKED_PRICE)); macroII.finish(); } String[] csvLine = new String[5]; csvLine[0] = currentP.toString(); csvLine[1] = currentI.toString(); csvLine[2] = String.valueOf(averageSquaredDistance.getMean()); csvLine[3] = String.valueOf(averageVariance.getMean()); csvLine[4] = String.valueOf(successes); writer.writeNext(csvLine); writer.flush(); System.out.println(Arrays.toString(csvLine)); currentI = currentI.add(increment).setScale(2); System.out.println(); } currentP = currentP.add(increment).setScale(2); } }
From source file:it.greenvulcano.gvesb.datahandling.dbo.DBOCallSP.java
/** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, * java.lang.String, java.lang.String) *///from ww w . jav a2 s. c o m @Override public void endElement(String uri, String localName, String qName) throws SAXException { if (ROW_NAME.equals(localName)) { if (!currCriticalError) { executeStatement(); } else { rowDisc++; // aggiunta DiscardCause al dhr... String msg = currentXSLMessage; dhr.addDiscardCause(new DiscardCause(rowCounter, msg)); resultMessage.append("Data error on row ").append(rowCounter).append(": ").append(msg); resultMessage.append("SQL Statement Informations:\n").append(sqlStatementInfo); resultMessage.append("Record parameters:\n").append(dumpCurrentRowFields()); resultStatus = STATUS_PARTIAL; } } else if (COL_NAME.equals(localName)) { CallableStatement cs = (CallableStatement) sqlStatementInfo.getStatement(); try { if (!outOnly) { colDataExpecting = false; String text = textBuffer.toString(); if ((currentUUID != null) && (currentUUID.trim().length() > 0) && (text.length() == 0)) { text = uuids.get(currentUUID); if (text == null) { text = currentUUID; } } if (TIMESTAMP_TYPE.equals(currType) || DATE_TYPE.equals(currType) || TIME_TYPE.equals(currType)) { if (text.equals("")) { if (TIMESTAMP_TYPE.equals(currType)) setNull(cs, Types.TIMESTAMP); else if (DATE_TYPE.equals(currType)) setNull(cs, Types.DATE); else setNull(cs, Types.TIME); currentRowFields.add(null); } else { dateFormatter.applyPattern(currDateFormat); Date formattedDate = dateFormatter.parse(text); if (TIMESTAMP_TYPE.equals(currType)) { Timestamp ts = new Timestamp(formattedDate.getTime()); setTimestamp(cs, ts); currentRowFields.add(ts); } else if (DATE_TYPE.equals(currType)) { java.sql.Date d = new java.sql.Date(formattedDate.getTime()); setDate(cs, d); currentRowFields.add(d); } else { java.sql.Time t = new java.sql.Time(formattedDate.getTime()); setTime(cs, t); currentRowFields.add(t); } } } else if (INTEGER_TYPE.equals(currType) || SMALLINT_TYPE.equals(currType) || BIGINT_TYPE.equals(currType)) { if (text.equals("")) { if (INTEGER_TYPE.equals(currType)) setNull(cs, Types.INTEGER); else if (SMALLINT_TYPE.equals(currType)) setNull(cs, Types.SMALLINT); else setNull(cs, Types.BIGINT); currentRowFields.add(null); } else { if (INTEGER_TYPE.equals(currType)) setInt(cs, Integer.parseInt(text, 10)); else if (SMALLINT_TYPE.equals(currType)) setShort(cs, Short.parseShort(text, 10)); else setLong(cs, Long.parseLong(text, 10)); currentRowFields.add(text); } } else if (FLOAT_TYPE.equals(currType) || DOUBLE_TYPE.equals(currType) || DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { if (text.equals("")) { if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) setNull(cs, Types.NUMERIC); else if (FLOAT_TYPE.equals(currType)) setNull(cs, Types.FLOAT); else setNull(cs, Types.DOUBLE); currentRowFields.add(null); } else { DecimalFormatSymbols dfs = numberFormatter.getDecimalFormatSymbols(); dfs.setDecimalSeparator(currDecSeparator.charAt(0)); dfs.setGroupingSeparator(currGroupSeparator.charAt(0)); numberFormatter.setDecimalFormatSymbols(dfs); numberFormatter.applyPattern(currNumberFormat); boolean isBigDecimal = numberFormatter.isParseBigDecimal(); try { numberFormatter.setParseBigDecimal(true); BigDecimal formattedNumber = (BigDecimal) numberFormatter.parse(text); if (DECIMAL_TYPE.equals(currType) || NUMERIC_TYPE.equals(currType)) { setBigDecimal(cs, formattedNumber); currentRowFields.add(formattedNumber); } else if (FLOAT_TYPE.equals(currType)) { setFloat(cs, formattedNumber.floatValue()); currentRowFields.add(formattedNumber.floatValue()); } else { setDouble(cs, formattedNumber.doubleValue()); currentRowFields.add(formattedNumber.doubleValue()); } } finally { numberFormatter.setParseBigDecimal(isBigDecimal); } } } else if (LONG_STRING_TYPE.equals(currType) || LONG_NSTRING_TYPE.equals(currType)) { if (text.equals("")) { if (LONG_STRING_TYPE.equals(currType)) setNull(cs, Types.CLOB); else setNull(cs, Types.NCLOB); currentRowFields.add(null); } else { if (LONG_STRING_TYPE.equals(currType)) { setCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } else { setNCharacterStream(cs, new StringReader(text)); currentRowFields.add(text); } } } else if (BASE64_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); data = Base64.getDecoder().decode(data); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BINARY_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BLOB); currentRowFields.add(null); } else { byte[] data = text.getBytes(); ByteArrayInputStream bais = new ByteArrayInputStream(data); setBinaryStream(cs, bais, data.length); currentRowFields.add(text); } } else if (BOOLEAN_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.BOOLEAN); currentRowFields.add(null); } else { setBoolean(cs, TextUtils.parseBoolean(text)); currentRowFields.add(text); } } else if (XML_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.SQLXML); currentRowFields.add(null); } else { SQLXML xml = cs.getConnection().createSQLXML(); xml.setString(text); setSQLXML(cs, xml); currentRowFields.add(text); } } else if (NSTRING_TYPE.equals(currType)) { if (text.equals("")) { setNull(cs, Types.NVARCHAR); currentRowFields.add(null); } else { setNString(cs, text); currentRowFields.add(text); } } else { if (text.equals("")) { setNull(cs, Types.VARCHAR); currentRowFields.add(null); } else { setString(cs, text); currentRowFields.add(text); } } } else { currentRowFields.add(currentUUID); } } catch (ParseException exc) { throw new SAXException(exc); } catch (SQLException exc) { OracleExceptionHandler.handleSQLException(exc); throw new SAXException(exc); } } }
From source file:nl.strohalm.cyclos.utils.notifications.MemberNotificationHandlerImpl.java
/** * Send the low units notification if needed *//*from w ww .j av a2s. c om*/ private void notifyLowUnits(final Payment payment) { if (!(payment instanceof Transfer)) { return; } final Account account = fetchService.fetch(payment.getFrom(), RelationshipHelper.nested(Account.Relationships.TYPE, AccountType.Relationships.CURRENCY), RelationshipHelper.nested(Payment.Relationships.FROM, MemberAccount.Relationships.MEMBER, Element.Relationships.GROUP)); if (!(account instanceof MemberAccount)) { return; } final MemberAccount memberAccount = (MemberAccount) account; final Group group = memberAccount.getMember().getGroup(); final AccountType accountType = account.getType(); final MemberGroupAccountSettings mgas = groupService.loadAccountSettings(group.getId(), accountType.getId()); final BigDecimal lowUnits = mgas.getLowUnits() == null ? BigDecimal.ZERO : mgas.getLowUnits(); // If low units message is used... if (lowUnits.floatValue() > PRECISION_DELTA && StringUtils.isNotEmpty(mgas.getLowUnitsMessage())) { doSendLowUnitsNotification(memberAccount, mgas); } }
From source file:com.marcosanta.service.impl.KalturaServiceImpl.java
private int GeneraReporte(List<CatReporteXls> reporteGlobal, List<CatReporteXls> reporteEntrys, List<Object[]> objs, int totalentrys, String nombre, String valorUnitarioMIN, String valorUnitarioTam, String partnerId) {//ww w . j ava2 s .co m for (Object[] obj : objs) { SistemaReporte sr = new SistemaReporte((String) obj[0], (int) obj[1], (long) obj[2]); sr.setDuracion(0L); sr.setFechaCorte(new Date()); BigDecimal tamanioDeci = new BigDecimal(sr.getTamanio()) .divide(new BigDecimal(1024), MathContext.DECIMAL128) .divide(new BigDecimal(1024), MathContext.DECIMAL128); BigDecimal taDeci = new BigDecimal(sr.getTamanio()).divide(new BigDecimal(1024), MathContext.DECIMAL128) .divide(new BigDecimal(1024), MathContext.DECIMAL128); if (reporteGlobal.contains(new CatReporteXls(nombre))) { reporteEntrys.add(new CatReporteXls(sr.getEntryId(), partnerId)); CatReporteXls caRepTmp = reporteGlobal.get(reporteGlobal.indexOf(new CatReporteXls(nombre))); caRepTmp.setMinVistos(caRepTmp.getMinVistos().add(new BigDecimal(sr.getTiempoVisto()))); caRepTmp.setDuration(caRepTmp.getDuration().add(new BigDecimal(sr.getDuracion()))); caRepTmp.setTamanio(caRepTmp.getTamanio().add(tamanioDeci)); caRepTmp.setTotalEntrys(new BigDecimal(totalentrys)); caRepTmp.setTamUni(caRepTmp.getTamUni() .add(tamanioDeci.multiply(new BigDecimal(Double.parseDouble(valorUnitarioTam))))); caRepTmp.setMinVisUni(caRepTmp.getMinVisUni().add(new BigDecimal(sr.getTiempoVisto()))); } else { reporteEntrys.add(new CatReporteXls(sr.getEntryId(), partnerId)); reporteGlobal.add(new CatReporteXls(nombre, new BigDecimal(sr.getTiempoVisto()), tamanioDeci, new BigDecimal(sr.getDuracion()), sr.getFechaCorte(), new BigDecimal(sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)), new BigDecimal(tamanioDeci.floatValue() * Double.parseDouble(valorUnitarioTam)), new BigDecimal(totalentrys))); } totalentrys++; } return totalentrys; }
From source file:com.marcosanta.service.impl.KalturaServiceImpl.java
private int GeneraReporte2(List<CatReporteXls> reporteGlobal, List<Object[]> objs, int totalentrys, String nombre, String valorUnitarioMIN, String valorUnitarioTam, String cuenta) { for (Object[] obj : objs) { SistemaReporte sr = new SistemaReporte((String) obj[0], (Integer) obj[1], (long) obj[2], (long) obj[3], (String) obj[4], (String) obj[5], (String) obj[6], (Date) obj[7]); sr.setNombre(sr.getEntryId());//from w w w. j a v a2 s.com sr.setDuracion(0L); sr.setFechaCorte(new Date()); BigDecimal tamanioDeci = new BigDecimal(sr.getTamanio()) .divide(new BigDecimal(1024), MathContext.DECIMAL128) .divide(new BigDecimal(1024), MathContext.DECIMAL128); BigDecimal taDeci = new BigDecimal(sr.getTamanio()).divide(new BigDecimal(1024), MathContext.DECIMAL128) .divide(new BigDecimal(1024), MathContext.DECIMAL128); if (reporteGlobal.contains(new CatReporteXls(sr.getNombre()))) { CatReporteXls caRepTmp = reporteGlobal .get(reporteGlobal.indexOf(new CatReporteXls(sr.getNombre()))); caRepTmp.setMinVistos(caRepTmp.getMinVistos().add(new BigDecimal(sr.getTiempoVisto()))); caRepTmp.setDuration(caRepTmp.getDuration().add(new BigDecimal(sr.getDuracion()))); caRepTmp.setTamanio(caRepTmp.getTamanio().add(tamanioDeci)); caRepTmp.setTotalEntrys(new BigDecimal(totalentrys)); caRepTmp.setTamUni(caRepTmp.getTamUni() .add(tamanioDeci.multiply(new BigDecimal(Double.parseDouble(valorUnitarioTam))))); caRepTmp.setMinVisUni(caRepTmp.getMinVisUni().add(new BigDecimal(sr.getTiempoVisto()))); } else { reporteGlobal.add(new CatReporteXls(sr.getNombre(), sr.getNombre(), sr.getNombreFabrica(), sr.getNombrePrograma(), cuenta, sr.getNombre(), sr.getNombreUnidad(), tamanioDeci, new BigDecimal(sr.getDuracion()), new BigDecimal(sr.getTiempoVisto()), sr.getFechaCorte(), sr.getFechaCreacion(), new BigDecimal(sr.getTiempoVisto() * Double.parseDouble(valorUnitarioMIN)), new BigDecimal(tamanioDeci.floatValue() * Double.parseDouble(valorUnitarioTam)), new BigDecimal(totalentrys))); } totalentrys++; } return totalentrys; }