Example usage for java.math BigDecimal ONE

List of usage examples for java.math BigDecimal ONE

Introduction

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

Prototype

BigDecimal ONE

To view the source code for java.math BigDecimal ONE.

Click Source Link

Document

The value 1, with a scale of 0.

Usage

From source file:org.ballerinalang.bre.bvm.BVM.java

private static void execTypeConversionOpcodes(Strand ctx, StackFrame sf, int opcode, int[] operands) {
    int i;/*from   w w  w . j a v  a  2s  .  c om*/
    int j;
    BRefType bRefType;
    String str;

    switch (opcode) {
    case InstructionCodes.I2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.I2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Long.toString(sf.longRegs[i]);
        break;
    case InstructionCodes.I2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.longRegs[i] != 0 ? 1 : 0;
        break;
    case InstructionCodes.I2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal((new BigDecimal(sf.longRegs[i], MathContext.DECIMAL128)).setScale(1,
                BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.I2BI:
        i = operands[0];
        j = operands[1];
        if (!isByteLiteral(sf.longRegs[i])) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.INT_TNAME + "' value '" + sf.longRegs[i] + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = sf.longRegs[i];
        break;
    case InstructionCodes.F2BI:
        i = operands[0];
        j = operands[1];
        double floatVal = sf.doubleRegs[i];
        if (Double.isNaN(floatVal) || Double.isInfinite(floatVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long floatAsIntVal = Math.round(floatVal);
        if (!isByteLiteral(floatAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + floatVal + "' cannot be converted to '"
                            + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = floatAsIntVal;
        break;
    case InstructionCodes.D2BI:
        i = operands[0];
        j = operands[1];

        DecimalValueKind valueKind = ((BDecimal) sf.refRegs[i]).valueKind;
        if (valueKind == DecimalValueKind.NOT_A_NUMBER || valueKind == DecimalValueKind.NEGATIVE_INFINITY
                || valueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }

        long doubleAsIntVal = Math.round(((BDecimal) sf.refRegs[i]).floatValue());
        if (!isByteLiteral(doubleAsIntVal)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.BYTE_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = doubleAsIntVal;
        break;
    case InstructionCodes.F2I:
        i = operands[0];
        j = operands[1];
        double valueToConvert = sf.doubleRegs[i];
        if (Double.isNaN(valueToConvert) || Double.isInfinite(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isFloatWithinIntRange(valueToConvert)) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out " + "of range '" + TypeConstants.FLOAT_TNAME + "' value '" + valueToConvert
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        sf.longRegs[j] = Math.round(valueToConvert);
        break;
    case InstructionCodes.F2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = Double.toString(sf.doubleRegs[i]);
        break;
    case InstructionCodes.F2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = sf.doubleRegs[i] != 0.0 ? 1 : 0;
        break;
    case InstructionCodes.F2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = new BDecimal(new BigDecimal(sf.doubleRegs[i], MathContext.DECIMAL128));
        break;
    case InstructionCodes.S2I:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BInteger(Long.parseLong(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.INT_TNAME);
        }
        break;
    case InstructionCodes.S2F:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BFloat(Double.parseDouble(str));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.FLOAT_TNAME);
        }
        break;
    case InstructionCodes.S2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = Boolean.parseBoolean(sf.stringRegs[i]) ? 1 : 0;
        break;
    case InstructionCodes.S2D:
        i = operands[0];
        j = operands[1];

        str = sf.stringRegs[i];
        try {
            sf.refRegs[j] = new BDecimal(new BigDecimal(str, MathContext.DECIMAL128));
        } catch (NumberFormatException e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.STRING_TNAME, TypeConstants.DECIMAL_TNAME);
        }
        break;
    case InstructionCodes.B2I:
        i = operands[0];
        j = operands[1];
        sf.longRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = sf.intRegs[i];
        break;
    case InstructionCodes.B2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.intRegs[i] == 1 ? "true" : "false";
        break;
    case InstructionCodes.B2D:
        i = operands[0];
        j = operands[1];
        sf.refRegs[j] = sf.intRegs[i] == 1
                ? new BDecimal(BigDecimal.ONE.setScale(1, BigDecimal.ROUND_HALF_EVEN))
                : new BDecimal(BigDecimal.ZERO.setScale(1, BigDecimal.ROUND_HALF_EVEN));
        break;
    case InstructionCodes.D2I:
        i = operands[0];
        j = operands[1];
        BDecimal decimal = (BDecimal) sf.refRegs[i];
        DecimalValueKind decValueKind = decimal.valueKind;
        if (decValueKind == DecimalValueKind.NOT_A_NUMBER || decValueKind == DecimalValueKind.NEGATIVE_INFINITY
                || decValueKind == DecimalValueKind.POSITIVE_INFINITY) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "'" + TypeConstants.DECIMAL_TNAME + "' value '" + sf.refRegs[i]
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }

        if (!isDecimalWithinIntRange((decimal.decimalValue()))) {
            ctx.setError(BLangVMErrors.createError(ctx, BallerinaErrorReasons.NUMBER_CONVERSION_ERROR,
                    "out of range '" + TypeConstants.DECIMAL_TNAME + "' value '" + decimal
                            + "' cannot be converted to '" + TypeConstants.INT_TNAME + "'"));
            handleError(ctx);
            break;
        }
        sf.longRegs[j] = Math.round(((BDecimal) sf.refRegs[i]).decimalValue().doubleValue());
        break;
    case InstructionCodes.D2F:
        i = operands[0];
        j = operands[1];
        sf.doubleRegs[j] = ((BDecimal) sf.refRegs[i]).floatValue();
        break;
    case InstructionCodes.D2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.D2B:
        i = operands[0];
        j = operands[1];
        sf.intRegs[j] = ((BDecimal) sf.refRegs[i]).decimalValue().compareTo(BigDecimal.ZERO) != 0 ? 1 : 0;
        break;
    case InstructionCodes.DT2XML:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleTypeConversionError(ctx, sf, j, BTypes.typeNull, BTypes.typeXML);
            break;
        }

        try {
            sf.refRegs[j] = XMLUtils.tableToXML((BTable) bRefType);
        } catch (Exception e) {
            sf.refRegs[j] = null;
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.DT2JSON:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            handleNullRefError(ctx);
            break;
        }

        try {
            sf.refRegs[j] = JSONUtils.toJSON((BTable) bRefType);
        } catch (Exception e) {
            handleTypeConversionError(ctx, sf, j, TypeConstants.TABLE_TNAME, TypeConstants.XML_TNAME);
        }
        break;
    case InstructionCodes.T2MAP:
        convertStructToMap(ctx, operands, sf);
        break;
    case InstructionCodes.T2JSON:
        convertStructToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2JSON:
        convertMapToJSON(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2MAP:
        convertJSONToMap(ctx, operands, sf);
        break;
    case InstructionCodes.MAP2T:
        convertMapToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.JSON2T:
        convertJSONToStruct(ctx, operands, sf);
        break;
    case InstructionCodes.XMLATTRS2MAP:
        i = operands[0];
        j = operands[1];
        bRefType = sf.refRegs[i];
        sf.refRegs[j] = ((BXMLAttributes) sf.refRegs[i]).value();
        break;
    case InstructionCodes.XML2S:
        i = operands[0];
        j = operands[1];
        sf.stringRegs[j] = sf.refRegs[i].stringValue();
        break;
    case InstructionCodes.ANY2SCONV:
        i = operands[0];
        j = operands[1];

        bRefType = sf.refRegs[i];
        if (bRefType == null) {
            sf.stringRegs[j] = STRING_NULL_VALUE;
        } else {
            sf.stringRegs[j] = bRefType.stringValue();
        }
        break;
    default:
        throw new UnsupportedOperationException();
    }
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param yearId/*from  w ww  . j  ava 2 s.  co  m*/
 * @param monthId
 * @param costCentreId
 * @param empcntClientProjectDataVoList
 * @param empcntClientProjectDataList
 * @param employeeIdList
 * @param employeeMonthlyAssignmentCount
 */
private void ruleOne(Integer yearId, Integer monthId, String costCentreId,
        List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpcntClientProjectData> empAverageCntClientProjectDataList, List<Integer> employeeIdList,
        EmployeeMonthlyAssignment employeeMonthlyAssignmentCount, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    BigDecimal assistedTimeZero = BigDecimal.ZERO;
    BigDecimal apportionedTimeZero = BigDecimal.ZERO;
    EmployeeMaster employeeMaster = employeeMonthlyAssignmentCount.getEmployeeMaster();
    TabMonth tabMonth = employeeMonthlyAssignmentCount.getTabMonth();
    TabYear tabYear = employeeMonthlyAssignmentCount.getTabYear();
    CostCentre costCentre = employeeMonthlyAssignmentCount.getCostCentre();
    CountClassification countClassification = new CountClassification();
    countClassification.setId(countTypeId);

    // get the employee aligned project for opening count
    List<EmpClientProjectTeamStruct> empClientProjectTeamStructList = empClientProjectTeamStructDao
            .findByYearMonthTypeEmps(yearId, monthId, countTypeId, employeeIdList);
    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();
    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    if (validEmployeeProjectIds.isEmpty()) {
        ruleFive(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                employeeMonthlyAssignmentCount, countTypeId, employeePcTagsTeamStructMap);
    } else {

        Set<Integer> clientCount = new HashSet<Integer>();
        Set<Integer> projectCount = new HashSet<Integer>();

        for (Integer key : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct empClientProjectTeamStruct = employeeProjectIds.get(key);
            clientCount.add(empClientProjectTeamStruct.getCompanyMaster().getCompanyId());
        }

        for (Integer key : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct empClientProjectTeamStruct = employeeProjectIds.get(key);
            projectCount.add(empClientProjectTeamStruct.getProjectMaster().getProjectId());
        }

        BigDecimal clintCountSize = new BigDecimal(clientCount.size());
        BigDecimal projectCountSize = new BigDecimal(projectCount.size());

        BigDecimal proportionToEveryClient = BigDecimal.ONE.divide(clintCountSize, 2, RoundingMode.HALF_EVEN);
        BigDecimal proportionToProjectAligned = proportionToEveryClient.divide(projectCountSize, 2,
                RoundingMode.HALF_EVEN);

        for (Integer key : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct empClientProjectTeamStruct = employeeProjectIds.get(key);
            CompanyMaster companyMaster = empClientProjectTeamStruct.getCompanyMaster();
            ProjectMaster projectMaster = empClientProjectTeamStruct.getProjectMaster();
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employeeMaster,
                    companyMaster, countClassification, tabMonth, projectMaster, tabYear, costCentre,
                    proportionToProjectAligned, assistedTimeZero, apportionedTimeZero,
                    proportionToProjectAligned);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }

    }

}

From source file:pe.gob.mef.gescon.web.ui.BaseLegalMB.java

public void activar(ActionEvent event) {
    try {// w w w .j a v a  2s .c om
        if (event != null) {
            if (this.getSelectedBaseLegal() != null) {
                LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
                User user = loginMB.getUser();
                BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
                this.getSelectedBaseLegal().setNactivo(BigDecimal.ONE);
                this.getSelectedBaseLegal().setDfechamodificacion(new Date());
                this.getSelectedBaseLegal().setVusuariomodificacion(user.getVlogin());
                service.saveOrUpdate(this.getSelectedBaseLegal());
                this.setListaBaseLegal(service.getBaselegales());
            } else {
                FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                        "Debe seleccionar la base legal a activar.");
                FacesContext.getCurrentInstance().addMessage(null, message);
            }
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String sendSiMod() {
    String pagina = null;/*from  ww  w. jav a2 s  . c  o  m*/
    try {
        if (StringUtils.isBlank(this.getSelectedPregunta().getVmsjmoderador())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                    "Campo requerido. Ingrese el mensaje a enviar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            pagina = null;
        } else {
            /* Validando si la cantidad de pregutnas destacados lleg al lmite (10 max.).*/
            if (this.getChkDestacado()) {
                ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
                HashMap filter = new HashMap();
                filter.put("ntipoconocimientoid", Constante.PREGUNTAS);
                BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
                if (cant.intValue() >= 10) {
                    this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                    RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                    return "";
                }
            }
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
            this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedPregunta()
                    .setVmsjmoderador(this.getSelectedPregunta().getVmsjmoderador().toUpperCase());
            service.saveOrUpdate(this.getSelectedPregunta());

            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("9")));
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.PREGUNTAS);
            asignacion.setNconocimientoid(this.getSelectedPregunta().getNpreguntaid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            asignacion.setNusuarioid(
                    serviceasig.getUserCreacionByPregunta(this.getSelectedPregunta().getNpreguntaid()));
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            loginMB.refreshNotifications();

            this.fSInfMod = "true";
            pagina = "/index.xhtml";
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

From source file:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param yearId/*from ww  w.  j  av  a2 s .  c  o  m*/
 * @param monthId
 * @param costCentreId
 * @param empcntClientProjectDataVoList
 * @param empcntClientProjectDataList
 * @param employeeIdList
 * @param employeeMonthlyAssignmentCount
 */
private void ruleTwo(Integer yearId, Integer monthId, String costCentreId,
        List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpcntClientProjectData> empAverageCntClientProjectDataList, List<Integer> employeeIdList,
        EmployeeMonthlyAssignment employeeMonthlyAssignmentCount, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    BigDecimal assistedTimeZero = BigDecimal.ZERO;
    BigDecimal apportionedTimeZero = BigDecimal.ZERO;
    EmployeeMaster employeeMaster = employeeMonthlyAssignmentCount.getEmployeeMaster();
    TabMonth tabMonth = employeeMonthlyAssignmentCount.getTabMonth();
    TabYear tabYear = employeeMonthlyAssignmentCount.getTabYear();
    CostCentre costCentre = employeeMonthlyAssignmentCount.getCostCentre();
    CountClassification countClassification = new CountClassification();
    countClassification.setId(countTypeId);
    // get the employee aligned project for opening count
    List<EmpClientProjectTeamStruct> empClientProjectTeamStructList = empClientProjectTeamStructDao
            .findByYearMonthTypeEmps(yearId, monthId, countTypeId, employeeIdList);

    // Get project details
    Map<Integer, EmpClientProjectTeamStruct> employeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();

    Map<Integer, EmpClientProjectTeamStruct> validEmployeeProjectIds = new HashMap<Integer, EmpClientProjectTeamStruct>();
    for (EmpClientProjectTeamStruct empClientProjectTeamStructThree : empClientProjectTeamStructList) {
        employeeProjectIds.put(empClientProjectTeamStructThree.getProjectMaster().getProjectId(),
                empClientProjectTeamStructThree);
    }

    validEmployeeProjectIds.putAll(employeeProjectIds);
    // logger.debug("validEmployeeProjectIds 1:size===>" +
    // validEmployeeProjectIds.size());

    // check in revenue table
    for (Integer key : employeeProjectIds.keySet()) {
        EmpClientProjectTeamStruct mapValues = employeeProjectIds.get(key);
        List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                .findByYearIdMonthIdProjectIdCostCentreId(mapValues.getTabYear().getYearId(),
                        mapValues.getTabMonth().getMonthId(), mapValues.getProjectMaster().getProjectId(),
                        costCentre.getCostCentreId());
        if (listValues.isEmpty()) {
            validEmployeeProjectIds.remove(key);
        }
    }
    // logger.debug("validEmployeeProjectIds 2:size===>" +
    // validEmployeeProjectIds.size());
    if (validEmployeeProjectIds.isEmpty()) {
        ruleFive(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empAverageCntClientProjectDataList, empCloseCntClientProjectDataList, employeeIdList,
                employeeMonthlyAssignmentCount, countTypeId, employeePcTagsTeamStructMap);
    } else {
        Set<Integer> clientCount = new HashSet<Integer>();

        for (Integer key : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct empClientProjectTeamStruct = employeeProjectIds.get(key);
            clientCount.add(empClientProjectTeamStruct.getCompanyMaster().getCompanyId());
        }

        BigDecimal clintCountSize = new BigDecimal(clientCount.size());
        BigDecimal proportionToEveryClient = BigDecimal.ONE.divide(clintCountSize, 2, RoundingMode.HALF_EVEN);

        for (Integer key : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct empClientProjectTeamStruct = employeeProjectIds.get(key);
            CompanyMaster companyMaster = empClientProjectTeamStruct.getCompanyMaster();
            ProjectMaster projectMaster = empClientProjectTeamStruct.getProjectMaster();
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employeeMaster,
                    companyMaster, countClassification, tabMonth, projectMaster, tabYear, costCentre,
                    proportionToEveryClient, assistedTimeZero, apportionedTimeZero, proportionToEveryClient);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    }

}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String Publicar() {
    String pagina = "/gescon/index.xhtml";
    try {//from   w ww  .  ja v a2  s. c o m
        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        User user = loginMB.getUser();

        //this.getSelectedPregunta().setVrespuesta(JSFUtils.getRequestParameter("descHtml"));
        PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
        this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        String html = this.getSelectedPregunta().getVrespuesta();
        if (Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString().length() > 400) {
            this.getSelectedPregunta().setVrespuesta(StringUtils.capitalize(
                    Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString().substring(0, 300)));
        } else {
            this.getSelectedPregunta().setVrespuesta(
                    StringUtils.capitalize(Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString()));
        }
        this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf((long) 6));
        this.getSelectedPregunta().setDfechapublicacion(new Date());
        service.saveOrUpdate(this.getSelectedPregunta());

        String ruta0 = this.pathpr + this.getSelectedPregunta().getNpreguntaid().toString() + "/"
                + BigDecimal.ZERO.toString() + "/";
        String texto = this.getSelectedPregunta().getVasunto() + " \n "
                + this.getSelectedPregunta().getVdetalle() + " \n " + html;
        GcmFileUtils.writeStringToFileServer(ruta0, "html.txt", texto);
        texto = this.getSelectedPregunta().getVasunto() + " \n " + this.getSelectedPregunta().getVdetalle()
                + " \n " + Jsoup.parse(this.getSelectedPregunta().getVrespuesta());
        GcmFileUtils.writeStringToFileServer(ruta0, "plain.txt", texto);

        this.setListaTargetVinculos(new ArrayList<Consulta>());

        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBL())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBL());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBP())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBP());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosCT())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosCT());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosOM())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosOM());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosPR())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosPR());
        }
        if (!CollectionUtils.isEmpty(this.getListaTargetVinculosWK())) {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosWK());
        }

        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaTargetVinculos())) {
            VinculoPreguntaService vinculopreguntaService = (VinculoPreguntaService) ServiceFinder
                    .findBean("VinculoPreguntaService");
            service.delete(this.getSelectedPregunta().getNpreguntaid());
            for (Consulta consulta : this.getListaTargetVinculos()) {
                VinculoPregunta vinculopregunta = new VinculoPregunta();
                vinculopregunta.setNvinculoid(vinculopreguntaService.getNextPK());
                vinculopregunta.setNpreguntaid(this.getSelectedPregunta().getNpreguntaid());
                vinculopregunta.setNconocimientovinc(consulta.getIdconocimiento());
                vinculopregunta.setNtipoconocimientovinc(consulta.getIdTipoConocimiento());
                vinculopregunta.setDfechacreacion(new Date());
                vinculopregunta.setVusuariocreacion(user.getVlogin());
                vinculopreguntaService.saveOrUpdate(vinculopregunta);

            }
        }

        AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
        this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
        this.getSelectedAsignacion().setDfechaatencion(new Date());
        this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("8")));
        serviceasig.saveOrUpdate(this.getSelectedAsignacion());

        loginMB.refreshNotifications();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO.",
                "Se public la pregunta.");
        FacesContext.getCurrentInstance().addMessage(null, message);
        FacesContext.getCurrentInstance().getExternalContext().redirect(pagina);
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;
}

