Example usage for java.math BigDecimal longValue

List of usage examples for java.math BigDecimal longValue

Introduction

In this page you can find the example usage for java.math BigDecimal longValue.

Prototype

@Override
public long longValue() 

Source Link

Document

Converts this BigDecimal to a long .

Usage

From source file:petascope.wcps2.util.CrsComputer.java

/**
 * Returns the translated subset for regular axis
 *
 * @param numericSubset the numeric subset to be translated
 * @return//from  www .  j a  v a2  s .  c  o  m
 */
private Interval<Long> getNumericPixelIndicesForRegularAxis(Interval<Double> numericSubset) {
    boolean zeroIsMin = coverage.getCoverageMetadata().getDomainDirectionalResolution(axisName)
            .doubleValue() > 0;
    DomainElement dom = coverage.getCoverageInfo().getDomainByName(axisName);
    CellDomainElement cdom = coverage.getCoverageInfo().getCellDomainByName(axisName);
    String axisUoM = dom.getUom();
    // Get Domain extremes (real sdom)
    BigDecimal domMin = dom.getMinValue();
    BigDecimal domMax = dom.getMaxValue();

    long pxMin = cdom.getLoInt();
    long pxMax = cdom.getHiInt();

    // Indexed CRSs do not require conversion
    if (crsName == CrsUtil.GRID_CRS) {
        return new Interval<Long>((long) numericSubset.getLowerLimit().doubleValue(),
                (long) numericSubset.getUpperLimit().doubleValue());
    }

    // This part is copied over from CRSUtil.java verbatim TODO: refactor the whole CRS computer ASAP
    // Indexed CRSs (integer "GridSpacing" UoM): no need for math proportion, coords are just int offsets.
    // This is not the same as CRS:1 which access direct grid coordinates.
    // Index CRSs have indexed coordinates, but still offset vectors can determine a different reference (eg origin is UL corner).
    if (axisUoM.equals(CrsUtil.INDEX_UOM)) {
        int count = 0;
        long indexMin = cdom.getLoInt();
        long indexMax = cdom.getHiInt();
        // S = subset value, px_s = subset grid index
        // m = min(grid index), M = max(grid index)
        // {isPositiveForwards / isNegativeForwards}
        // Formula : px_s = grid_origin + [{S/M} - {m/S}]
        long[] subsetGridIndexes = new long[2];
        for (String subset : (Arrays.asList(new String[] { numericSubset.getLowerLimit().toString(),
                numericSubset.getUpperLimit().toString() }))) {
            // NOTE: on subsets.lo the /next/ integer needs to be taken : trunc(stringLo) + 1 (if it is not exact integer)
            boolean roundUp = subset.equals(numericSubset.getLowerLimit().toString())
                    && ((double) Double.parseDouble(subset) != (long) Double.parseDouble(subset));
            long hiBound = dom.isPositiveForwards() ? (long) Double.parseDouble(subset) + (roundUp ? 1 : 0)
                    : indexMax;
            long loBound = dom.isPositiveForwards() ? indexMin
                    : (long) Double.parseDouble(subset) + (roundUp ? 1 : 0);
            subsetGridIndexes[count] = domMin.longValue() + (hiBound - loBound);
            count += 1;
        }
        // if offset is negative, the limits are inverted
        if (subsetGridIndexes[0] > subsetGridIndexes[1]) {
            return new Interval<Long>(subsetGridIndexes[1], subsetGridIndexes[0]);
        }
        return new Interval<Long>(subsetGridIndexes[0], subsetGridIndexes[1]);
    }

    BigDecimal cellWidth = (domMax.subtract(domMin))
            .divide((BigDecimal.valueOf(pxMax + 1)).subtract(BigDecimal.valueOf(pxMin)), RoundingMode.UP);

    // Open interval on the right: take away epsilon from upper bound:

    long returnLowerLimit, returnUpperLimit;
    if (zeroIsMin) {
        // Normal linear numerical axis
        returnLowerLimit = (long) Math.floor(BigDecimalUtil
                .divide(BigDecimal.valueOf(numericSubset.getLowerLimit()).subtract(domMin), cellWidth)
                .doubleValue()) + pxMin;
        if (numericSubset.getUpperLimit().equals(numericSubset.getLowerLimit())) {
            returnUpperLimit = returnLowerLimit;
        } else {
            returnUpperLimit = (long) Math.ceil(BigDecimalUtil
                    .divide(BigDecimal.valueOf(numericSubset.getUpperLimit()).subtract(domMin), cellWidth)
                    .doubleValue()) - 1 + pxMin;
        }
        // NOTE: the if a slice equals the upper bound of a coverage, out[0]=pxHi+1 but still it is a valid subset.
        if (numericSubset.getLowerLimit() == numericSubset.getUpperLimit()
                && numericSubset.getUpperLimit() == domMax.doubleValue()) {
            returnLowerLimit = returnLowerLimit - 1;
        }
    } else {
        // Linear negative axis (eg northing of georeferenced images)
        // First coordHi, so that left-hand index is the lower one
        returnLowerLimit = (long) Math.ceil(BigDecimalUtil
                .divide(domMax.subtract(BigDecimal.valueOf(numericSubset.getUpperLimit())), cellWidth)
                .doubleValue()) + pxMin;
        if (numericSubset.getUpperLimit() == numericSubset.getLowerLimit()) {
            returnUpperLimit = returnLowerLimit;
        } else {
            returnUpperLimit = (long) Math.floor(BigDecimalUtil
                    .divide(domMax.subtract(BigDecimal.valueOf(numericSubset.getLowerLimit())), cellWidth)
                    .doubleValue()) - 1 + pxMin;
        }
        // NOTE: the if a slice equals the lower bound of a coverage, out[0]=pxHi+1 but still it is a valid subset.
        if (numericSubset.getLowerLimit() == numericSubset.getUpperLimit()
                && numericSubset.getUpperLimit() == domMin.doubleValue()) {
            returnLowerLimit -= 1;
        }
    }
    return new Interval<Long>(returnLowerLimit, returnUpperLimit);
}

From source file:org.plasma.sdo.helper.DataConverter.java

public Object fromDecimal(Type targetType, BigDecimal value) {
    DataType targetDataType = DataType.valueOf(targetType.getName());
    switch (targetDataType) {
    case Decimal:
        return value;
    case Double:
        return new Double(value.doubleValue());
    case Float:
        return new Float(value.floatValue());
    case Int://from w w w  .  j  a  v a2s . c  o m
        return new Integer(value.intValue());
    case Long:
        return new Long(value.longValue());
    case Integer:
        return value.toBigInteger();
    case String:
        // as per spec: ('+'|'-')? [0-9]* ('.'[0-9]*)? (('E'|'e') ('+'|'-')? [0-9]+)?
        /*
         *  [123,0]      "123"
         *   [-123,0]     "-123"
         *   [123,-1]     "1.23E+3"
         *   [123,-3]     "1.23E+5"
         *   [123,1]      "12.3"
         *   [123,5]      "0.00123"
         *   [123,10]     "1.23E-8"
         *   [-123,12]    "-1.23E-10"
         */
        return value.toString();
    default:
        throw new InvalidDataConversionException(targetDataType, DataType.Decimal, value);
    }
}

From source file:org.egov.pgr.elasticsearch.service.ComplaintIndexService.java

private void callStatusAndRatingCount(Terms callStatTerms, IVRSFeedBackResponse feedbackResponse) {
    BigDecimal notRespondedCount = ZERO;
    for (Bucket callStatBucket : callStatTerms.getBuckets()) {
        if (RESPONDED_WITH_FEEDBACK == callStatBucket.getKeyAsNumber().intValue()
                || RESPONDED_WITH_REPEAT_FEEDBACK == callStatBucket.getKeyAsNumber().intValue()) {
            feedbackResponse.setResponded(callStatBucket.getDocCount());
            Terms countTerms = callStatBucket.getAggregations().get("countAggr");
            for (Bucket countBucket : countTerms.getBuckets())
                getDifferentRatingCounts(feedbackResponse, countBucket);
        } else/*from  w w w.j  a  v a 2 s .  c  om*/
            notRespondedCount = notRespondedCount.add(BigDecimal.valueOf(callStatBucket.getDocCount()));
    }
    feedbackResponse.setNotResponded(notRespondedCount.longValue());
}

From source file:org.openhab.binding.netatmo.internal.NetatmoBinding.java

