List of usage examples for java.lang Number longValue
public abstract long longValue();
From source file:fr.cls.atoll.motu.processor.wps.MotuWPSProcess.java
/** * Process request id as long./*www .j ava 2 s.c om*/ * * @param in the in * * @return the long * * @throws MotuException the motu exception * @throws ProcessletException the processlet exception */ public long processRequestIdAsLong(ProcessletInputs in) throws MotuException, ProcessletException { MotuWPSProcessData motuWPSProcessData = getMotuWPSProcessData(in); long requestId = -1; Object object = getRequestIdAsObject(in); if (object == null) { MotuWPSProcess.setReturnCode(motuWPSProcessData.getProcessletOutputs(), new MotuInvalidRequestIdException(requestId), true); return requestId; } Class<?> classType = object.getClass(); if ((classType == long.class) || (classType == Long.class)) { Number number = (Number) object; requestId = number.longValue(); MotuWPSProcess.setRequestId(motuWPSProcessData.getProcessletOutputs(), requestId); } else { // MotuWPSProcess.setRequestId(motuWPSProcessData.getProcessletOutputs(), object.toString()); MotuWPSProcess.setComplexOutputParameters(motuWPSProcessData.getProcessletOutputs(), object.toString()); MotuWPSProcess.setReturnCode(motuWPSProcessData.getProcessletOutputs(), new MotuException(object.toString()), true); } return requestId; }
From source file:com.glaf.dts.transform.MxTransformThread.java
@SuppressWarnings("unchecked") public void run() { logger.debug(taskId + "----------------execution-----------------"); TransformTask task = transformTaskService.getTransformTask(taskId); if (task != null) { if (task.getStatus() == 9 || task.getRetryTimes() > 3) { return; }//from ww w . ja v a 2s. c o m task.setStartTime(new java.util.Date()); task.setRetryTimes(task.getRetryTimes() + 1); task.setStatus(1); transformTaskService.save(task); } List<TableModel> resultList = new java.util.ArrayList<TableModel>(); Map<String, Object> singleDataMap = new HashMap<String, Object>(); Connection conn = null; PreparedStatement psmt = null; ResultSet rs = null; ResultSetMetaData rsmd = null; boolean success = true; long start = System.currentTimeMillis(); logger.debug("start:" + DateUtils.getDateTime(new java.util.Date())); try { Database database = getDatabaseService().getDatabaseById(queryDefinition.getDatabaseId()); if (database != null) { conn = DBConnectionFactory.getConnection(database.getName()); } else { conn = DBConnectionFactory.getConnection(); } logger.debug("conn:" + conn.toString()); String sql = queryDefinition.getSql(); sql = QueryUtils.replaceSQLVars(sql); List<Object> values = null; if (paramMap != null) { SqlExecutor sqlExecutor = JdbcUtils.rebuildSQL(sql, paramMap); sql = sqlExecutor.getSql(); values = (List<Object>) sqlExecutor.getParameter(); } logger.debug("--------------execute query----------------------"); logger.debug(queryDefinition.getTitle()); logger.debug("::sql::" + sql); psmt = conn.prepareStatement(sql); if (values != null && !values.isEmpty()) { JdbcUtils.fillStatement(psmt, values); logger.debug("::values::" + values); } List<ColumnDefinition> columns = new java.util.ArrayList<ColumnDefinition>(); rs = psmt.executeQuery(); rsmd = rs.getMetaData(); int count = rsmd.getColumnCount(); for (int i = 1; i <= count; i++) { int sqlType = rsmd.getColumnType(i); ColumnDefinition column = new ColumnDefinition(); column.setColumnName(rsmd.getColumnName(i)); column.setColumnLabel(rsmd.getColumnLabel(i)); column.setJavaType(FieldType.getJavaType(sqlType)); column.setPrecision(rsmd.getPrecision(i)); column.setScale(rsmd.getScale(i)); columns.add(column); } Set<String> cols = new HashSet<String>(); while (rs.next()) { int index = 0; TableModel rowModel = new TableModel(); ColumnModel cell01 = new ColumnModel(); cell01.setColumnName("ID"); cell01.setType("String"); rowModel.addColumn(cell01); rowModel.setIdColumn(cell01); cols.add(cell01.getColumnName()); ColumnModel cell04 = new ColumnModel(); cell04.setColumnName("AGGREGATIONKEY"); cell04.setType("String"); rowModel.addColumn(cell04); cols.add(cell04.getColumnName()); Iterator<ColumnDefinition> iterator = columns.iterator(); while (iterator.hasNext()) { ColumnDefinition column = iterator.next(); /** * ???? */ if (cols.contains(column.getColumnName())) { continue; } ColumnModel cell = new ColumnModel(); String columnName = column.getColumnName(); String javaType = column.getJavaType(); cell.setColumnName(columnName); cell.setType(javaType); index = index + 1; if ("String".equals(javaType)) { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } else if ("Integer".equals(javaType)) { try { Integer value = rs.getInt(columnName); cell.setIntValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("integer:" + str); str = StringTools.replace(str, "$", ""); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setIntValue(num.intValue()); cell.setValue(cell.getIntValue()); logger.debug("?:" + num.intValue()); } } else if ("Long".equals(javaType)) { try { Long value = rs.getLong(columnName); cell.setLongValue(value); cell.setValue(value); } catch (Exception e) { String str = rs.getString(columnName); logger.error("long:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setLongValue(num.longValue()); cell.setValue(cell.getLongValue()); logger.debug("?:" + num.longValue()); } } else if ("Double".equals(javaType)) { try { Double d = rs.getDouble(columnName); cell.setDoubleValue(d); cell.setValue(d); } catch (Exception e) { String str = rs.getString(columnName); logger.error("double:" + str); str = StringTools.replace(str, "", ""); str = StringTools.replace(str, ",", ""); NumberFormat fmt = NumberFormat.getInstance(); Number num = fmt.parse(str); cell.setDoubleValue(num.doubleValue()); cell.setValue(cell.getDoubleValue()); logger.debug("?:" + num.doubleValue()); } } else if ("Boolean".equals(javaType)) { Boolean value = rs.getBoolean(columnName); cell.setBooleanValue(value); cell.setValue(value); } else if ("Date".equals(javaType)) { Date value = rs.getTimestamp(columnName); cell.setDateValue(value); cell.setValue(value); } else { String value = rs.getString(columnName); cell.setStringValue(value); cell.setValue(value); } rowModel.addColumn(cell); if (resultList.isEmpty()) { singleDataMap.put(column.getColumnLabel(), cell.getValue()); } } resultList.add(rowModel); } logger.debug("--------------------resultList size:" + resultList.size()); } catch (Exception ex) { success = false; ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { JdbcUtils.close(rs); JdbcUtils.close(psmt); JdbcUtils.close(conn); if (!success) { if (task != null) { task.setStatus(2); transformTaskService.save(task); } } } logger.debug("--------------execute mybatis save----------------------"); try { if (!StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C")) { TransformTable tbl = new TransformTable(); tbl.createOrAlterTable(tableDefinition); } List<ColumnDefinition> columns = DBUtils.getColumnDefinitions(tableDefinition.getTableName()); if (columns != null && !columns.isEmpty()) { tableDefinition.setColumns(columns); } if (resultList != null && !resultList.isEmpty() && tableDefinition.getTableName() != null && tableDefinition.getAggregationKeys() != null) { logger.debug("RotatingFlag:" + queryDefinition.getRotatingFlag()); logger.debug("RotatingColumn:" + queryDefinition.getRotatingColumn()); /** * ???? */ if (StringUtils.equalsIgnoreCase(queryDefinition.getRotatingFlag(), "R2C") && StringUtils.isNotEmpty(queryDefinition.getRotatingColumn()) && resultList.size() == 1) { logger.debug("?dataMap?:" + singleDataMap); logger.debug("AggregationKeys:" + tableDefinition.getAggregationKeys()); ColumnDefinition idField = columnMap.get(tableDefinition.getAggregationKeys().toLowerCase()); ColumnDefinition field = columnMap.get(queryDefinition.getRotatingColumn().toLowerCase()); logger.debug("idField:" + idField); logger.debug("field:" + field); if (idField != null && field != null) { String javaType = field.getJavaType(); List<TableModel> list = new ArrayList<TableModel>(); Set<Entry<String, Object>> entrySet = singleDataMap.entrySet(); for (Entry<String, Object> entry : entrySet) { String key = entry.getKey(); Object value = entry.getValue(); if (key == null || value == null) { continue; } TableModel tableModel = new TableModel(); tableModel.setTableName(queryDefinition.getTargetTableName()); ColumnModel cell = new ColumnModel(); cell.setColumnName(queryDefinition.getRotatingColumn()); cell.setType(javaType); // logger.debug(cell.getColumnName()+"->"+javaType); if ("String".equals(javaType)) { cell.setStringValue(ParamUtils.getString(singleDataMap, key)); cell.setValue(cell.getStringValue()); } else if ("Integer".equals(javaType)) { cell.setIntValue(ParamUtils.getInt(singleDataMap, key)); cell.setValue(cell.getIntValue()); } else if ("Long".equals(javaType)) { cell.setLongValue(ParamUtils.getLong(singleDataMap, key)); cell.setValue(cell.getLongValue()); } else if ("Double".equals(javaType)) { cell.setDoubleValue(ParamUtils.getDouble(singleDataMap, key)); cell.setValue(cell.getDoubleValue()); } else if ("Date".equals(javaType)) { cell.setDateValue(ParamUtils.getDate(singleDataMap, key)); cell.setValue(cell.getDateValue()); } else { cell.setValue(value); } tableModel.addColumn(cell); ColumnModel idColumn = new ColumnModel(); idColumn.setColumnName(tableDefinition.getAggregationKeys()); idColumn.setJavaType(idField.getJavaType()); idColumn.setValue(key); tableModel.setIdColumn(idColumn); list.add(tableModel); } logger.debug("update datalist:" + list); tableDataService.updateTableData(list); } } else { tableDataService.saveAll(tableDefinition, null, resultList); } } resultList.clear(); resultList = null; long time = System.currentTimeMillis() - start; if (task != null) { task.setEndTime(new java.util.Date()); task.setStatus(9); task.setDuration(time); } logger.debug("execute time(ms)--------------------------" + time); } catch (Exception ex) { if (task != null) { task.setStatus(2); } ex.printStackTrace(); logger.error(ex); throw new RuntimeException(ex); } finally { if (task != null) { transformTaskService.save(task); if (task.getStatus() != 9) { this.run(); } } } }
From source file:com.tibbo.linkserver.plugin.device.file.item.NumericItem.java
public short[] valueToShorts(Number value) { if (dataType == 2 || dataType == 3) { return (new short[] { toShort(value) }); }//from w w w . j a v a2s . com if (dataType == 16) { short s = toShort(value); return (new short[] { (short) ((s / 1000) % 10 << 12 | (s / 100) % 10 << 8 | (s / 10) % 10 << 4 | s % 10) }); } if (dataType == 4 || dataType == 5) { int i = toInt(value); return (new short[] { (short) (i >> 16), (short) i }); } if (dataType == 6 || dataType == 7) { int i = toInt(value); return (new short[] { (short) i, (short) (i >> 16) }); } if (dataType == 8) { int i = Float.floatToIntBits(value.floatValue()); return (new short[] { (short) (i >> 16), (short) i }); } if (dataType == 9) { int i = Float.floatToIntBits(value.floatValue()); return (new short[] { (short) i, (short) (i >> 16) }); } if (dataType == 17) { int i = toInt(value); return (new short[] { (short) ((i / 0x989680) % 10 << 12 | (i / 0xf4240) % 10 << 8 | (i / 0x186a0) % 10 << 4 | (i / 10000) % 10), (short) ((i / 1000) % 10 << 12 | (i / 100) % 10 << 8 | (i / 10) % 10 << 4 | i % 10) }); } if (dataType == 10 || dataType == 11) { long l = value.longValue(); return (new short[] { (short) (int) (l >> 48), (short) (int) (l >> 32), (short) (int) (l >> 16), (short) (int) l }); } if (dataType == 12 || dataType == 13) { long l = value.longValue(); return (new short[] { (short) (int) l, (short) (int) (l >> 16), (short) (int) (l >> 32), (short) (int) (l >> 48) }); } if (dataType == 14) { long l = Double.doubleToLongBits(value.doubleValue()); return (new short[] { (short) (int) (l >> 48), (short) (int) (l >> 32), (short) (int) (l >> 16), (short) (int) l }); } if (dataType == 15) { long l = Double.doubleToLongBits(value.doubleValue()); return (new short[] { (short) (int) l, (short) (int) (l >> 16), (short) (int) (l >> 32), (short) (int) (l >> 48) }); } else { throw new RuntimeException( (new StringBuilder()).append("Unsupported data type: ").append(dataType).toString()); } }
From source file:it.drwolf.ridire.index.sketch.AsyncSketchCreator.java
private void processNotTrinaryTable(HashMap<String, SketchResult> sr, String freqTable, long firstFreq, StrTokenizer strTokenizer, List<String> lines) { if (lines != null && lines.size() > 0 && lines.get(0).trim().length() > 0) { // fA = first line Number fA = Long.valueOf(lines.get(0).trim()); for (String l : lines) { String[] tokens = strTokenizer.reset(l).getTokenArray(); if (tokens.length != 2) { continue; }/*from w ww . jav a 2s .c o m*/ String f = tokens[1]; List<Number> fBs = this.entityManager .createNativeQuery("select freq from " + freqTable + " where item=:item") .setParameter("item", f).getResultList(); if (fBs == null || fBs.size() < 1) { continue; } SketchResult res = sr.get(f); if (res == null) { res = new SketchResult(); } long fB = fBs.get(0).longValue(); if (fBs != null && fBs.size() > 0 && fB > 0) { res.setCollocata(f); long n = this.corpusSizeParams.getCorpusSize(freqTable.substring(5)).longValue(); long fAB = Long.parseLong(tokens[0]); double score = this.getSketchScore(CWBCollocatesExtractor.LOGDICE_SCORE, fA.longValue(), fB, fAB, n); res.setScore(score); res.setfA(fA.longValue()); res.setfAB(fAB); res.setfB(fB); sr.put(f, res); } } } }
From source file:org.objectstyle.cayenne.dataview.DataTypeSpec.java
public Object toDataType(DataTypeEnum dataType, Object untypedValue) { Class dataTypeClass = getJavaClass(dataType); if (dataTypeClass == null || untypedValue == null || ClassUtils.isAssignable(untypedValue.getClass(), dataTypeClass)) { if (DataTypeEnum.DATE_TYPE.equals(dataType) && Date.class.equals(dataTypeClass)) { return DateUtils.truncate(untypedValue, Calendar.DATE); }/*from w w w . j a v a 2 s. c om*/ return untypedValue; } Object v = null; String strUntypedValue = null; boolean isStringUntypedValue; Number numUntypedValue = null; boolean isNumberUntypedValue; if (isStringUntypedValue = untypedValue instanceof String) strUntypedValue = (String) untypedValue; if (isNumberUntypedValue = untypedValue instanceof Number) numUntypedValue = (Number) untypedValue; switch (dataType.getValue()) { case DataTypeEnum.BOOLEAN_TYPE_VALUE: if (isNumberUntypedValue) v = BooleanUtils.toBooleanObject(numUntypedValue.intValue()); else if (isStringUntypedValue) v = BooleanUtils.toBooleanObject(strUntypedValue); break; case DataTypeEnum.INTEGER_TYPE_VALUE: if (isNumberUntypedValue) v = new Integer(numUntypedValue.intValue()); else if (isStringUntypedValue) v = NumberUtils.createInteger(strUntypedValue); break; case DataTypeEnum.DOUBLE_TYPE_VALUE: if (isNumberUntypedValue) v = new Double(numUntypedValue.doubleValue()); else if (isStringUntypedValue) v = NumberUtils.createDouble(strUntypedValue); break; case DataTypeEnum.STRING_TYPE_VALUE: v = ObjectUtils.toString(untypedValue); break; case DataTypeEnum.DATE_TYPE_VALUE: if (isNumberUntypedValue) v = DateUtils.truncate(new Date(numUntypedValue.longValue()), Calendar.DATE); break; case DataTypeEnum.DATETIME_TYPE_VALUE: if (isNumberUntypedValue) v = new Date(numUntypedValue.longValue()); break; case DataTypeEnum.MONEY_TYPE_VALUE: if (isNumberUntypedValue) v = new Double(numUntypedValue.doubleValue()); else if (isStringUntypedValue) v = NumberUtils.createDouble(strUntypedValue); break; case DataTypeEnum.PERCENT_TYPE_VALUE: if (isNumberUntypedValue) v = new Double(numUntypedValue.doubleValue()); else if (isStringUntypedValue) v = NumberUtils.createDouble(strUntypedValue); break; } return v; }
From source file:org.openconcerto.erp.core.sales.invoice.component.SaisieVenteFactureSQLComponent.java
private void refreshText() { Number n = this.fieldTTC.getValue(); if (this.selAvoir.getSelectedId() > 1) { SQLTable tableAvoir = Configuration.getInstance().getDirectory().getElement("AVOIR_CLIENT").getTable(); if (n != null) { long ttc = n.longValue(); SQLRow rowAvoir = tableAvoir.getRow(this.selAvoir.getSelectedId()); long totalAvoir = ((Number) rowAvoir.getObject("MONTANT_TTC")).longValue(); totalAvoir -= ((Number) rowAvoir.getObject("MONTANT_SOLDE")).longValue(); if (getSelectedID() > 1) { SQLRow row = getTable().getRow(getSelectedID()); int idAvoirOld = row.getInt("ID_AVOIR_CLIENT"); if (idAvoirOld == rowAvoir.getID()) { totalAvoir += Long.valueOf(row.getObject("T_AVOIR_TTC").toString()); }//from ww w . ja v a2s . c om } long l = ttc - totalAvoir; if (l < 0) { l = 0; this.textAvoirTTC.setValue(ttc); } else { this.textAvoirTTC.setValue(totalAvoir); } this.textTotalAvoir.setValue(l); } else { this.textTotalAvoir.setValue(0l); } } else { if (n != null) { this.textTotalAvoir.setValue(n.longValue()); } else { this.textTotalAvoir.setValue(0l); } this.textAvoirTTC.setValue(0l); } }
From source file:org.mifos.clientportfolio.loan.ui.LoanAccountFormBean.java
@edu.umd.cs.findbugs.annotations.SuppressWarnings(value = { "SIC_INNER_SHOULD_BE_STATIC_ANON" }, justification = "") public void validateEnterAccountDetailsStep(ValidationContext context) { MessageContext messageContext = context.getMessageContext(); Errors errors = validator.checkConstraints(this); // handle data binding errors that may of occurred if (messageContext.hasErrorMessages()) { Message[] errorMessages = messageContext.getMessagesByCriteria(new MessageCriteria() { @Override/* ww w . j a v a 2 s .c o m*/ public boolean test(@SuppressWarnings("unused") Message message) { return true; } }); messageContext.clearMessages(); for (Message message : errorMessages) { handleDataMappingError(errors, message); } } if (this.glimApplicable) { int index = 0; int selectedCount = 0; for (Boolean clientSelected : this.clientSelectForGroup) { if (clientSelected != null && clientSelected.booleanValue()) { Number clientAmount = this.clientAmount[index]; if (clientAmount == null || exceedsMinOrMax(clientAmount, Integer.valueOf(1), this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; rejectGlimClientAmountField(index + 1, errors, defaultErrorMessage); } if (clientAmount != null) { BigDecimal amountAsDecimal = new BigDecimal(clientAmount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsAfterDecimal.invalid", new Object[] { index + 1, this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.client.amount.digitsBeforeDecimal.invalid", new Object[] { index + 1, this.digitsBeforeDecimalForMonetaryAmounts }); } } // check error message of loan purpose for each client when its mandatory.. Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (this.purposeOfLoanMandatory && isInvalidSelection(clientLoanPurposeId)) { errors.rejectValue("clientLoanPurposeId", "loanAccountFormBean.glim.purposeOfLoan.invalid", new Object[] { index + 1 }, "Please specify loan purpose."); this.clientLoanPurposeId[index] = 0; } else { // needed so attempt in freemarker(ftl) to display loan purpose doesnt fall over. if (clientLoanPurposeId == null) { this.clientLoanPurposeId[index] = 0; } } selectedCount++; } else { Number clientAmount = this.clientAmount[index]; Integer clientLoanPurposeId = this.clientLoanPurposeId[index]; if (clientAmount != null || clientLoanPurposeId != null) { String defaultErrorMessage = "You have entered details for a member you have not selected. Select the checkbox in front of the member's name in order to include him or her in the loan."; rejectUnselectedGlimClientAmountField(index + 1, errors, defaultErrorMessage); } } index++; } if (selectedCount < 2) { String defaultErrorMessage = "Not enough clients for group loan."; rejectGroupLoanWithTooFewClients(errors, defaultErrorMessage); } } if (this.amount == null || exceedsMinOrMax(this.amount, this.minAllowedAmount, this.maxAllowedAmount)) { String defaultErrorMessage = "Please specify valid Amount."; if (glimApplicable) { defaultErrorMessage = "The sum of the amounts specified for each member is outside the allowable total amount for this loan product."; rejectGlimTotalAmountField(errors, defaultErrorMessage); } else { rejectAmountField(errors, defaultErrorMessage); } } if (this.amount != null) { BigDecimal amountAsDecimal = new BigDecimal(this.amount.toString()).stripTrailingZeros(); int places = amountAsDecimal.scale(); if (places > this.digitsAfterDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsAfterDecimal.invalid", new Object[] { this.digitsAfterDecimalForMonetaryAmounts }); } int digitsBefore = amountAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForMonetaryAmounts) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.amount.digitsBeforeDecimal.invalid", new Object[] { this.digitsBeforeDecimalForMonetaryAmounts }); } } if (this.interestRate == null || exceedsMinOrMax(this.interestRate, this.minAllowedInterestRate, this.maxAllowedInterestRate)) { String defaultErrorMessage = "Please specify valid Interest rate."; rejectInterestRateField(errors, defaultErrorMessage); } if (this.interestRate != null) { BigDecimal interestRateAsDecimal = new BigDecimal(this.interestRate.toString()).stripTrailingZeros(); int places = interestRateAsDecimal.scale(); if (places > this.digitsAfterDecimalForInterest) { String defaultErrorMessage = "The number of digits after the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsAfterDecimalForInterest.invalid", new Object[] { this.digitsAfterDecimalForInterest }); } int digitsBefore = interestRateAsDecimal.toBigInteger().toString().length(); if (digitsBefore > this.digitsBeforeDecimalForInterest) { String defaultErrorMessage = "The number of digits before the decimal separator exceeds the allowed number."; rejectInterestRateFieldValue(errors, defaultErrorMessage, "loanAccountFormBean.digitsBeforeDecimalForInterest.invalid", new Object[] { this.digitsBeforeDecimalForInterest }); } } if (this.numberOfInstallments == null || exceedsMinOrMax(this.numberOfInstallments, this.minNumberOfInstallments, this.maxNumberOfInstallments)) { String defaultErrorMessage = "Please specify valid number of installments."; rejectNumberOfInstallmentsField(errors, defaultErrorMessage); } if (this.graceDuration == null || this.graceDuration.intValue() < 0) { if (!errors.hasFieldErrors("graceDuration")) { String defaultErrorMessage = "Please specify valid Grace period for repayments. Grace period should be a value less than " + numberOfInstallments.intValue() + "."; rejectGraceDurationField(errors, defaultErrorMessage); } } else { if (this.graceDuration.intValue() > this.maxGraceDuration.intValue()) { String defaultErrorMessage = "The Grace period cannot be greater than in loan product definition."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDuration.invalid", defaultErrorMessage); } if (this.numberOfInstallments != null && (this.graceDuration.intValue() >= this.numberOfInstallments.intValue())) { String defaultErrorMessage = "Grace period for repayments must be less than number of loan installments."; errors.rejectValue("graceDuration", "loanAccountFormBean.gracePeriodDurationInRelationToInstallments.invalid", defaultErrorMessage); } } if (dateValidator == null) { dateValidator = new DateValidator(); } if (!dateValidator.formsValidDate(this.disbursementDateDD, this.disbursementDateMM, this.disbursementDateYY)) { String defaultErrorMessage = "Please specify valid disbursal date."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", "loanAccountFormBean.DisbursalDate.invalid", ""); } else { LocalDate validDate = new DateTime().withDate(disbursementDateYY.intValue(), disbursementDateMM.intValue(), disbursementDateDD.intValue()).toLocalDate(); org.mifos.platform.validations.Errors disbursementDateErrors = new org.mifos.platform.validations.Errors(); if (this.redoLoanAccount) { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanWithBackdatedPaymentsDisbursementDate(validDate, customerId, productId); } else { disbursementDateErrors = loanDisbursementDateValidationServiceFacade .validateLoanDisbursementDate(validDate, customerId, productId); } for (ErrorEntry entry : disbursementDateErrors.getErrorEntries()) { String defaultErrorMessage = "The disbursal date is invalid."; rejectDisbursementDateField(errors, defaultErrorMessage, "disbursementDateDD", entry.getErrorCode(), entry.getArgs().get(0)); } } if (this.sourceOfFundsMandatory && isInvalidSelection(this.fundId)) { errors.rejectValue("fundId", "loanAccountFormBean.SourceOfFunds.invalid", "Please specify source of funds."); } if (this.externalIdMandatory && StringUtils.isBlank(this.externalId)) { errors.rejectValue("externalId", "loanAccountFormBean.externalid.invalid", "Please specify required external id."); } if (!this.glimApplicable && this.purposeOfLoanMandatory && isInvalidSelection(this.loanPurposeId)) { errors.rejectValue("loanPurposeId", "loanAccountFormBean.PurposeOfLoan.invalid", "Please specify loan purpose."); } validateAdministrativeAndAdditionalFees(errors); if (this.repaymentScheduleIndependentOfCustomerMeeting) { if (isInvalidRecurringFrequency(this.repaymentRecursEvery)) { errors.rejectValue("repaymentRecursEvery", "loanAccountFormBean.repaymentDay.recursEvery.invalid", "Please specify a valid recurring frequency for repayment day."); } if (this.weekly) { if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.weekly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } else if (this.monthly) { if (this.monthlyDayOfMonthOptionSelected) { if (isInvalidDayOfMonthEntered()) { errors.rejectValue("repaymentDayOfMonth", "loanAccountFormBean.repaymentDay.monthly.dayOfMonth.invalid", "Please select a day of the month for repayment day."); } } else if (this.monthlyWeekOfMonthOptionSelected) { if (isInvalidWeekOfMonthSelection()) { errors.rejectValue("repaymentWeekOfMonth", "loanAccountFormBean.repaymentDay.monthly.weekOfMonth.invalid", "Please select a week of the month for repayment day."); } if (isInvalidDayOfWeekSelection()) { errors.rejectValue("repaymentDayOfWeek", "loanAccountFormBean.repaymentDay.monthly.dayOfWeek.invalid", "Please select a day of the week for repayment day."); } } } if (this.variableInstallmentsAllowed) { if (this.selectedFeeId != null) { for (Number feeId : this.selectedFeeId) { if (feeId != null) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.additionalfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } } int defaultFeeIndex = 0; if (this.defaultFeeId != null) { for (Number feeId : this.defaultFeeId) { if (feeId != null) { Boolean feeSelectedForRemoval = this.defaultFeeSelected[defaultFeeIndex]; if (feeSelectedForRemoval == null || !feeSelectedForRemoval) { VariableInstallmentWithFeeValidationResult result = variableInstallmentsFeeValidationServiceFacade .validateFeeCanBeAppliedToVariableInstallmentLoan(feeId.longValue()); if (!result.isFeeCanBeAppliedToVariableInstallmentLoan()) { errors.rejectValue("selectedFeeId", "loanAccountFormBean.defaultfees.variableinstallments.invalid", new String[] { result.getFeeName() }, "This type of fee cannot be applied to loan with variable installments."); } } } defaultFeeIndex++; } } } } if (errors.hasErrors()) { for (FieldError fieldError : errors.getFieldErrors()) { MessageBuilder builder = new MessageBuilder().error().source(fieldError.getField()) .codes(fieldError.getCodes()).defaultText(fieldError.getDefaultMessage()) .args(fieldError.getArguments()); messageContext.addMessage(builder.build()); } } }
From source file:org.sakaiproject.sitestats.impl.chart.ChartServiceImpl.java
private Number getTotalValue(Number existingValue, Stat s, Report r) { try {/*from w ww .j ava2 s . co m*/ String what = r.getReportDefinition().getReportParams().getWhat(); if (ReportManager.WHAT_VISITS_TOTALS.equals(what)) { if (s instanceof SiteVisits) { long totalVisits = ((SiteVisits) s).getTotalVisits(); if (existingValue != null) { totalVisits += existingValue.longValue(); } return totalVisits; } } else if (ReportManager.WHAT_PRESENCES.equals(what)) { if (s instanceof SitePresence) { double duration = (double) ((SitePresence) s).getDuration(); duration = Util.round(duration / 1000 / 60, 1); // in minutes if (existingValue != null) { duration += existingValue.doubleValue(); } return duration; } } long count = s.getCount(); if (existingValue != null) { count += existingValue.longValue(); } return count; } catch (Exception e) { LOG.warn("Error occurred while getting total value for chart", e); } return null; }
From source file:com.cinchapi.concourse.util.ConvertTest.java
@Test public void testConvertLinkFromLongValue() { // A int/long that is wrapped between two at (@) symbols must always // convert to a Link Number number = Random.getLong(); String value = MessageFormat.format("{0}{1}", "@", number.toString()); // must // use // number.toString() // so // comma // separators // are // not // added // to // the // output Link link = (Link) Convert.stringToJava(value); Assert.assertEquals(number.longValue(), link.longValue()); }
From source file:com.imaginary.home.cloud.api.RestApi.java
public @Nonnull String generateToken(@Nonnull String method, @Nonnull HttpServletRequest request, Map<String, Object> headers) throws RestException { Number timestamp = (Number) headers.get(TIMESTAMP); String apiKey = (String) headers.get(API_KEY); String signature = (String) headers.get(SIGNATURE); String version = (String) headers.get(VERSION); if (timestamp == null || apiKey == null || signature == null || version == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, "Incomplete authentication headers, requires: " + API_KEY + " - " + TIMESTAMP + " - " + SIGNATURE + " - " + VERSION); }/*from ww w . ja v a 2 s . c om*/ if (signature.length() < 1) { throw new RestException(HttpServletResponse.SC_FORBIDDEN, "No signature was provided for authentication"); } try { ControllerRelay relay = ControllerRelay.getRelay(apiKey); String secret, customSalt; if (relay == null) { throw new RestException(HttpServletResponse.SC_BAD_REQUEST, RestException.BAD_TOKEN, "User keys don't use token authentication"); } else { secret = relay.getApiKeySecret(); customSalt = relay.getLocationId(); } String stringToSign = method.toLowerCase() + ":" + request.getPathInfo().toLowerCase() + ":" + apiKey + ":" + timestamp.longValue() + ":" + version; String expected; try { expected = CloudService.sign(Configuration.decrypt(customSalt, secret).getBytes("utf-8"), stringToSign); } catch (Exception e) { throw new RestException(e); } if (signature.equals(expected)) { String token = Configuration.generateToken(40, 60); relay.setToken(token); return token; } throw new RestException(HttpServletResponse.SC_FORBIDDEN, "Illegal Access", "Illegal access to requested resource"); } catch (PersistenceException e) { throw new RestException(e); } }