From source file:org.kuali.ole.select.document.service.impl.OleInvoiceServiceImpl.java

/**
 * This method calculates the Amount and the Percent in Accounting Line if the Invoiced List Price changed
 *///from   w w w .  j  ava2  s.  c  o m
public void calculateAccount(PurApItem purapItem) {
    purapItem.setExtendedPrice(purapItem.calculateExtendedPrice());
    List<PurApAccountingLine> purApAccountingLines = purapItem.getSourceAccountingLines();
    BigDecimal totalPercent = BigDecimal.ZERO;
    BigDecimal totalAmt = BigDecimal.ZERO;
    for (PurApAccountingLine account : purApAccountingLines) {
        if (purapItem.getTotalAmount() != null && !purapItem.getTotalAmount().equals(KualiDecimal.ZERO)) {
            if (account.getAccountLinePercent() != null
                    && (account.getAmount() == null || account.getAmount().equals(KualiDecimal.ZERO))) {
                BigDecimal percent = account.getAccountLinePercent().divide(new BigDecimal(100));
                account.setAmount((purapItem.getTotalAmount().multiply(new KualiDecimal(percent))));
            } else if (account.getAmount() != null && account.getAmount().isNonZero()
                    && account.getAccountLinePercent() == null) {
                KualiDecimal dollar = account.getAmount().multiply(new KualiDecimal(100));
                BigDecimal dollarToPercent = dollar.bigDecimalValue()
                        .divide((purapItem.getTotalAmount().bigDecimalValue()), 0, RoundingMode.FLOOR);
                account.setAccountLinePercent(dollarToPercent);
            } else if (account.getAmount() != null && account.getAmount().isZero()
                    && account.getAccountLinePercent() == null) {
                account.setAccountLinePercent(new BigDecimal(0));
            } else if ((account.getAmount() != null && account.getAccountLinePercent() != null)
                    || (account.getAmount() != null && account.getAccountLinePercent().intValue() == 100)) {
                BigDecimal percent = account.getAccountLinePercent().divide(new BigDecimal(100));
                account.setAmount((purapItem.getTotalAmount().multiply(new KualiDecimal(percent))));
            }
            totalPercent = totalPercent.add(account.getAccountLinePercent());
            totalAmt = totalAmt.add(account.getAmount().bigDecimalValue());
        } else {
            account.setAmount(KualiDecimal.ZERO);
        }
    }
    // If Total Percent or Total Amount mis matches,percentage is divided across accounting lines.
    if (totalPercent.intValue() != 100 || (purapItem.getTotalAmount() != null
            && totalAmt.compareTo(purapItem.getTotalAmount().bigDecimalValue()) != 0)) {
        for (PurApAccountingLine account : purApAccountingLines) {
            if (purapItem.getTotalAmount() != null && !purapItem.getTotalAmount().equals(KualiDecimal.ZERO)) {
                BigDecimal percent = BigDecimal.ONE.divide(new BigDecimal(purApAccountingLines.size()),
                        BigDecimal.ROUND_CEILING, BigDecimal.ROUND_HALF_UP);
                account.setAmount((purapItem.getTotalAmount().multiply(new KualiDecimal(percent))));
            } else {
                account.setAmount(KualiDecimal.ZERO);
            }
        }
    }

}