/**
 * {@inheritDoc}//from w ww  .  ja va 2 s. c o  m
 */
@SuppressWarnings("incomplete-switch")
@Override
protected void execute() {
    logger.debug("Querying Netatmo API");
    for (String userid : credentialsCache.keySet()) {

        OAuthCredentials oauthCredentials = getOAuthCredentials(userid);
        if (oauthCredentials.noAccessToken()) {
            // initial run after a restart, so get an access token first
            oauthCredentials.refreshAccessToken();
        }

        try {
            if (oauthCredentials.firstExecution) {
                processGetStationsData(oauthCredentials);
            }

            DeviceMeasureValueMap deviceMeasureValueMap = processMeasurements(oauthCredentials);
            if (deviceMeasureValueMap == null) {
                return;
            }

            for (final NetatmoBindingProvider provider : this.providers) {
                for (final String itemName : provider.getItemNames()) {
                    final String deviceId = provider.getDeviceId(itemName);
                    final String moduleId = provider.getModuleId(itemName);
                    final NetatmoMeasureType measureType = provider.getMeasureType(itemName);
                    final NetatmoScale scale = provider.getNetatmoScale(itemName);

                    State state = null;
                    switch (measureType) {
                    case MODULENAME:
                        if (moduleId == null) // we're on the main device
                            for (Device device : oauthCredentials.getStationsDataResponse.getDevices()) {
                                if (device.getId().equals(deviceId)) {
                                    state = new StringType(device.getModuleName());
                                    break;
                                }
                            }
                        else {
                            for (Device device : oauthCredentials.getStationsDataResponse.getDevices()) {
                                for (Module module : device.getModules()) {
                                    if (module.getId().equals(moduleId)) {
                                        state = new StringType(module.getModuleName());
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    case TIMESTAMP:
                        state = deviceMeasureValueMap.timeStamp;
                        break;
                    case TEMPERATURE:
                    case CO2:
                    case HUMIDITY:
                    case NOISE:
                    case PRESSURE:
                    case RAIN:
                    case MIN_TEMP:
                    case MAX_TEMP:
                    case MIN_HUM:
                    case MAX_HUM:
                    case MIN_PRESSURE:
                    case MAX_PRESSURE:
                    case MIN_NOISE:
                    case MAX_NOISE:
                    case MIN_CO2:
                    case MAX_CO2:
                    case SUM_RAIN:
                    case WINDSTRENGTH:
                    case WINDANGLE:
                    case GUSTSTRENGTH:
                    case GUSTANGLE: {
                        BigDecimal value = getValue(deviceMeasureValueMap, measureType,
                                createKey(deviceId, moduleId, scale));
                        // Protect that sometimes Netatmo returns null where
                        // numeric value is awaited (issue #1848)
                        if (value != null) {
                            if (NetatmoMeasureType.isTemperature(measureType)) {
                                value = unitSystem.convertTemp(value);
                            } else if (NetatmoMeasureType.isRain(measureType)) {
                                value = unitSystem.convertRain(value);
                            } else if (NetatmoMeasureType.isPressure(measureType)) {
                                value = pressureUnit.convertPressure(value);
                            } else if (NetatmoMeasureType.isWind(measureType)) {
                                value = unitSystem.convertWind(value);
                            }

                            state = new DecimalType(value);
                        }
                    }
                        break;
                    case DATE_MIN_TEMP:
                    case DATE_MAX_TEMP:
                    case DATE_MIN_HUM:
                    case DATE_MAX_HUM:
                    case DATE_MIN_PRESSURE:
                    case DATE_MAX_PRESSURE:
                    case DATE_MIN_NOISE:
                    case DATE_MAX_NOISE:
                    case DATE_MIN_CO2:
                    case DATE_MAX_CO2:
                    case DATE_MAX_GUST: {
                        final BigDecimal value = getValue(deviceMeasureValueMap, measureType,
                                createKey(deviceId, moduleId, scale));
                        if (value != null) {
                            final Calendar calendar = GregorianCalendar.getInstance();
                            calendar.setTimeInMillis(value.longValue() * 1000);

                            state = new DateTimeType(calendar);
                        }
                    }
                        break;
                    case BATTERYVP:
                    case RFSTATUS:
                        for (Device device : oauthCredentials.getStationsDataResponse.getDevices()) {
                            for (Module module : device.getModules()) {
                                if (module.getId().equals(moduleId)) {
                                    switch (measureType) {
                                    case BATTERYVP:
                                        state = new DecimalType(module.getBatteryLevel());
                                        break;
                                    case RFSTATUS:
                                        state = new DecimalType(module.getRfLevel());
                                        break;
                                    case MODULENAME:
                                        state = new StringType(module.getModuleName());
                                        break;
                                    }
                                }
                            }
                        }
                        break;
                    case ALTITUDE:
                    case LATITUDE:
                    case LONGITUDE:
                    case WIFISTATUS:
                    case COORDINATE:
                    case STATIONNAME:
                        for (Device device : oauthCredentials.getStationsDataResponse.getDevices()) {
                            if (stationPosition == null) {
                                DecimalType altitude = DecimalType.ZERO;
                                if (device.getAltitude() != null) {
                                    altitude = new DecimalType(
                                            Math.round(unitSystem.convertAltitude(device.getAltitude())));
                                }
                                stationPosition = new PointType(
                                        new DecimalType(new BigDecimal(device.getLatitude()).setScale(6,
                                                BigDecimal.ROUND_HALF_UP)),
                                        new DecimalType(new BigDecimal(device.getLongitude()).setScale(6,
                                                BigDecimal.ROUND_HALF_UP)),
                                        altitude);
                            }
                            if (device.getId().equals(deviceId)) {
                                switch (measureType) {
                                case LATITUDE:
                                    state = stationPosition.getLatitude();
                                    break;
                                case LONGITUDE:
                                    state = stationPosition.getLongitude();
                                    break;
                                case ALTITUDE:
                                    state = stationPosition.getAltitude();
                                    break;
                                case WIFISTATUS:
                                    state = new DecimalType(device.getWifiLevel());
                                    break;
                                case COORDINATE:
                                    state = stationPosition;
                                    break;
                                case STATIONNAME:
                                    state = new StringType(device.getStationName());
                                    break;
                                }
                            }
                        }
                        break;
                    }

                    if (state != null) {
                        this.eventPublisher.postUpdate(itemName, state);
                    }
                }
            }
        } catch (NetatmoException ne) {
            logger.error(ne.getMessage());
        }
    }
}

From source file:mx.edu.um.mateo.activos.dao.impl.ActivoDaoHibernate.java

@Override
@SuppressWarnings("unchecked")
public void sube(byte[] datos, Usuario usuario, OutputStream out, Integer codigoInicial) {
    Date inicio = new Date();
    int idx = 5;//from  w  ww  .j a  va  2 s .  c o m
    int i = 0;
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yy");
    SimpleDateFormat sdf3 = new SimpleDateFormat("dd-MM-yy");

    MathContext mc = new MathContext(16, RoundingMode.HALF_UP);
    NumberFormat nf = NumberFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMaximumFractionDigits(0);
    nf.setMinimumIntegerDigits(5);

    Transaction tx = null;
    try {
        String ejercicioId = "001-2012";
        Map<String, CentroCosto> centrosDeCosto = new HashMap<>();
        Map<String, TipoActivo> tipos = new HashMap<>();
        Query tipoActivoQuery = currentSession()
                .createQuery("select ta from TipoActivo ta " + "where ta.empresa.id = :empresaId "
                        + "and ta.cuenta.id.ejercicio.id.idEjercicio = :ejercicioId "
                        + "and ta.cuenta.id.ejercicio.id.organizacion.id = :organizacionId");
        log.debug("empresaId: {}", usuario.getEmpresa().getId());
        log.debug("ejercicioId: {}", ejercicioId);
        log.debug("organizacionId: {}", usuario.getEmpresa().getOrganizacion().getId());
        tipoActivoQuery.setLong("empresaId", usuario.getEmpresa().getId());
        tipoActivoQuery.setString("ejercicioId", ejercicioId);
        tipoActivoQuery.setLong("organizacionId", usuario.getEmpresa().getOrganizacion().getId());
        List<TipoActivo> listaTipos = tipoActivoQuery.list();
        for (TipoActivo tipoActivo : listaTipos) {
            tipos.put(tipoActivo.getCuenta().getId().getIdCtaMayor(), tipoActivo);
        }
        log.debug("TIPOS: {}", tipos);

        Query proveedorQuery = currentSession().createQuery(
                "select p from Proveedor p where p.empresa.id = :empresaId and p.nombre = :nombreEmpresa");
        proveedorQuery.setLong("empresaId", usuario.getEmpresa().getId());
        proveedorQuery.setString("nombreEmpresa", usuario.getEmpresa().getNombre());
        Proveedor proveedor = (Proveedor) proveedorQuery.uniqueResult();

        Query codigoDuplicadoQuery = currentSession()
                .createQuery("select a from Activo a where a.empresa.id = :empresaId and a.codigo = :codigo");

        XSSFWorkbook workbook = new XSSFWorkbook(new ByteArrayInputStream(datos));
        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();

        XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet ccostoFantasma = wb.createSheet("CCOSTO-FANTASMAS");
        int ccostoFantasmaRow = 0;
        XSSFSheet sinCCosto = wb.createSheet("SIN-CCOSTO");
        int sinCCostoRow = 0;
        XSSFSheet codigoAsignado = wb.createSheet("CODIGO-ASIGNADO");
        int codigoAsignadoRow = 0;
        XSSFSheet fechaInvalida = wb.createSheet("FECHA-INVALIDA");
        int fechaInvalidaRow = 0;
        XSSFSheet sinCosto = wb.createSheet("SIN-COSTO");
        int sinCostoRow = 0;

        tx = currentSession().beginTransaction();
        for (idx = 0; idx <= 5; idx++) {
            XSSFSheet sheet = workbook.getSheetAt(idx);

            int rows = sheet.getPhysicalNumberOfRows();
            for (i = 2; i < rows; i++) {
                log.debug("Leyendo pagina {} renglon {}", idx, i);
                XSSFRow row = sheet.getRow(i);
                if (row.getCell(0) == null) {
                    break;
                }
                String nombreGrupo = row.getCell(0).getStringCellValue().trim();
                TipoActivo tipoActivo = tipos.get(nombreGrupo);
                if (tipoActivo != null) {
                    String cuentaCCosto = row.getCell(2).toString().trim();
                    if (StringUtils.isNotBlank(cuentaCCosto)) {
                        CentroCosto centroCosto = centrosDeCosto.get(cuentaCCosto);
                        if (centroCosto == null) {
                            Query ccostoQuery = currentSession().createQuery("select cc from CentroCosto cc "
                                    + "where cc.id.ejercicio.id.idEjercicio = :ejercicioId "
                                    + "and cc.id.ejercicio.id.organizacion.id = :organizacionId "
                                    + "and cc.id.idCosto like :idCosto");
                            ccostoQuery.setString("ejercicioId", ejercicioId);
                            ccostoQuery.setLong("organizacionId",
                                    usuario.getEmpresa().getOrganizacion().getId());
                            ccostoQuery.setString("idCosto", "1.01." + cuentaCCosto);
                            ccostoQuery.setMaxResults(1);
                            List<CentroCosto> listaCCosto = ccostoQuery.list();
                            if (listaCCosto != null && listaCCosto.size() > 0) {
                                centroCosto = listaCCosto.get(0);
                            }
                            if (centroCosto == null) {
                                XSSFRow renglon = ccostoFantasma.createRow(ccostoFantasmaRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(row.getCell(8).toString());
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                continue;
                            }
                            centrosDeCosto.put(cuentaCCosto, centroCosto);
                        }
                        String poliza = null;
                        switch (row.getCell(4).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            poliza = row.getCell(4).toString();
                            poliza = StringUtils.removeEnd(poliza, ".0");
                            log.debug("POLIZA-N: {}", poliza);
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            poliza = row.getCell(4).getStringCellValue().trim();
                            log.debug("POLIZA-S: {}", poliza);
                            break;
                        }
                        Boolean seguro = false;
                        if (row.getCell(5) != null && StringUtils.isNotBlank(row.getCell(5).toString())) {
                            seguro = true;
                        }
                        Boolean garantia = false;
                        if (row.getCell(6) != null && StringUtils.isNotBlank(row.getCell(6).toString())) {
                            garantia = true;
                        }
                        Date fechaCompra = null;
                        if (row.getCell(7) != null) {
                            log.debug("VALIDANDO FECHA");
                            XSSFCell cell = row.getCell(7);
                            switch (cell.getCellType()) {
                            case Cell.CELL_TYPE_NUMERIC:
                                log.debug("ES NUMERIC");
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    log.debug("ES FECHA");
                                    fechaCompra = cell.getDateCellValue();
                                } else if (DateUtil.isCellInternalDateFormatted(cell)) {
                                    log.debug("ES FECHA INTERNAL");
                                    fechaCompra = cell.getDateCellValue();
                                } else {
                                    BigDecimal bd = new BigDecimal(cell.getNumericCellValue());
                                    bd = stripTrailingZeros(bd);

                                    log.debug("CONVIRTIENDO DOUBLE {} - {}",
                                            DateUtil.isValidExcelDate(bd.doubleValue()), bd);
                                    fechaCompra = HSSFDateUtil.getJavaDate(bd.longValue(), true);
                                    log.debug("Cal: {}", fechaCompra);
                                }
                                break;
                            case Cell.CELL_TYPE_FORMULA:
                                log.debug("ES FORMULA");
                                CellValue cellValue = evaluator.evaluate(cell);
                                switch (cellValue.getCellType()) {
                                case Cell.CELL_TYPE_NUMERIC:
                                    if (DateUtil.isCellDateFormatted(cell)) {
                                        fechaCompra = DateUtil.getJavaDate(cellValue.getNumberValue(), true);
                                    }
                                }
                            }
                        }
                        if (row.getCell(7) != null && fechaCompra == null) {
                            String fechaCompraString;
                            if (row.getCell(7).getCellType() == Cell.CELL_TYPE_STRING) {
                                fechaCompraString = row.getCell(7).getStringCellValue();
                            } else {
                                fechaCompraString = row.getCell(7).toString().trim();
                            }
                            try {
                                fechaCompra = sdf.parse(fechaCompraString);
                            } catch (ParseException e) {
                                try {
                                    fechaCompra = sdf2.parse(fechaCompraString);
                                } catch (ParseException e2) {
                                    try {
                                        fechaCompra = sdf3.parse(fechaCompraString);
                                    } catch (ParseException e3) {
                                        // no se pudo convertir
                                    }
                                }
                            }
                        }

                        if (fechaCompra == null) {
                            XSSFRow renglon = fechaInvalida.createRow(fechaInvalidaRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        String codigo = null;
                        switch (row.getCell(8).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            codigo = row.getCell(8).toString();
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            codigo = row.getCell(8).getStringCellValue().trim();
                            break;
                        }
                        if (StringUtils.isBlank(codigo)) {
                            codigo = nf.format(codigoInicial);
                            XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(codigoInicial);
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            codigoInicial++;
                        } else {
                            // busca codigo duplicado
                            if (codigo.contains(".")) {
                                codigo = codigo.substring(0, codigo.lastIndexOf("."));
                                log.debug("CODIGO: {}", codigo);
                            }

                            codigoDuplicadoQuery.setLong("empresaId", usuario.getEmpresa().getId());
                            codigoDuplicadoQuery.setString("codigo", codigo);
                            Activo activo = (Activo) codigoDuplicadoQuery.uniqueResult();
                            if (activo != null) {
                                XSSFRow renglon = codigoAsignado.createRow(codigoAsignadoRow++);
                                renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                                renglon.createCell(1).setCellValue(row.getCell(0).toString());
                                renglon.createCell(2).setCellValue(row.getCell(1).toString());
                                renglon.createCell(3).setCellValue(row.getCell(2).toString());
                                renglon.createCell(4).setCellValue(row.getCell(3).toString());
                                renglon.createCell(5).setCellValue(row.getCell(4).toString());
                                renglon.createCell(6).setCellValue(row.getCell(5).toString());
                                renglon.createCell(7).setCellValue(row.getCell(6).toString());
                                renglon.createCell(8).setCellValue(row.getCell(7).toString());
                                renglon.createCell(9).setCellValue(codigo + "-" + nf.format(codigoInicial));
                                renglon.createCell(10).setCellValue(row.getCell(9).toString());
                                renglon.createCell(11).setCellValue(row.getCell(10).toString());
                                renglon.createCell(12).setCellValue(row.getCell(11).toString());
                                renglon.createCell(13).setCellValue(row.getCell(12).toString());
                                renglon.createCell(14).setCellValue(row.getCell(13).toString());
                                renglon.createCell(15).setCellValue(row.getCell(14).toString());
                                renglon.createCell(16).setCellValue(row.getCell(15).toString());
                                codigo = nf.format(codigoInicial);
                                codigoInicial++;
                            }
                        }
                        String descripcion = null;
                        if (row.getCell(9) != null) {
                            switch (row.getCell(9).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                descripcion = row.getCell(9).toString();
                                descripcion = StringUtils.removeEnd(descripcion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                descripcion = row.getCell(9).getStringCellValue().trim();
                                break;
                            default:
                                descripcion = row.getCell(9).toString().trim();
                            }
                        }
                        String marca = null;
                        if (row.getCell(10) != null) {
                            switch (row.getCell(10).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                marca = row.getCell(10).toString();
                                marca = StringUtils.removeEnd(marca, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                marca = row.getCell(10).getStringCellValue().trim();
                                break;
                            default:
                                marca = row.getCell(10).toString().trim();
                            }
                        }
                        String modelo = null;
                        if (row.getCell(11) != null) {
                            switch (row.getCell(11).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                modelo = row.getCell(11).toString();
                                modelo = StringUtils.removeEnd(modelo, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                modelo = row.getCell(11).getStringCellValue().trim();
                                break;
                            default:
                                modelo = row.getCell(11).toString().trim();
                            }
                        }
                        String serie = null;
                        if (row.getCell(12) != null) {
                            switch (row.getCell(12).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                serie = row.getCell(12).toString();
                                serie = StringUtils.removeEnd(serie, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                serie = row.getCell(12).getStringCellValue().trim();
                                break;
                            default:
                                serie = row.getCell(12).toString().trim();
                            }
                        }
                        String responsable = null;
                        if (row.getCell(13) != null) {
                            switch (row.getCell(13).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                responsable = row.getCell(13).toString();
                                responsable = StringUtils.removeEnd(responsable, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                responsable = row.getCell(13).getStringCellValue().trim();
                                break;
                            default:
                                responsable = row.getCell(13).toString().trim();
                            }
                        }

                        String ubicacion = null;
                        if (row.getCell(14) != null) {
                            switch (row.getCell(14).getCellType()) {
                            case XSSFCell.CELL_TYPE_NUMERIC:
                                ubicacion = row.getCell(14).toString();
                                ubicacion = StringUtils.removeEnd(ubicacion, ".0");
                                break;
                            case XSSFCell.CELL_TYPE_STRING:
                                ubicacion = row.getCell(14).getStringCellValue().trim();
                                break;
                            default:
                                ubicacion = row.getCell(14).toString().trim();
                            }
                        }
                        BigDecimal costo = null;
                        switch (row.getCell(15).getCellType()) {
                        case XSSFCell.CELL_TYPE_NUMERIC:
                            costo = new BigDecimal(row.getCell(15).getNumericCellValue(), mc);
                            log.debug("COSTO-N: {} - {}", costo, row.getCell(15).getNumericCellValue());
                            break;
                        case XSSFCell.CELL_TYPE_STRING:
                            costo = new BigDecimal(row.getCell(15).toString(), mc);
                            log.debug("COSTO-S: {} - {}", costo, row.getCell(15).toString());
                            break;
                        case XSSFCell.CELL_TYPE_FORMULA:
                            costo = new BigDecimal(
                                    evaluator.evaluateInCell(row.getCell(15)).getNumericCellValue(), mc);
                            log.debug("COSTO-F: {}", costo);
                        }
                        if (costo == null) {
                            XSSFRow renglon = sinCosto.createRow(sinCostoRow++);
                            renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                            renglon.createCell(1).setCellValue(row.getCell(0).toString());
                            renglon.createCell(2).setCellValue(row.getCell(1).toString());
                            renglon.createCell(3).setCellValue(row.getCell(2).toString());
                            renglon.createCell(4).setCellValue(row.getCell(3).toString());
                            renglon.createCell(5).setCellValue(row.getCell(4).toString());
                            renglon.createCell(6).setCellValue(row.getCell(5).toString());
                            renglon.createCell(7).setCellValue(row.getCell(6).toString());
                            renglon.createCell(8).setCellValue(row.getCell(7).toString());
                            renglon.createCell(9).setCellValue(row.getCell(8).toString());
                            renglon.createCell(10).setCellValue(row.getCell(9).toString());
                            renglon.createCell(11).setCellValue(row.getCell(10).toString());
                            renglon.createCell(12).setCellValue(row.getCell(11).toString());
                            renglon.createCell(13).setCellValue(row.getCell(12).toString());
                            renglon.createCell(14).setCellValue(row.getCell(13).toString());
                            renglon.createCell(15).setCellValue(row.getCell(14).toString());
                            renglon.createCell(16).setCellValue(row.getCell(15).toString());
                            continue;
                        }

                        Activo activo = new Activo(fechaCompra, seguro, garantia, poliza, codigo, descripcion,
                                marca, modelo, serie, responsable, ubicacion, costo, tipoActivo, centroCosto,
                                proveedor, usuario.getEmpresa());
                        this.crea(activo, usuario);

                    } else {
                        XSSFRow renglon = sinCCosto.createRow(sinCCostoRow++);
                        renglon.createCell(0).setCellValue(sheet.getSheetName() + ":" + (i + 1));
                        renglon.createCell(1).setCellValue(row.getCell(0).toString());
                        renglon.createCell(2).setCellValue(row.getCell(1).toString());
                        renglon.createCell(3).setCellValue(row.getCell(2).toString());
                        renglon.createCell(4).setCellValue(row.getCell(3).toString());
                        renglon.createCell(5).setCellValue(row.getCell(4).toString());
                        renglon.createCell(6).setCellValue(row.getCell(5).toString());
                        renglon.createCell(7).setCellValue(row.getCell(6).toString());
                        renglon.createCell(8).setCellValue(row.getCell(7).toString());
                        renglon.createCell(9).setCellValue(row.getCell(8).toString());
                        renglon.createCell(10).setCellValue(row.getCell(9).toString());
                        renglon.createCell(11).setCellValue(row.getCell(10).toString());
                        renglon.createCell(12).setCellValue(row.getCell(11).toString());
                        renglon.createCell(13).setCellValue(row.getCell(12).toString());
                        renglon.createCell(14).setCellValue(row.getCell(13).toString());
                        renglon.createCell(15).setCellValue(row.getCell(14).toString());
                        renglon.createCell(16).setCellValue(row.getCell(15).toString());
                        continue;
                    }
                } else {
                    throw new RuntimeException(
                            "(" + idx + ":" + i + ") No se encontro el tipo de activo " + nombreGrupo);
                }
            }
        }
        tx.commit();
        log.debug("################################################");
        log.debug("################################################");
        log.debug("TERMINO EN {} MINS", (new Date().getTime() - inicio.getTime()) / (1000 * 60));
        log.debug("################################################");
        log.debug("################################################");

        wb.write(out);
    } catch (IOException | RuntimeException e) {
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        log.error("Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
        throw new RuntimeException(
                "Hubo problemas al intentar pasar datos de archivo excel a BD (" + idx + ":" + i + ")", e);
    }
}

From source file:axiom.objectmodel.db.NodeManager.java

/**
 *  Create a new Node from a ResultSet./*from   www  . j  a  va 2  s.c  o m*/
 */
public Node createNode(DbMapping dbm, ResultSet rs, DbColumn[] columns, int offset)
        throws SQLException, IOException, ClassNotFoundException {
    HashMap propBuffer = new HashMap();
    String id = null;
    String name = null;
    String protoName = dbm.getTypeName();
    DbMapping dbmap = dbm;

    Node node = new Node();

    for (int i = 0; i < columns.length; i++) {
        // set prototype?
        if (columns[i].isPrototypeField()) {
            protoName = rs.getString(i + 1 + offset);

            if (protoName != null) {
                dbmap = getDbMapping(protoName);

                if (dbmap == null) {
                    // invalid prototype name!
                    app.logError(ErrorReporter.errorMsg(this.getClass(), "createNode")
                            + "Invalid prototype name: " + protoName + " - using default");
                    dbmap = dbm;
                    protoName = dbmap.getTypeName();
                }
            }
        }

        // set id?
        if (columns[i].isIdField()) {
            id = rs.getString(i + 1 + offset);
            // if id == null, the object doesn't actually exist - return null
            if (id == null) {
                return null;
            }
        }

        // set name?
        if (columns[i].isNameField()) {
            name = rs.getString(i + 1 + offset);
        }

        Property newprop = new Property(node);

        switch (columns[i].getType()) {
        case Types.BIT:
            newprop.setBooleanValue(rs.getBoolean(i + 1 + offset));

            break;

        case Types.TINYINT:
        case Types.BIGINT:
        case Types.SMALLINT:
        case Types.INTEGER:
            newprop.setIntegerValue(rs.getLong(i + 1 + offset));

            break;

        case Types.REAL:
        case Types.FLOAT:
        case Types.DOUBLE:
            newprop.setFloatValue(rs.getDouble(i + 1 + offset));

            break;

        case Types.DECIMAL:
        case Types.NUMERIC:

            BigDecimal num = rs.getBigDecimal(i + 1 + offset);

            if (num == null) {
                break;
            }

            if (num.scale() > 0) {
                newprop.setFloatValue(num.doubleValue());
            } else {
                newprop.setIntegerValue(num.longValue());
            }

            break;

        case Types.VARBINARY:
        case Types.BINARY:
            //                    newprop.setStringValue(rs.getString(i+1+offset));
            newprop.setJavaObjectValue(rs.getBytes(i + 1 + offset));

            break;

        case Types.LONGVARBINARY: {
            InputStream in = rs.getBinaryStream(i + 1 + offset);
            if (in == null) {
                break;
            }
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int read;
            while ((read = in.read(buffer)) > -1) {
                bout.write(buffer, 0, read);
            }
            newprop.setJavaObjectValue(bout.toByteArray());
        }

            break;
        case Types.LONGVARCHAR:
            try {
                newprop.setStringValue(rs.getString(i + 1 + offset));
            } catch (SQLException x) {
                Reader in = rs.getCharacterStream(i + 1 + offset);
                char[] buffer = new char[2048];
                int read = 0;
                int r;

                while ((r = in.read(buffer, read, buffer.length - read)) > -1) {
                    read += r;

                    if (read == buffer.length) {
                        // grow input buffer
                        char[] newBuffer = new char[buffer.length * 2];

                        System.arraycopy(buffer, 0, newBuffer, 0, buffer.length);
                        buffer = newBuffer;
                    }
                }

                newprop.setStringValue(new String(buffer, 0, read));
            }

            break;

        case Types.CHAR:
        case Types.VARCHAR:
        case Types.OTHER:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;

        case Types.DATE:
        case Types.TIME:
        case Types.TIMESTAMP:
            newprop.setDateValue(rs.getTimestamp(i + 1 + offset));

            break;

        case Types.NULL:
            newprop.setStringValue(null);

            break;

        case Types.CLOB:
            Clob cl = rs.getClob(i + 1 + offset);
            if (cl == null) {
                newprop.setStringValue(null);
                break;
            }
            char[] c = new char[(int) cl.length()];
            Reader isr = cl.getCharacterStream();
            isr.read(c);
            newprop.setStringValue(String.copyValueOf(c));
            break;

        default:
            newprop.setStringValue(rs.getString(i + 1 + offset));

            break;
        }

        if (rs.wasNull()) {
            newprop.setStringValue(null);
        }

        propBuffer.put(columns[i].getName(), newprop);

        // mark property as clean, since it's fresh from the db
        newprop.dirty = false;
    }

    if (id == null) {
        return null;
    }

    Hashtable propMap = new Hashtable();
    DbColumn[] columns2 = dbmap.getColumns();
    for (int i = 0; i < columns2.length; i++) {
        Relation rel = columns2[i].getRelation();

        if (rel != null && (rel.reftype == Relation.PRIMITIVE || rel.reftype == Relation.REFERENCE)) {

            Property prop = (Property) propBuffer.get(columns2[i].getName());

            if (prop == null) {
                continue;
            }
            prop.setName(rel.propName);
            // if the property is a pointer to another node, change the property type to NODE
            if ((rel.reftype == Relation.REFERENCE) && rel.usesPrimaryKey()) {
                // FIXME: References to anything other than the primary key are not supported
                prop.convertToNodeReference(rel.otherType, this.app.getCurrentRequestEvaluator().getLayer());
            }
            propMap.put(rel.propName.toLowerCase(), prop);
        }
    }

    node.init(dbmap, id, name, protoName, propMap, safe);

    return node;
}

From source file:org.egov.wtms.service.es.WaterChargeDocumentService.java

public WaterChargeDocument updateWaterChargeIndex(final WaterChargeDocument waterChargeDocument,
        final WaterConnectionDetails waterConnectionDetails, final AssessmentDetails assessmentDetails,
        final BigDecimal amountTodisplayInIndex) {

    Iterator<OwnerName> ownerNameItr = assessmentDetails.getOwnerNames().iterator();
    Long monthlyRate = null;/*from   ww  w .  j av a2 s  .  c  om*/
    String consumername = "";
    String aadharNumber = "";
    String mobilNumber = "";
    final SimpleDateFormat dateFormatter = new SimpleDateFormat(ES_DATE_FORMAT);
    String createdDate = null;

    if (waterConnectionDetails.getLegacy()) {
        if (waterConnectionDetails.getApplicationDate() != null)
            createdDate = dateFormatter.format(waterConnectionDetails.getApplicationDate());
    } else
        createdDate = dateFormatter.format(waterConnectionDetails.getExecutionDate());
    monthlyRate = monthlyRateFirld(waterConnectionDetails);
    if (ownerNameItr != null && ownerNameItr.hasNext())
        ownerNameItr.next().getMobileNumber();
    ownerNameItr = assessmentDetails.getOwnerNames().iterator();
    if (ownerNameItr.hasNext()) {
        final OwnerName ownerName = ownerNameItr.next();
        consumername = ownerName.getOwnerName();
        mobilNumber = ownerName.getMobileNumber();
        aadharNumber = ownerName.getAadhaarNumber() != null ? ownerName.getAadhaarNumber() : "";
        while (ownerNameItr.hasNext()) {
            final OwnerName multipleOwner = ownerNameItr.next();
            consumername = consumername.concat(",".concat(multipleOwner.getOwnerName()));
            aadharNumber = aadharNumber.concat(","
                    .concat(multipleOwner.getAadhaarNumber() != null ? multipleOwner.getAadhaarNumber() : ""));
        }
    }
    final Map<String, Object> cityInfo = cityService.cityDataAsMap();
    try {
        waterChargeDocument.setZone(assessmentDetails.getBoundaryDetails().getZoneName());
        waterChargeDocument.setRevenueWard(assessmentDetails.getBoundaryDetails().getWardName());
        waterChargeDocument.setAdminWard(assessmentDetails.getBoundaryDetails().getAdminWardName());
        waterChargeDocument.setDoorNo(assessmentDetails.getHouseNo());
        waterChargeDocument.setTotalDue(assessmentDetails.getPropertyDetails().getTaxDue().longValue());
        waterChargeDocument.setLegacy(waterConnectionDetails.getLegacy());
        waterChargeDocument.setCityGrade(defaultString((String) cityInfo.get(CITY_CORP_GRADE_KEY)));
        waterChargeDocument.setRegionName(defaultString((String) cityInfo.get(CITY_REGION_NAME_KEY)));
        waterChargeDocument.setClosureType(waterConnectionDetails.getCloseConnectionType() != null
                ? waterConnectionDetails.getCloseConnectionType()
                : "");
        waterChargeDocument.setLocality(assessmentDetails.getBoundaryDetails().getLocalityName() != null
                ? assessmentDetails.getBoundaryDetails().getLocalityName()
                : "");
        waterChargeDocument.setPropertyId(waterConnectionDetails.getConnection().getPropertyIdentifier());
        waterChargeDocument.setApplicationCode(waterConnectionDetails.getApplicationType().getCode());
        waterChargeDocument.setCreatedDate(dateFormatter.parse(createdDate));
        waterChargeDocument.setMobileNumber(mobilNumber);
        waterChargeDocument.setStatus(waterConnectionDetails.getConnectionStatus().name());
        waterChargeDocument.setDistrictName(defaultString((String) cityInfo.get(CITY_DIST_NAME_KEY)));
        waterChargeDocument.setConnectionType(waterConnectionDetails.getConnectionType().name());
        waterChargeDocument.setWaterTaxDue(amountTodisplayInIndex.longValue());
        waterChargeDocument.setUsage(waterConnectionDetails.getUsageType().getName());
        waterChargeDocument.setConsumerCode(waterConnectionDetails.getConnection().getConsumerCode());
        waterChargeDocument.setWaterSource(waterConnectionDetails.getWaterSource().getWaterSourceType());
        waterChargeDocument.setPropertyType(waterConnectionDetails.getPropertyType().getName());
        waterChargeDocument.setCategory(waterConnectionDetails.getCategory().getName());
        waterChargeDocument.setCityName(defaultString((String) cityInfo.get(CITY_NAME_KEY)));
        waterChargeDocument.setCityCode(defaultString((String) cityInfo.get(cityService.getCityCode())));

        waterChargeDocument.setSumpCapacity(waterConnectionDetails.getSumpCapacity());
        waterChargeDocument.setPipeSize(waterConnectionDetails.getPipeSize().getCode());
        waterChargeDocument.setNumberOfPerson(waterConnectionDetails.getNumberOfPerson() != null
                ? Long.valueOf(waterConnectionDetails.getNumberOfPerson())
                : 0l);
        waterChargeDocument.setCurrentDue(waterConnectionDetailsService
                .getTotalAmountTillCurrentFinYear(waterConnectionDetails)
                .subtract(
                        waterConnectionDetailsService.getTotalAmountTillPreviousFinYear(waterConnectionDetails))
                .longValue());
        waterChargeDocument.setArrearsDue(waterConnectionDetailsService
                .getTotalAmountTillPreviousFinYear(waterConnectionDetails).longValue());
        waterChargeDocument.setCurrentDemand(waterConnectionDetailsService
                .getTotalDemandTillCurrentFinYear(waterConnectionDetails)
                .subtract(waterConnectionDetailsService.getArrearsDemand(waterConnectionDetails)).longValue());
        waterChargeDocument.setArrearsDemand(
                waterConnectionDetailsService.getArrearsDemand(waterConnectionDetails).longValue());
        waterChargeDocument.setMonthlyRate(monthlyRate);
        waterChargeDocument.setConsumerName(consumername);
        waterChargeDocument.setAadhaarNumber(aadharNumber);
        waterChargeDocument.setWardlocation(commonWardlocationField(assessmentDetails));
        waterChargeDocument.setPropertylocation(commonPropertylocationField(assessmentDetails));
    } catch (final ParseException exp) {
        LOGGER.error("Exception parsing Date " + exp.getMessage());
    }
    createWaterChargeDocument(waterChargeDocument);
    return waterChargeDocument;

}

From source file:org.apache.pig.test.TestBuiltin.java

@Test
public void testAVGIntermediate() throws Exception {
    String[] avgTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate",
            "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate",
            "BigIntegerAvgIntermediate" };
    for (int k = 0; k < avgTypes.length; k++) {
        EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]);
        String inputType = getInputType(avgTypes[k]);
        Tuple tup = inputMap.get(inputType);
        // The tuple we got above has a bag with input
        // values. Input to the Intermediate.exec() however comes
        // from the map which would put each value and a count of
        // 1 in a tuple and send it down. So lets create a bag with
        // tuples that have two fields - the value and a count 1.
        DataBag bag = (DataBag) tup.get(0);
        DataBag bg = bagFactory.newDefaultBag();
        for (Tuple t : bag) {
            Tuple newTuple = tupleFactory.newTuple(2);
            newTuple.set(0, t.get(0));//from   w  ww  . ja  v  a 2  s  .com
            if (inputType == "BigDecimal") {
                newTuple.set(1, BigDecimal.ONE);
            } else if (inputType == "BigInteger") {
                newTuple.set(1, BigInteger.ONE);
            } else {
                newTuple.set(1, new Long(1));
            }
            bg.add(newTuple);
        }
        Tuple intermediateInput = tupleFactory.newTuple();
        intermediateInput.append(bg);

        Object output = avg.exec(intermediateInput);

        if (inputType == "Long" || inputType == "Integer" || inputType == "IntegerAsLong") {
            Long l = (Long) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + l + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, getExpected(avgTypes[k]), l);
        } else if (inputType == "BigDecimal") {
            BigDecimal f1 = (BigDecimal) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(), f1.toPlainString());
        } else if (inputType == "BigInteger") {
            BigInteger f1 = (BigInteger) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, ((BigInteger) getExpected(avgTypes[k])).toString(), f1.toString());
        } else {
            Double f1 = (Double) ((Tuple) output).get(0);
            String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k])
                    + " ( (output) " + f1 + " == " + getExpected(avgTypes[k]) + " (expected) )]";
            assertEquals(msg, (Double) getExpected(avgTypes[k]), f1, 0.00001);
        }
        if (inputType == "BigDecimal") {
            BigDecimal f2 = (BigDecimal) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toPlainString());

        } else if (inputType == "BigInteger") {
            BigInteger f2 = (BigInteger) ((Tuple) output).get(1);
            assertEquals("[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 4",
                    "4", f2.toString());

        } else {
            Long f2 = (Long) ((Tuple) output).get(1);
            assertEquals(
                    "[Testing " + avgTypes[k] + " on input type: " + inputType + "]Expected count to be 11", 11,
                    f2.longValue());
        }
    }
}

From source file:org.egov.wtms.service.es.WaterChargeDocumentService.java

public WaterChargeDocument createWaterChargeIndex(final WaterConnectionDetails waterConnectionDetails,
        final AssessmentDetails assessmentDetails, final BigDecimal amountTodisplayInIndex) {
    WaterChargeDocument waterChargeDocument = null;
    final Map<String, Object> cityInfo = cityService.cityDataAsMap();
    final SimpleDateFormat dateFormatter = new SimpleDateFormat(ES_DATE_FORMAT);

    if (waterConnectionDetails.getConnection() != null
            && waterConnectionDetails.getConnection().getConsumerCode() != null)
        waterChargeDocument = waterChargeIndexRepository.findByConsumerCodeAndCityName(
                waterConnectionDetails.getConnection().getConsumerCode(),
                defaultString((String) cityInfo.get(CITY_NAME_KEY)));
    if (waterChargeDocument == null) {
        Iterator<OwnerName> ownerNameItr = assessmentDetails.getOwnerNames().iterator();
        Long monthlyRate = null;/*  w w  w  .  jav  a 2  s.  c  o  m*/
        String consumername = "";
        String aadharNumber = "";
        String mobilNumber = "";
        String createdDateStr = "";
        monthlyRate = monthlyRateFirld(waterConnectionDetails);
        if (ownerNameItr != null && ownerNameItr.hasNext())
            ownerNameItr.next().getMobileNumber();
        ownerNameItr = assessmentDetails.getOwnerNames().iterator();
        if (ownerNameItr.hasNext()) {
            final OwnerName ownerName = ownerNameItr.next();
            consumername = ownerName.getOwnerName();
            mobilNumber = ownerName.getMobileNumber();
            aadharNumber = ownerName.getAadhaarNumber() != null ? ownerName.getAadhaarNumber() : "";
            while (ownerNameItr.hasNext()) {
                final OwnerName multipleOwner = ownerNameItr.next();
                consumername = consumername.concat(",".concat(multipleOwner.getOwnerName()));
                aadharNumber = aadharNumber.concat(",".concat(
                        multipleOwner.getAadhaarNumber() != null ? multipleOwner.getAadhaarNumber() : ""));
            }
        }
        if (waterConnectionDetails.getExecutionDate() != null)
            createdDateStr = dateFormatter.format(waterConnectionDetails.getExecutionDate());
        try {
            waterChargeDocument = WaterChargeDocument.builder()
                    .withZone(assessmentDetails.getBoundaryDetails().getZoneName())
                    .withRevenueWard(assessmentDetails.getBoundaryDetails().getWardName())
                    .withAdminward(assessmentDetails.getBoundaryDetails().getAdminWardName())
                    .withDoorNo(assessmentDetails.getHouseNo())
                    .withTotaldue(assessmentDetails.getPropertyDetails().getTaxDue().longValue())
                    .withLegacy(waterConnectionDetails.getLegacy())
                    .withCityGrade(defaultString((String) cityInfo.get(CITY_CORP_GRADE_KEY)))
                    .withRegionname(defaultString((String) cityInfo.get(CITY_REGION_NAME_KEY)))
                    .withClosureType(waterConnectionDetails.getCloseConnectionType() != null
                            ? waterConnectionDetails.getCloseConnectionType()
                            : "")
                    .withLocality(assessmentDetails.getBoundaryDetails().getLocalityName() != null
                            ? assessmentDetails.getBoundaryDetails().getLocalityName()
                            : "")
                    .withPropertyid(waterConnectionDetails.getConnection().getPropertyIdentifier())
                    .withApplicationcode(waterConnectionDetails.getApplicationType().getCode())
                    .withCreatedDate(
                            createdDateStr.isEmpty() ? new Date() : dateFormatter.parse(createdDateStr))
                    .withMobileNumber(mobilNumber)
                    .withStatus(waterConnectionDetails.getConnectionStatus().name())
                    .withDistrictName(defaultString((String) cityInfo.get(CITY_DIST_NAME_KEY)))
                    .withConnectiontype(waterConnectionDetails.getConnectionType().name())
                    .withWaterTaxDue(amountTodisplayInIndex.longValue())
                    .withUsage(waterConnectionDetails.getUsageType().getName())
                    .withConsumerCode(waterConnectionDetails.getConnection().getConsumerCode())
                    .withWatersource(waterConnectionDetails.getWaterSource().getWaterSourceType())
                    .withPropertytype(waterConnectionDetails.getPropertyType().getName())
                    .withCategory(waterConnectionDetails.getCategory().getName())
                    .withCityName(defaultString((String) cityInfo.get(CITY_NAME_KEY)))
                    .withCityCode(defaultString((String) cityInfo.get(cityService.getCityCode())))
                    .withSumpcapacity(waterConnectionDetails.getSumpCapacity())
                    .withPipesize(waterConnectionDetails.getPipeSize().getCode())
                    .withNumberOfPerson(waterConnectionDetails.getNumberOfPerson() != null
                            ? Long.valueOf(waterConnectionDetails.getNumberOfPerson())
                            : 0l)
                    .withCurrentDue(waterConnectionDetailsService
                            .getTotalAmountTillCurrentFinYear(waterConnectionDetails)
                            .subtract(waterConnectionDetailsService
                                    .getTotalAmountTillPreviousFinYear(waterConnectionDetails))
                            .longValue())
                    .withArrearsDue(waterConnectionDetailsService
                            .getTotalAmountTillPreviousFinYear(waterConnectionDetails).longValue())
                    .withCurrentDemand(waterConnectionDetailsService
                            .getTotalDemandTillCurrentFinYear(waterConnectionDetails)
                            .subtract(waterConnectionDetailsService.getArrearsDemand(waterConnectionDetails))
                            .longValue())
                    .withArrearsDemand(
                            waterConnectionDetailsService.getArrearsDemand(waterConnectionDetails).longValue())
                    .withMonthlyRate(monthlyRate).withConsumername(consumername).withAadhaarnumber(aadharNumber)
                    .withWardlocation(commonWardlocationField(assessmentDetails))
                    .withPropertylocation(commonPropertylocationField(assessmentDetails)).build();
        } catch (final ParseException exp) {
            LOGGER.error("Exception parsing Date " + exp.getMessage());
        }
        createWaterChargeDocument(waterChargeDocument);
    } else
        updateWaterChargeIndex(waterChargeDocument, waterConnectionDetails, assessmentDetails,
                amountTodisplayInIndex);
    return waterChargeDocument;
}

From source file:org.kuali.kpme.tklm.leave.summary.service.LeaveSummaryServiceImpl.java

protected LeaveSummary getLeaveSummary(String principalId, LocalDate startDate, LocalDate endDate,
        String accrualCategory, boolean includeFuture) {
    LeaveSummary ls = new LeaveSummary();
    List<LeaveSummaryRow> rows = new ArrayList<LeaveSummaryRow>();

    if (StringUtils.isEmpty(principalId) || startDate == null || endDate == null) {
        return ls;
    }/*from  w ww  . j a  v a2 s. c om*/

    Set<String> leavePlans = getLeavePlans(principalId, startDate, endDate);
    PrincipalHRAttributes pha = getPrincipalHrAttributes(principalId, startDate, endDate);
    if (CollectionUtils.isNotEmpty(leavePlans)) {
        List<LeavePlan> leavePlanList = HrServiceLocator.getLeavePlanService()
                .getLeavePlans(new ArrayList<String>(leavePlans), startDate);
        if (CollectionUtils.isNotEmpty(leavePlanList)) {
            LeaveCalendarDocumentHeader approvedLcdh = LmServiceLocator.getLeaveCalendarDocumentHeaderService()
                    .getMaxEndDateApprovedLeaveCalendar(principalId);
            //until we have something that creates carry over, we need to grab everything.
            // Calculating leave bLocks from Calendar Year start instead of Service Date
            Map<String, LeaveBlock> carryOverBlocks = getLeaveBlockService().getLastCarryOverBlocks(principalId,
                    startDate);
            for (LeavePlan lp : leavePlanList) {
                DateTimeFormatter formatter = DateTimeFormat.forPattern("MMMM d");
                DateTimeFormatter formatter2 = DateTimeFormat.forPattern("MMMM d yyyy");
                DateTime entryEndDate = endDate.toDateTimeAtStartOfDay();
                if (entryEndDate.getHourOfDay() == 0) {
                    entryEndDate = entryEndDate.minusDays(1);
                }
                String aString = formatter.print(startDate) + " - " + formatter2.print(entryEndDate);
                ls.setPendingDatesString(aString);

                if (approvedLcdh != null) {
                    DateTime endApprovedDate = approvedLcdh.getEndDateTime();
                    LocalDateTime aLocalTime = approvedLcdh.getEndDateTime().toLocalDateTime();
                    DateTime endApprovedTime = aLocalTime
                            .toDateTime(HrServiceLocator.getTimezoneService().getUserTimezoneWithFallback());
                    if (endApprovedTime.getHourOfDay() == 0) {
                        endApprovedDate = endApprovedDate.minusDays(1);
                    }
                    String datesString = formatter.print(approvedLcdh.getBeginDateTime()) + " - "
                            + formatter2.print(endApprovedDate);
                    ls.setYtdDatesString(datesString);
                }

                boolean filterByAccrualCategory = false;
                if (StringUtils.isNotEmpty(accrualCategory)) {
                    filterByAccrualCategory = true;
                    //remove unwanted carry over blocks from map
                    LeaveBlock carryOverBlock = carryOverBlocks.get(accrualCategory);
                    carryOverBlocks = new HashMap<String, LeaveBlock>(1);
                    if (ObjectUtils.isNotNull(carryOverBlock)) {
                        carryOverBlocks.put(carryOverBlock.getAccrualCategory(), carryOverBlock);
                    }
                }
                List<LeaveBlock> leaveBlocks = getLeaveBlockService().getLeaveBlocksSinceCarryOver(principalId,
                        carryOverBlocks, endDate, filterByAccrualCategory);

                List<LeaveBlock> futureLeaveBlocks = new ArrayList<LeaveBlock>();
                if (includeFuture) {
                    if (!filterByAccrualCategory) {
                        futureLeaveBlocks = getLeaveBlockService().getLeaveBlocks(principalId, endDate,
                                endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())));
                    } else {
                        futureLeaveBlocks = getLeaveBlockService().getLeaveBlocksWithAccrualCategory(
                                principalId, endDate,
                                endDate.plusMonths(Integer.parseInt(lp.getPlanningMonths())), accrualCategory);
                    }
                }
                Map<String, List<LeaveBlock>> leaveBlockMap = mapLeaveBlocksByAccrualCategory(leaveBlocks);
                Map<String, List<LeaveBlock>> futureLeaveBlockMap = mapLeaveBlocksByAccrualCategory(
                        futureLeaveBlocks);
                List<AccrualCategory> acList = HrServiceLocator.getAccrualCategoryService()
                        .getActiveAccrualCategoriesForLeavePlan(lp.getLeavePlan(), endDate);
                if (CollectionUtils.isNotEmpty(acList)) {
                    for (AccrualCategory ac : acList) {
                        if (ac.getShowOnGrid().equals("Y")) {

                            LeaveSummaryRow lsr = new LeaveSummaryRow();
                            lsr.setAccrualCategory(ac.getAccrualCategory());
                            lsr.setAccrualCategoryId(ac.getLmAccrualCategoryId());
                            //get max balances
                            AccrualCategoryRule acRule = HrServiceLocator.getAccrualCategoryRuleService()
                                    .getAccrualCategoryRuleForDate(ac, endDate, pha.getServiceLocalDate());
                            //accrual category rule id set on a leave summary row will be useful in generating a relevant balance transfer
                            //document from the leave calendar display. Could put this id in the request for balance transfer document.
                            EmployeeOverrideContract maxUsageOverride = LmServiceLocator
                                    .getEmployeeOverrideService().getEmployeeOverride(principalId,
                                            lp.getLeavePlan(), ac.getAccrualCategory(), "MU", endDate);

                            lsr.setAccrualCategoryRuleId(
                                    acRule == null ? null : acRule.getLmAccrualCategoryRuleId());
                            if (acRule != null
                                    && (acRule.getMaxBalance() != null || acRule.getMaxUsage() != null)) {
                                if (acRule.getMaxUsage() != null) {
                                    lsr.setUsageLimit(new BigDecimal(acRule.getMaxUsage()).setScale(2));
                                    ls.setUsageLimit(true);
                                } else {
                                    lsr.setUsageLimit(null);
                                }

                            } else {
                                lsr.setUsageLimit(null);
                            }

                            if (maxUsageOverride != null)
                                lsr.setUsageLimit(new BigDecimal(maxUsageOverride.getOverrideValue()));

                            //Fetching leaveblocks for accCat with type CarryOver -- This is logic according to the CO blocks created from scheduler job.
                            BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                            lsr.setCarryOver(carryOver);

                            //handle up to current leave blocks
                            //CalendarEntry.getEndPeriodDate passed to fetch leave block amounts on last day of Calendar period
                            assignApprovedValuesToRow(lsr, ac.getAccrualCategory(),
                                    leaveBlockMap.get(ac.getAccrualCategory()), lp, startDate, endDate);

                            //how about the leave blocks on the calendar entry being currently handled??
                            /*                            if(carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                                           LeaveBlock carryOverBlock = carryOverBlocks.get(lsr.getAccrualCategory());
                                                           DateTime carryOverBlockLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), carryOverBlock.getLeaveDate());
                                                           DateTime currentLPStart = HrServiceLocator.getLeavePlanService().getFirstDayOfLeavePlan(lp.getLeavePlan(), TKUtils.getCurrentDate());
                                                           if(carryOverBlockLPStart.equals(currentLPStart))
                             carryOver = carryOverBlock.getLeaveAmount();
                                                        }*/
                            //figure out past carry over values!!!
                            //We now have list of past years accrual and use (with ordered keys!!!)

                            //merge key sets
                            if (carryOverBlocks.containsKey(lsr.getAccrualCategory())) {
                                carryOver = carryOverBlocks.get(lsr.getAccrualCategory()).getLeaveAmount();
                                carryOver = carryOver.setScale(2);
                            }
                            Set<String> keyset = new HashSet<String>();
                            keyset.addAll(lsr.getPriorYearsUsage().keySet());
                            keyset.addAll(lsr.getPriorYearsTotalAccrued().keySet());
                            EmployeeOverrideContract carryOverOverride = LmServiceLocator
                                    .getEmployeeOverrideService().getEmployeeOverride(principalId,
                                            lp.getLeavePlan(), ac.getAccrualCategory(), "MAC", endDate);

                            for (String key : keyset) {
                                BigDecimal value = lsr.getPriorYearsTotalAccrued().get(key);
                                if (value == null) {
                                    value = BigDecimal.ZERO;
                                }
                                carryOver = carryOver.add(value);
                                BigDecimal use = lsr.getPriorYearsUsage().containsKey(key)
                                        ? lsr.getPriorYearsUsage().get(key)
                                        : BigDecimal.ZERO;
                                carryOver = carryOver.add(use);
                                if (acRule != null && acRule.getMaxCarryOver() != null) {
                                    BigDecimal carryOverDisplay = BigDecimal.ZERO;
                                    if (carryOverOverride != null) {
                                        carryOverDisplay = new BigDecimal(
                                                carryOverOverride.getOverrideValue() < carryOver.longValue()
                                                        ? carryOverOverride.getOverrideValue()
                                                        : carryOver.longValue());
                                    } else {
                                        carryOverDisplay = new BigDecimal(
                                                acRule.getMaxCarryOver() < carryOver.longValue()
                                                        ? acRule.getMaxCarryOver()
                                                        : carryOver.longValue());
                                    }
                                    carryOver = carryOverDisplay;
                                }
                            }

                            lsr.setCarryOver(carryOver);
                            if (acRule != null && acRule.getMaxCarryOver() != null) {
                                if (carryOverOverride != null) {
                                    lsr.setMaxCarryOver(new BigDecimal(carryOverOverride.getOverrideValue()));
                                } else {
                                    lsr.setMaxCarryOver(
                                            new BigDecimal(acRule.getMaxCarryOver() < carryOver.longValue()
                                                    ? acRule.getMaxCarryOver()
                                                    : carryOver.longValue()));
                                }
                            }

                            //handle future leave blocks
                            assignPendingValuesToRow(lsr, ac.getAccrualCategory(),
                                    futureLeaveBlockMap.get(ac.getAccrualCategory()));

                            //compute Leave Balance
                            BigDecimal leaveBalance = lsr.getAccruedBalance()
                                    .subtract(lsr.getPendingLeaveRequests());
                            //if leave balance is set
                            //Employee overrides have already been taken into consideration and the appropriate values
                            //for usage have been set by this point.
                            //                            if (acRule != null && StringUtils.equals(acRule.getMaxBalFlag(), "Y")) {
                            //there exists an accrual category rule with max balance limit imposed.
                            //max bal flag = 'Y' has no precedence here with max-bal / balance transfers implemented.
                            //unless institutions are not required to define a max balance limit for action_at_max_bal = LOSE.
                            //Possibly preferable to procure forfeiture blocks through balance transfer
                            if (lsr.getUsageLimit() != null) { //should not set leave balance to usage limit simply because it's not null.
                                BigDecimal availableUsage = lsr.getUsageLimit()
                                        .subtract(lsr.getYtdApprovedUsage().add(lsr.getPendingLeaveRequests()));
                                if (leaveBalance.compareTo(availableUsage) > 0)
                                    lsr.setLeaveBalance(availableUsage);
                                else
                                    lsr.setLeaveBalance(leaveBalance);
                            } else { //no usage limit
                                lsr.setLeaveBalance(leaveBalance);
                            }

                            rows.add(lsr);
                        }
                    }
                    // let's check for 'empty' accrual categories
                    if (leaveBlockMap.containsKey(null) || futureLeaveBlockMap.containsKey(null)) {
                        LeaveSummaryRow otherLeaveSummary = new LeaveSummaryRow();
                        //otherLeaveSummary.setAccrualCategory("Other");

                        assignApprovedValuesToRow(otherLeaveSummary, null, leaveBlockMap.get(null), lp,
                                startDate, endDate);
                        BigDecimal carryOver = BigDecimal.ZERO.setScale(2);
                        for (Map.Entry<String, BigDecimal> entry : otherLeaveSummary.getPriorYearsTotalAccrued()
                                .entrySet()) {
                            carryOver = carryOver.add(entry.getValue());
                            BigDecimal use = otherLeaveSummary.getPriorYearsUsage().containsKey(entry.getKey())
                                    ? otherLeaveSummary.getPriorYearsUsage().get(entry.getKey())
                                    : BigDecimal.ZERO;
                            carryOver = carryOver.add(use);
                        }
                        otherLeaveSummary.setCarryOver(carryOver);
                        assignPendingValuesToRow(otherLeaveSummary, null, futureLeaveBlockMap.get(null));
                        otherLeaveSummary.setAccrualCategory("Other");

                        //compute Leave Balance
                        // blank the avail
                        otherLeaveSummary.setUsageLimit(null);
                        otherLeaveSummary.setLeaveBalance(null);

                        rows.add(otherLeaveSummary);
                    }
                }
            }
        }
    }
    ls.setLeaveSummaryRows(rows);
    return ls;
}