From source file:org.openbravo.erpCommon.ad_forms.AcctServer.java

private BigDecimal calculateMultipleRatesDifferences(BigDecimal _amount, String currencyIDFrom,
        String currencyIDTo, DocLine line, ConnectionProvider conn) {
    // _amount * ((TrxRate *
    // AccountingRateCurrencyFromCurrencyTo)-AccountingRateCurrencyDocCurrencyTo)
    String conversionDate = DateAcct;
    String strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
            .getProperty("dateFormat.java");
    final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
    // Calculate accountingRateCurrencyFromCurrencyTo
    BigDecimal accountingRateCurrencyFromCurrencyTo = BigDecimal.ONE;
    if (!currencyIDFrom.equals(currencyIDTo)) {
        ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID,
                currencyIDFrom, currencyIDTo);
        if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                && line instanceof DocLine_FINReconciliation) {
            String transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
            FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                    transactionID);/*from w  w w.  ja  v a  2  s .  c o  m*/
            conversionDate = dateFormat.format(transaction.getDateAcct());
            conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
                    currencyIDFrom, currencyIDTo);
        }
        if (conversionRateCurrentDoc != null) {
            accountingRateCurrencyFromCurrencyTo = conversionRateCurrentDoc.getRate();
        } else {
            // I try to find a reversal rate for the doc, if exists i apply it reversal as well
            if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                    && line instanceof DocLine_FINReconciliation) {
                String transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
                FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                        transactionID);
                conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
                        currencyIDTo, currencyIDFrom);
            } else {
                conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID, currencyIDTo,
                        currencyIDFrom);
            }
            if (conversionRateCurrentDoc != null) {
                accountingRateCurrencyFromCurrencyTo = BigDecimal.ONE.divide(conversionRateCurrentDoc.getRate(),
                        MathContext.DECIMAL64);
            } else {
                accountingRateCurrencyFromCurrencyTo = getConvertionRate(currencyIDFrom, currencyIDTo,
                        conversionDate, "", AD_Client_ID, AD_Org_ID, conn);
            }
        }
    }

    // Calculate accountingRateCurrencyFromCurrencyTo
    BigDecimal accountingRateCurrencyDocCurrencyTo = BigDecimal.ONE;
    if (!C_Currency_ID.equals(currencyIDTo)) {
        ConversionRateDoc conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID, C_Currency_ID,
                currencyIDTo);
        if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                && line instanceof DocLine_FINReconciliation) {
            String transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
            FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                    transactionID);
            conversionDate = dateFormat.format(transaction.getTransactionDate());
            conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
                    C_Currency_ID, currencyIDTo);
        }
        if (conversionRateCurrentDoc != null) {
            accountingRateCurrencyDocCurrencyTo = conversionRateCurrentDoc.getRate();
        } else {
            // I try to find a reversal rate for the doc, if exists i apply it reversal as well
            if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                    && line instanceof DocLine_FINReconciliation) {
                String transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
                FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                        transactionID);
                conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
                        currencyIDTo, C_Currency_ID);
            } else {
                conversionRateCurrentDoc = getConversionRateDoc(AD_Table_ID, Record_ID, currencyIDTo,
                        C_Currency_ID);
            }
            if (conversionRateCurrentDoc != null) {
                accountingRateCurrencyDocCurrencyTo = BigDecimal.ONE.divide(conversionRateCurrentDoc.getRate(),
                        MathContext.DECIMAL64);
            } else {
                accountingRateCurrencyDocCurrencyTo = getConvertionRate(C_Currency_ID, currencyIDTo,
                        conversionDate, "", AD_Client_ID, AD_Org_ID, conn);
            }
        }
    }
    // Calculate transaction rate
    BigDecimal trxRate = BigDecimal.ONE;
    if (!C_Currency_ID.equals(currencyIDFrom)) {
        if (AD_Table_ID.equals(TABLEID_Payment)) {
            FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, Record_ID);
            trxRate = payment.getFinancialTransactionConvertRate();
        } else if (AD_Table_ID.equals(TABLEID_Transaction) || AD_Table_ID.equals(TABLEID_Reconciliation)) {
            String transactionID = Record_ID;
            // When TableID = Reconciliation info is loaded from transaction
            if (AD_Table_ID.equals(AcctServer.TABLEID_Reconciliation)
                    && line instanceof DocLine_FINReconciliation) {
                transactionID = ((DocLine_FINReconciliation) line).getFinFinAccTransactionId();
            }
            FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
                    transactionID);
            trxRate = transaction.getForeignConversionRate();
        }
    }
    Currency currencyFrom = OBDal.getInstance().get(Currency.class, currencyIDTo);
    return _amount
            .multiply(trxRate.multiply(accountingRateCurrencyDocCurrencyTo)
                    .subtract(accountingRateCurrencyFromCurrencyTo))
            .setScale(currencyFrom.getStandardPrecision().intValue(), BigDecimal.ROUND_HALF_EVEN);
}

From source file:pe.gob.mef.gescon.web.ui.PendienteMB.java

public void Responder(ActionEvent event) {
    try {/*from  w  w w  .  ja v  a  2s.co m*/
        if (StringUtils.isBlank(this.getSelectedPregunta().getVrespuesta())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, Constante.SEVERETY_ALERTA,
                    "Campo requerido. Ingrese la respuesta.");
            FacesContext.getCurrentInstance().addMessage(null, message);
        } else {
            LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
            User user = loginMB.getUser();

            PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
            //this.getSelectedPregunta().setVrespuesta(JSFUtils.getRequestParameter("descHtml"));
            String html = this.getSelectedPregunta().getVrespuesta();
            if (Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString().length() > 400) {
                this.getSelectedPregunta().setVrespuesta(StringUtils.capitalize(
                        Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString().substring(0, 300)));
            } else {
                this.getSelectedPregunta().setVrespuesta(StringUtils
                        .capitalize(Jsoup.parse(this.getSelectedPregunta().getVrespuesta()).toString()));
            }
            this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
            this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf((long) 5));
            service.saveOrUpdate(this.getSelectedPregunta());

            String ruta0 = this.pathpr + this.getSelectedPregunta().getNpreguntaid().toString() + "/"
                    + BigDecimal.ZERO.toString() + "/";
            String texto = this.getSelectedPregunta().getVasunto() + " \n "
                    + this.getSelectedPregunta().getVdetalle() + " \n " + html;
            GcmFileUtils.writeStringToFileServer(ruta0, "html.txt", texto);
            texto = this.getSelectedPregunta().getVasunto() + " \n " + this.getSelectedPregunta().getVdetalle()
                    + " \n " + Jsoup.parse(this.getSelectedPregunta().getVrespuesta());
            GcmFileUtils.writeStringToFileServer(ruta0, "plain.txt", texto);

            this.setListaTargetVinculos(new ArrayList<Consulta>());

            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBL())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBL());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosBP())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBP());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosCT())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosCT());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosOM())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosOM());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosPR())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosPR());
            }
            if (!CollectionUtils.isEmpty(this.getListaTargetVinculosWK())) {
                this.getListaTargetVinculos().addAll(this.getListaTargetVinculosWK());
            }

            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(this.getListaTargetVinculos())) {
                VinculoPreguntaService vinculopreguntaService = (VinculoPreguntaService) ServiceFinder
                        .findBean("VinculoPreguntaService");
                service.delete(this.getSelectedPregunta().getNpreguntaid());
                for (Consulta consulta : this.getListaTargetVinculos()) {
                    VinculoPregunta vinculopregunta = new VinculoPregunta();
                    vinculopregunta.setNvinculoid(vinculopreguntaService.getNextPK());
                    vinculopregunta.setNpreguntaid(this.getSelectedPregunta().getNpreguntaid());
                    vinculopregunta.setNconocimientovinc(consulta.getIdconocimiento());
                    vinculopregunta.setNtipoconocimientovinc(consulta.getIdTipoConocimiento());
                    vinculopregunta.setDfechacreacion(new Date());
                    vinculopregunta.setVusuariocreacion(user.getVlogin());
                    vinculopreguntaService.saveOrUpdate(vinculopregunta);

                }
            }

            AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
            this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            this.getSelectedAsignacion().setDfechaatencion(new Date());
            serviceasig.saveOrUpdate(this.getSelectedAsignacion());

            Asignacion asignacion = new Asignacion();
            asignacion.setNasignacionid(serviceasig.getNextPK());
            asignacion.setNtipoconocimientoid(Constante.PREGUNTAS);
            asignacion.setNconocimientoid(this.getSelectedPregunta().getNpreguntaid());
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("1")));
            CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
            asignacion.setNusuarioid(categoriaService
                    .getCategoriaById(this.getSelectedPregunta().getNcategoriaid()).getNmoderador());
            asignacion.setDfechacreacion(new Date());
            asignacion.setDfechaasignacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            loginMB.refreshNotifications();

            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO.",
                    "Se respondi la pregunta.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            FacesContext.getCurrentInstance().getExternalContext().redirect("/gescon/index.xhtml");
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.lp.server.lieferschein.ejbfac.LieferscheinFacBean.java

private BigDecimal getSollsatzgroesseArtikelSet(AuftragpositionDto auftragpositionDto,
        List<Artikelset> artikelsets) {
    BelegpositionVerkaufDto headDto = findArtikelsetHead(auftragpositionDto, artikelsets);
    if (null != headDto) {
        BigDecimal headAmount = headDto.getNMenge();
        return auftragpositionDto.getNMenge().divide(headAmount);
    }//from   w  w  w  . ja v a 2s.  c  om

    return BigDecimal.ONE;
}