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.apache.pig.test.TestBuiltin.java

@Test
public void testAVGFinal() throws Exception {
    String[] avgTypes = { "AVGFinal", "DoubleAvgFinal", "LongAvgFinal", "IntAvgFinal", "FloatAvgFinal",
            "BigDecimalAvgFinal", "BigIntegerAvgFinal" };
    String[] avgIntermediateTypes = { "AVGIntermediate", "DoubleAvgIntermediate", "LongAvgIntermediate",
            "IntAvgIntermediate", "FloatAvgIntermediate", "BigDecimalAvgIntermediate",
            "BigIntegerAvgIntermediate" };
    for (int k = 0; k < avgTypes.length; k++) {
        EvalFunc<?> avg = evalFuncMap.get(avgTypes[k]);
        Tuple tup = inputMap.get(getInputType(avgTypes[k]));

        // To test AVGFinal, AVGIntermediate should first be called and
        // the output of AVGIntermediate should be supplied as input to
        // AVGFinal. To simulate this, we will call Intermediate twice
        // on the above tuple and collect the outputs and pass it to
        // Final.

        // get the right "Intermediate" EvalFunc
        EvalFunc<?> avgIntermediate = evalFuncMap.get(avgIntermediateTypes[k]);
        // 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.
        // The input has 10 values - lets put the first five of them
        // in the input to the first call of AVGIntermediate and the
        // remaining five in the second call.
        DataBag bg = (DataBag) tup.get(0);
        DataBag bg1 = bagFactory.newDefaultBag();
        DataBag bg2 = bagFactory.newDefaultBag();
        int i = 0;
        for (Tuple t : bg) {
            Tuple newTuple = tupleFactory.newTuple(2);
            newTuple.set(0, t.get(0));//from   ww w.j  av a  2s .  c  om
            if (t.get(0) == null) {
                if (getInputType(avgTypes[k]) == "BigDecimal") {
                    newTuple.set(1, BigDecimal.ZERO);
                } else if (getInputType(avgTypes[k]) == "BigInteger") {
                    newTuple.set(1, BigInteger.ZERO);
                } else {
                    newTuple.set(1, new Long(0));
                }
            } else {
                if (getInputType(avgTypes[k]) == "BigDecimal") {
                    newTuple.set(1, BigDecimal.ONE);
                } else if (getInputType(avgTypes[k]) == "BigInteger") {
                    newTuple.set(1, BigInteger.ONE);
                } else {
                    newTuple.set(1, new Long(1));
                }
            }
            if (i < 5) {
                bg1.add(newTuple);
            } else {
                bg2.add(newTuple);
            }
            i++;
        }
        Tuple intermediateInput1 = tupleFactory.newTuple();
        intermediateInput1.append(bg1);
        Object output1 = avgIntermediate.exec(intermediateInput1);
        Tuple intermediateInput2 = tupleFactory.newTuple();
        intermediateInput2.append(bg2);
        Object output2 = avgIntermediate.exec(intermediateInput2);

        DataBag bag = Util.createBag(new Tuple[] { (Tuple) output1, (Tuple) output2 });

        Tuple finalTuple = TupleFactory.getInstance().newTuple(1);
        finalTuple.set(0, bag);
        Object output = avg.exec(finalTuple);
        String msg = "[Testing " + avgTypes[k] + " on input type: " + getInputType(avgTypes[k]) + " ( (output) "
                + output + " == " + getExpected(avgTypes[k]) + " (expected) )]";
        if (getInputType(avgTypes[k]) == "BigDecimal" || getInputType(avgTypes[k]) == "BigInteger") {
            assertEquals(msg, ((BigDecimal) getExpected(avgTypes[k])).toPlainString(),
                    ((BigDecimal) output).toPlainString());
        } else {
            assertEquals(msg, (Double) getExpected(avgTypes[k]), (Double) output, 0.00001);
        }
    }
}

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

/**
 * @param empcntClientProjectDataList/* w  w  w.  j a  v a 2s.  com*/
 * @param empClientProjectTeamStructList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeZero
 * @param assistedTimeZero
 * @param apportionedTimeZero
 * @param allignedTimeOne
 * @param totalTimeOne
 * @return
 */

private void getMultipleProjectDetail(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList,
        List<EmpClientProjectTeamStruct> empClientProjectTeamStructList, EmployeeMaster employee,
        TabMonth month, TabYear year, CostCentre costCentre, CountClassification countType,
        BigDecimal allignedTimeZero, BigDecimal assistedTimeZero, BigDecimal apportionedTimeZero,
        BigDecimal allignedTimeOne, BigDecimal totalTimeOne, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getMultipleProjectDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getMultipleProjectDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // 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());
    // For all invalid projects calculate count zero
    if (validEmployeeProjectIds.isEmpty()) {
        getZeroProjectsDetail(yearId, monthId, costCentreId, empOpenCntClientProjectDataList,
                empCloseCntClientProjectDataList, employee, month, year, costCentre, countType,
                allignedTimeZero, assistedTimeZero, totalTimeOne, totalTimeOne, countTypeId,
                employeePcTagsTeamStructMap);
    }
    // Get list of project from execution data for that employee
    List<Integer> projectIdList = executionDataDao.findByPersonYearMonthCostCentre(employeeId, yearId, monthId,
            costCentreId);
    // logger.debug("execution data projects===>" + projectIdList.size());

    // If List is empty
    if (projectIdList.isEmpty()) {
        // logger.debug("Contain InValid projects (: Find by Revenue)===>");

        Map<Integer, BigDecimal> projectRevenueMap = new HashMap<Integer, BigDecimal>();
        BigDecimal sumOfRevenue = BigDecimal.ZERO;

        List<Object[]> collageProjectRevenueList = collageProjectRevenueDao.findByCostCentreIdYearIdMonthId(
                costCentre.getCostCentreId(), year.getYearId(), month.getMonthId());

        for (Object[] collageProjectRevenue : collageProjectRevenueList) {
            Integer projectId = (Integer) collageProjectRevenue[0];
            BigDecimal revenue = (BigDecimal) collageProjectRevenue[1];
            projectRevenueMap.put(projectId, revenue);
        }
        // logger.debug("projectRevenueMap size===>" +
        // projectRevenueMap.size());

        for (Integer key : projectRevenueMap.keySet()) {
            sumOfRevenue = sumOfRevenue.add(projectRevenueMap.get(key));
        }
        logger.debug("sumOfRevenue===>" + sumOfRevenue);

        for (Integer projectId : validEmployeeProjectIds.keySet()) {
            EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
            BigDecimal revenue = projectRevenueMap.get(projectId);
            logger.debug("revenue===>" + revenue);
            BigDecimal projectRevenueCount = revenue.divide(sumOfRevenue, 2, RoundingMode.HALF_EVEN);
            projectRevenueCount = projectRevenueCount.setScale(2, RoundingMode.CEILING);
            // logger.debug("685 empOpenCntClientProjectData ProjectId:Revenue===>"+projectId+" : "
            // + projectRevenueCount);
            EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                    mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                    costCentre, projectRevenueCount, BigDecimal.ZERO, BigDecimal.ZERO, projectRevenueCount);
            if (countTypeId == 1) {
                empOpenCntClientProjectDataList.add(empcntClientProjectData);
            }
            if (countTypeId == 2) {
                empCloseCntClientProjectDataList.add(empcntClientProjectData);
            }
        }
    } else {
        // logger.debug("Else Contain Valid projects===>");
        Integer validEmployeeProjectCount = validEmployeeProjectIds.size();
        // Get valid projects list=>project is both revenue data and
        // execution data
        Set<Integer> validAllProjects = new HashSet<Integer>();
        for (Integer projectId : projectIdList) {
            List<CollageProjectRevenue> listValues = collageProjectRevenueDao
                    .findByYearIdMonthIdProjectIdCostCentreId(yearId, monthId, projectId, costCentreId);
            if (!listValues.isEmpty()) {
                validAllProjects.add(projectId);
            }

        }
        Integer validAllProjectCount = validAllProjects.size();
        // logger.debug("validAllProjects :size===>" +
        // validAllProjects.size());
        // Total hour worked by an Employee
        List<BigDecimal> toatalHours = executionDataDao.findByPersonIdYearIdMonthIdCostCentreId(employeeId,
                yearId, monthId, costCentreId);
        BigDecimal toatlTime = toatalHours.get(0);
        // logger.debug("ToatalHours===>" + toatlTime);

        // Separate assigned projects from execution data projects
        Map<Integer, BigDecimal> assignedProjects = new HashMap<Integer, BigDecimal>();
        Map<Integer, BigDecimal> unAssignedProjects = new HashMap<Integer, BigDecimal>();
        List<Object[]> allProjectTimeList = executionDataDao
                .findByEmployeeIdYearIdMonthIdCostCentreId(employeeId, yearId, monthId, costCentreId);
        for (Object[] result : allProjectTimeList) {
            Integer projectId = (Integer) result[0];
            BigDecimal hour = (BigDecimal) result[1];
            Integer companyId = (Integer) result[2];
            if (validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjects.put(projectId, hour);
            }
            if (!validEmployeeProjectIds.containsKey(projectId) && validAllProjects.contains(projectId)) {
                // logger.debug("assignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                unAssignedProjects.put(projectId, hour);
            }
        }

        if (validEmployeeProjectCount == validAllProjectCount
                && validAllProjects.containsAll(validEmployeeProjectIds.keySet())
                && unAssignedProjects.isEmpty()) {

            // logger.debug("validEmployeeProjectCount==validAllProjectCount :(Only in assigned projects)");
            for (Integer key : assignedProjects.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                BigDecimal timeByProject = assignedProjects.get(key);
                EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                // logger.debug("744 : Worked hours (Only in assigned projects) 1===>"+timeByProject+
                // " : "+toatlTime);
                BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("745: Worked hours (Only in assigned projects) 2===>"+workedHours);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                        costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }

        } else if (!assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("validEmployeeProjectCount!=validAllProjectCount :(Both in assigned and unassigned projects)");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug("Worked hours===> >=168");
                for (Integer key : assignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("768: Aligned hours (Both in assigned and unassigned projects) 1===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, workedHours, assistedTimeZero, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("787: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    // logger.debug("Project Id===>"+key);
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("811: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                totalUnAssingnedHours = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                for (Map.Entry<Integer, BigDecimal> entry : assignedProjects.entrySet()) {
                    assingnedHours = assingnedHours.add(entry.getValue());
                }
                // logger.debug("Aligned Hours===> "+assingnedHours);
                for (Integer key : assignedProjects.keySet()) {
                    Integer projectId = key;
                    BigDecimal timeByProject = assignedProjects.get(key);
                    // logger.debug("831 :projectId : timeByProject===> "+projectId+" : "+timeByProject);
                    EmpClientProjectTeamStruct mapValues = validEmployeeProjectIds.get(projectId);
                    BigDecimal averageWorkedHours = timeByProject.divide(assingnedHours, 2,
                            RoundingMode.HALF_EVEN);
                    // logger.debug("834 :averageWorkedHours : assingnedHours===> "+averageWorkedHours+" : "+assingnedHours);
                    BigDecimal actualWorkedHours = averageWorkedHours.multiply(totalUnAssingnedHours);
                    actualWorkedHours = actualWorkedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("836: actualWorkedHours : totalUnAssingnedHours 2===>"+actualWorkedHours+" : "+totalUnAssingnedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            mapValues.getCompanyMaster(), countType, month, mapValues.getProjectMaster(), year,
                            costCentre, actualWorkedHours, assistedTimeZero, apportionedTimeZero,
                            actualWorkedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            }
        } else if (assignedProjects.isEmpty() && !unAssignedProjects.isEmpty()) {
            // logger.debug("Only in unassigned projects===>");
            if (toatlTime.compareTo(new BigDecimal(Constants.TOTAL_WORKING_HOURS)) >= 0) {
                // logger.debug(" unassigned projects Worked hours===> >=168");
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal workedHours = timeByProject.divide(toatlTime, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    // logger.debug("860: Assisted hours (Both in assigned and unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
            } else {
                // logger.debug("unassigned projects Worked hours===> <168");
                BigDecimal totalUnAssingnedHours = BigDecimal.ZERO;
                BigDecimal assingnedHours = BigDecimal.ZERO;
                for (Integer key : unAssignedProjects.keySet()) {
                    // Get time spent on each project by employee id
                    Integer projectId = key;
                    BigDecimal timeByProject = unAssignedProjects.get(key);
                    BigDecimal workedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                    workedHours = workedHours.setScale(2, RoundingMode.CEILING);
                    totalUnAssingnedHours = totalUnAssingnedHours.add(workedHours);
                    // Assign to assisted count for unAssignedProjects
                    List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                    ProjectMaster projectMaster = projectList.get(0);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    // logger.debug("884: Assisted hours in unassigned projects) 2===>"+workedHours);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre,
                            apportionedTimeZero, workedHours, apportionedTimeZero, workedHours);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                }
                // logger.debug("totalUnAssingnedHours===> "+totalUnAssingnedHours);
                if (totalUnAssingnedHours.compareTo(BigDecimal.ONE) == -1) {
                    BigDecimal remainProportion = BigDecimal.ONE.subtract(totalUnAssingnedHours);
                    getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                            employee, month, year, costCentre, countType, remainProportion, unAssignedProjects,
                            countTypeId, employeePcTagsTeamStructMap);
                }
            }
        }

    }
    // logger.debug("<====getMultipleProjectDetail END====>");
}

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

public String Publicar() throws Exception {
    String pagina = null;//from w ww.  ja  v a2s .  co m
    try {
        /* 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");
        User user_savepreg = loginMB.getUser();

        PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
        if (this.getSelectedCategoria() == null) {
            this.getSelectedPregunta().setNcategoriaid(this.getSelectedPregunta().getNcategoriaid());
        } else {
            this.getSelectedPregunta().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
        }
        this.getSelectedPregunta().setVasunto(this.getSelectedPregunta().getVasunto().trim());
        this.getSelectedPregunta().setVdetalle(this.getSelectedPregunta().getVdetalle().trim());
        this.getSelectedPregunta().setNentidadid(this.getSelectedPregunta().getNentidadid());
        this.getSelectedPregunta().setVrespuesta(this.getSelectedPregunta().getVrespuesta());
        this.getSelectedPregunta().setVdatoadicional(this.getSelectedPregunta().getVdatoadicional().trim());
        this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedPregunta().setDfechamodificacion(new Date());
        this.getSelectedPregunta().setVusuariomodificacion(user_savepreg.getVlogin());
        this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf((long) 6));
        this.getSelectedPregunta().setDfechapublicacion(new Date());
        service.saveOrUpdate(this.getSelectedPregunta());

        RespuestaHistService serviceresp = (RespuestaHistService) ServiceFinder
                .findBean("RespuestaHistService");
        RespuestaHist respuestahist = new RespuestaHist();
        respuestahist.setNhistorialid(serviceresp.getNextPK());
        respuestahist.setNpreguntaid(this.getSelectedPregunta().getNpreguntaid());
        respuestahist.setVrespuesta(this.getSelectedPregunta().getVrespuesta());
        respuestahist.setVusuariocreacion(user_savepreg.getVlogin());
        respuestahist.setDfechacreacion(new Date());
        serviceresp.saveOrUpdate(respuestahist);

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

        listaTargetVinculos = new ArrayList<Consulta>();

        if (this.getListaTargetVinculosBL() == null) {
        } else {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBL());
        }
        if (this.getListaTargetVinculosBP() == null) {
        } else {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosBP());
        }
        if (this.getListaTargetVinculosCT() == null) {
        } else {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosCT());
        }
        if (this.getListaTargetVinculosOM() == null) {
        } else {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosOM());
        }
        if (this.getListaTargetVinculosPR() == null) {
        } else {
            this.getListaTargetVinculos().addAll(this.getListaTargetVinculosPR());
        }
        if (this.getListaTargetVinculosWK() == null) {
        } else {
            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_savepreg.getVlogin());
                vinculopreguntaService.saveOrUpdate(vinculopregunta);

            }
        }
        pagina = "/pages/pregunta/lista?faces-redirect=true";

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

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The hyperbolic tangent./*from  www .ja v a  2 s.  c  o m*/
 *
 * @param x The argument.
 * @return The tanh(x) = sinh(x)/cosh(x).
 */
static public BigDecimal tanh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return tanh(x.negate()).negate();
    } else if (x.compareTo(BigDecimal.ZERO) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* tanh(x) = (1-e^(-2x))/(1+e^(-2x)) .
         */
        BigDecimal exp2x = exp(xhighpr.multiply(new BigDecimal(-2)));
        /* The error in tanh x is err(x)/cosh^2(x).
         */

        double eps = 0.5 * x.ulp().doubleValue() / Math.pow(Math.cosh(x.doubleValue()), 2.0);
        MathContext mc = new MathContext(err2prec(Math.tanh(x.doubleValue()), eps));

        return BigDecimal.ONE.subtract(exp2x).divide(BigDecimal.ONE.add(exp2x), mc);

    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The inverse hyperbolic cosine.// www. j a  va2s  .co  m
 *
 * @param x The argument.
 * @return The arccosh(x) .
 */
static public BigDecimal acosh(final BigDecimal x) {
    if (x.compareTo(BigDecimal.ONE) < 0) {
        throw new ArithmeticException("Out of range argument cosh " + x.toString());
    } else if (x.compareTo(BigDecimal.ONE) == 0) {
        return BigDecimal.ZERO;
    } else {
        BigDecimal xhighpr = scalePrec(x, 2);
        /* arccosh(x) = log(x+sqrt(x^2-1))
         */
        BigDecimal logx = log(sqrt(xhighpr.pow(2).subtract(BigDecimal.ONE)).add(xhighpr));
        /* The absolute error in arcsinh x is err(x)/sqrt(x^2-1)
         */

        double xDbl = x.doubleValue();

        double eps = 0.5 * x.ulp().doubleValue() / Math.sqrt(xDbl * xDbl - 1.);
        MathContext mc = new MathContext(err2prec(logx.doubleValue(), eps));

        return logx.round(mc);

    }
}

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

public void edit(ActionEvent event) {
    try {/*  w w w .  j a va  2s  . co m*/
        if (this.getSelectedCategoria() == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Seleccione la categora de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (this.getSelectedBaseLegal().getNtiporangoid() == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Seleccione el tipo de rango de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (this.getSelectedBaseLegal().getNrangoid() == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Seleccione el tipo de rango de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (StringUtils.isBlank(this.getTipoNorma())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Ingrese el tipo de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (StringUtils.isBlank(this.getNumeroNorma())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Ingrese el nmero de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (StringUtils.isBlank(this.getSelectedBaseLegal().getVnombre())) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Ingrese la sumilla de la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (this.getSelectedBaseLegal().getDfechavigencia() == null) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Ingrese la fecha de publicacin en el diario \"EL PERUANO\".");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (!this.getChkGobNacional() && !this.getChkGobRegional() && !this.getChkGobLocal()
                && !this.getChkMancomunidades()) {
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                    "Seleccione al menos un mbito para la base legal a registrar.");
            FacesContext.getCurrentInstance().addMessage(null, message);
            return;
        }
        if (this.getSelectedBaseLegal().getNdestacado().equals(BigDecimal.ZERO) && this.getChkDestacado()) {
            ConsultaService consultaService = (ConsultaService) ServiceFinder.findBean("ConsultaService");
            HashMap filter = new HashMap();
            filter.put("ntipoconocimientoid", Constante.BASELEGAL);
            BigDecimal cant = consultaService.countDestacadosByTipoConocimiento(filter);
            if (cant.intValue() >= 10) {
                this.setListaDestacados(consultaService.getDestacadosByTipoConocimiento(filter));
                RequestContext.getCurrentInstance().execute("PF('destDialog').show();");
                return;
            }
        }
        if (!CollectionUtils.isEmpty(this.getListaTarget())) {
            for (BaseLegal v : this.getListaTarget()) {
                if (v.getNestadoid().equals(BigDecimal.ZERO)) {
                    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_ERROR, "ERROR.",
                            "Debe seleccionar el estado de todos los vnculos agregados.");
                    FacesContext.getCurrentInstance().addMessage(null, message);
                    return;
                }
            }
        }

        if (CollectionUtils.isEmpty(this.getListaBaseLegal())) {
            this.setListaBaseLegal(new ArrayList());
        }
        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        User user = loginMB.getUser();
        if (this.getSelectedCategoria() != null) {
            this.getSelectedBaseLegal().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
        }
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.getSelectedBaseLegal()
                .setVnombre(StringUtils.capitalize(this.getSelectedBaseLegal().getVnombre()));
        this.getSelectedBaseLegal().setVnumero(
                this.getTipoNorma().concat(" - ").concat(StringUtils.upperCase(this.getNumeroNorma())));
        this.getSelectedBaseLegal().setNtiporangoid(this.getSelectedBaseLegal().getNtiporangoid());
        this.getSelectedBaseLegal().setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        this.getSelectedBaseLegal()
                .setNgobnacional(this.getChkGobNacional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNgobregional(this.getChkGobRegional() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNgoblocal(this.getChkGobLocal() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal()
                .setNmancomunidades(this.getChkMancomunidades() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedBaseLegal().setNcodigowiki(this.getCodigoWiki());
        this.getSelectedBaseLegal().setVsumilla(this.getSelectedBaseLegal().getVsumilla().trim());
        this.getSelectedBaseLegal().setDfechavigencia(this.getSelectedBaseLegal().getDfechavigencia());
        this.getSelectedBaseLegal().setVtema(this.getSelectedBaseLegal().getVtema());
        this.getSelectedBaseLegal().setVusuariomodificacion(user.getVlogin());
        this.getSelectedBaseLegal().setDfechamodificacion(new Date());
        service.saveOrUpdate(this.getSelectedBaseLegal());

        BaseLegalHistorialService serviceHistorial = (BaseLegalHistorialService) ServiceFinder
                .findBean("BaseLegalHistorialService");
        BaselegalHist hist = serviceHistorial
                .getLastHistorialByBaselegal(this.getSelectedBaseLegal().getNbaselegalid());

        BaselegalHist baseHist = new BaselegalHist();
        baseHist.setNhistorialid(serviceHistorial.getNextPK());
        baseHist.setNbaselegalid(this.getSelectedBaseLegal().getNbaselegalid());
        baseHist.setNcategoriaid(this.getSelectedBaseLegal().getNcategoriaid());
        baseHist.setVnombre(this.getSelectedBaseLegal().getVnombre());
        baseHist.setVnumero(this.getSelectedBaseLegal().getVnumero());
        baseHist.setNtiporangoid(this.getSelectedBaseLegal().getNtiporangoid());
        baseHist.setNrangoid(this.getSelectedBaseLegal().getNrangoid());
        baseHist.setNgobnacional(this.getSelectedBaseLegal().getNgobnacional());
        baseHist.setNgobregional(this.getSelectedBaseLegal().getNgobregional());
        baseHist.setNgoblocal(this.getSelectedBaseLegal().getNgoblocal());
        baseHist.setNmancomunidades(this.getSelectedBaseLegal().getNmancomunidades());
        baseHist.setNdestacado(this.getSelectedBaseLegal().getNdestacado());
        baseHist.setVsumilla(this.getSelectedBaseLegal().getVsumilla());
        baseHist.setDfechavigencia(this.getSelectedBaseLegal().getDfechavigencia());
        baseHist.setVtema(this.getSelectedBaseLegal().getVtema());
        baseHist.setNactivo(this.getSelectedBaseLegal().getNactivo());
        baseHist.setNestadoid(this.getSelectedBaseLegal().getNestadoid());
        baseHist.setNversion(BigDecimal.valueOf(hist.getNversion().intValue() + 1));
        baseHist.setVusuariocreacion(user.getVlogin());
        baseHist.setDfechacreacion(new Date());
        baseHist.setVusuariomodificacion(this.getSelectedBaseLegal().getVusuariomodificacion());
        baseHist.setDfechamodificacion(this.getSelectedBaseLegal().getDfechamodificacion());
        serviceHistorial.saveOrUpdate(baseHist);

        Tbaselegal tbaselegal = new Tbaselegal();
        BeanUtils.copyProperties(tbaselegal, this.getSelectedBaseLegal());

        String ruta0 = this.pathBL + this.getSelectedBaseLegal().getNbaselegalid().toString() + "\\"
                + BigDecimal.ZERO.toString() + "\\";
        String txt0 = this.getSelectedBaseLegal().getVnombre();
        GcmFileUtils.writeStringToFileServer(ruta0, "plain.txt", txt0);
        String ruta1 = this.pathBL + this.getSelectedBaseLegal().getNbaselegalid().toString() + "\\"
                + baseHist.getNversion().toString() + "\\";
        String txt1 = baseHist.getVnombre();
        GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt", txt1);

        ArchivoService aservice = (ArchivoService) ServiceFinder.findBean("ArchivoService");
        Archivo archivo = aservice.getArchivoByBaseLegal(this.getSelectedBaseLegal());
        if (this.getUploadFile() != null) {
            ruta0 = this.path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "\\"
                    + BigDecimal.ZERO.toString() + "\\";
            archivo.setVnombre(this.getUploadFile().getFileName());
            archivo.setVruta(ruta0 + archivo.getVnombre());
            archivo.setVusuariomodificacion(user.getVlogin());
            archivo.setDfechamodificacion(new Date());
            aservice.saveOrUpdate(archivo);
            saveFile(ruta0);
        }

        ruta1 = this.path + this.getSelectedBaseLegal().getNbaselegalid().toString() + "\\"
                + baseHist.getNversion().toString() + "\\";
        ArchivoHistorialService aserviceHist = (ArchivoHistorialService) ServiceFinder
                .findBean("ArchivoHistorialService");
        ArchivoHist archivoHist = aserviceHist.getLastArchivoHistByBaseLegalHist(baseHist);
        archivoHist = archivoHist != null ? archivoHist : new ArchivoHist();
        archivoHist.setNarchivohistid(aserviceHist.getNextPK());
        archivoHist.setNhistorialid(baseHist.getNhistorialid());
        archivoHist.setNbaselegalid(baseHist.getNbaselegalid());
        archivoHist.setVnombre(archivo.getVnombre());
        archivoHist.setVruta(ruta1 + archivo.getVnombre());
        archivoHist.setVusuariocreacion(user.getVlogin());
        archivoHist.setDfechacreacion(new Date());
        aserviceHist.saveOrUpdate(archivoHist);
        saveFile(ruta1);

        VinculoBaseLegalService vservice = (VinculoBaseLegalService) ServiceFinder
                .findBean("VinculoBaseLegalService");
        vservice.deleteByBaseLegal(this.getSelectedBaseLegal());
        for (BaseLegal v : this.getListaTarget()) {
            TvinculoBaselegalId id = new TvinculoBaselegalId();
            id.setNbaselegalid(tbaselegal.getNbaselegalid());
            id.setNvinculoid(vservice.getNextPK());
            VinculoBaselegal vinculo = new VinculoBaselegal();
            vinculo.setId(id);
            vinculo.setTbaselegal(tbaselegal);
            vinculo.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculo.setNtipovinculo(v.getNestadoid());
            vinculo.setDfechacreacion(new Date());
            vinculo.setVusuariocreacion(user.getVlogin());
            vservice.saveOrUpdate(vinculo);

            BaseLegal blvinculada = service.getBaselegalById(v.getNbaselegalid());
            blvinculada.setNestadoid(v.getNestadoid());
            blvinculada.setDfechamodificacion(new Date());
            blvinculada.setVusuariomodificacion(user.getVlogin());
            service.saveOrUpdate(blvinculada);

            if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_MODIFICADA)
                    || v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_CONCORDADO)) {

                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                if (!CollectionUtils.isEmpty(listaConocimientos)) {
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getIdconocimiento());
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(user.getVlogin());
                        String descripcionHtml = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "html.txt");
                        String descripcionPlain = GcmFileUtils.readStringFromFileServer(conocimiento.getVruta(),
                                "plain.txt");
                        cservice.saveOrUpdate(conocimiento);

                        HistorialService historialService = (HistorialService) ServiceFinder
                                .findBean("HistorialService");
                        Historial lastHistorial = historialService
                                .getLastHistorialByConocimiento(conocimiento.getNconocimientoid());
                        int lastversion;
                        if (lastHistorial != null) {
                            lastversion = lastHistorial.getNnumversion().intValue();
                        } else {
                            lastversion = 0;
                        }
                        String newpath = "";
                        if (conocimiento.getNtipoconocimientoid().equals(Constante.BASELEGAL)) {
                            newpath = "bl/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.BUENAPRACTICA)) {
                            newpath = "bp/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.CONTENIDO)) {
                            newpath = "ct/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.OPORTUNIDADMEJORA)) {
                            newpath = "om/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.PREGUNTAS)) {
                            newpath = "pr/";
                        } else if (conocimiento.getNtipoconocimientoid().equals(Constante.WIKI)) {
                            newpath = "wk/";
                        }

                        String url = newpath.concat(conocimiento.getNconocimientoid().toString()).concat("/")
                                .concat(Integer.toString(lastversion + 1)).concat("/");

                        ThistorialId thistorialId = new ThistorialId();
                        thistorialId.setNconocimientoid(conocimiento.getNconocimientoid());
                        thistorialId.setNhistorialid(historialService.getNextPK());
                        Historial historial = new Historial();
                        historial.setId(thistorialId);
                        historial.setNtipoconocimientoid(conocimiento.getNtipoconocimientoid());
                        historial.setNcategoriaid(conocimiento.getNcategoriaid());
                        historial.setVtitulo(conocimiento.getVtitulo());
                        historial.setNactivo(BigDecimal.ONE);
                        historial.setNsituacionid(conocimiento.getNsituacionid());
                        historial.setVruta(url);
                        historial.setNnumversion(BigDecimal.valueOf(lastversion + 1));
                        historial.setDfechacreacion(new Date());
                        historial.setVusuariocreacion(user.getVlogin());
                        historialService.saveOrUpdate(historial);

                        GcmFileUtils.writeStringToFileServer(url, "html.txt", descripcionHtml);
                        GcmFileUtils.writeStringToFileServer(url, "plain.txt", descripcionPlain);

                        SeccionService seccionService = (SeccionService) ServiceFinder
                                .findBean("SeccionService");
                        SeccionHistService seccionHistService = (SeccionHistService) ServiceFinder
                                .findBean("SeccionHistService");
                        List<Seccion> listaSeccion = seccionService
                                .getSeccionesByConocimiento(conocimiento.getNconocimientoid());
                        if (!CollectionUtils.isEmpty(listaSeccion)) {
                            String url0 = conocimiento.getVruta().concat("s");
                            String url1 = url.concat("s");
                            for (Seccion seccion : listaSeccion) {
                                seccion.setDetalleHtml(
                                        GcmFileUtils.readStringFromFileServer(seccion.getVruta(), "html.txt"));
                                ruta0 = url0.concat(seccion.getNorden().toString()).concat("/");
                                seccion.setVruta(ruta0);
                                seccion.setDfechamodificacion(new Date());
                                seccion.setVusuariomodificacion(user.getVlogin());
                                seccionService.saveOrUpdate(seccion);

                                seccion.setDetallePlain(Jsoup.parse(seccion.getDetalleHtml()).text());

                                ruta1 = url1.concat(seccion.getNorden().toString()).concat("/");
                                TseccionHistId tseccionHistId = new TseccionHistId();
                                tseccionHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                                tseccionHistId.setNhistorialid(thistorialId.getNhistorialid());
                                tseccionHistId.setNseccionhid(seccionHistService.getNextPK());
                                SeccionHist seccionHist = new SeccionHist();
                                seccionHist.setId(tseccionHistId);
                                seccionHist.setNorden(seccion.getNorden());
                                seccionHist.setVruta(ruta1);
                                seccionHist.setVtitulo(seccion.getVtitulo());
                                seccionHist.setVusuariocreacion(user.getVlogin());
                                seccionHist.setDfechacreacion(new Date());
                                seccionHistService.saveOrUpdate(seccionHist);

                                GcmFileUtils.writeStringToFileServer(ruta1, "html.txt",
                                        seccion.getDetalleHtml());
                                GcmFileUtils.writeStringToFileServer(ruta1, "plain.txt",
                                        seccion.getDetallePlain());
                            }
                        }

                        VinculoService vinculoService = (VinculoService) ServiceFinder
                                .findBean("VinculoService");
                        Vinculo vinculoC = new Vinculo();
                        vinculoC.setNvinculoid(vinculoService.getNextPK());
                        vinculoC.setNconocimientoid(conocimiento.getNconocimientoid());
                        vinculoC.setNconocimientovinc(tbaselegal.getNbaselegalid());
                        vinculoC.setNtipoconocimientovinc(Constante.BASELEGAL);
                        vinculoC.setDfechacreacion(new Date());
                        vinculoC.setVusuariocreacion(user.getVlogin());
                        vinculoService.saveOrUpdate(vinculoC);

                        List<Vinculo> vinculos = vinculoService
                                .getVinculosByConocimiento(conocimiento.getNtipoconocimientoid());
                        VinculoHistService vinculoHistService = (VinculoHistService) ServiceFinder
                                .findBean("VinculoHistService");
                        for (Vinculo vinc : vinculos) {
                            TvinculoHistId vinculoHistId = new TvinculoHistId();
                            vinculoHistId.setNvinculohid(vinculoHistService.getNextPK());
                            vinculoHistId.setNconocimientoid(thistorialId.getNconocimientoid());
                            vinculoHistId.setNhistorialid(thistorialId.getNhistorialid());
                            VinculoHist vinculoHist = new VinculoHist();
                            vinculoHist.setId(vinculoHistId);
                            vinculoHist.setNconocimientovinc(vinc.getNconocimientovinc());
                            vinculoHist.setDfechacreacion(new Date());
                            vinculoHist.setVusuariocreacion(user.getVlogin());
                            vinculoHistService.saveOrUpdate(vinculoHist);
                        }
                    }
                }
            } else if (v.getNbaselegalid().toString().equals(Constante.ESTADO_BASELEGAL_DEROGADA)) {
                ConocimientoService cservice = (ConocimientoService) ServiceFinder
                        .findBean("ConocimientoService");
                List<Consulta> listaConocimientos = cservice
                        .getConcimientosByVinculoBaseLegalId(blvinculada.getNbaselegalid());
                if (!CollectionUtils.isEmpty(listaConocimientos)) {
                    for (Consulta c : listaConocimientos) {
                        Conocimiento conocimiento = cservice.getConocimientoById(c.getIdconocimiento());
                        conocimiento.setNflgvinculo(BigDecimal.ONE);
                        conocimiento.setDfechamodificacion(new Date());
                        conocimiento.setVusuariomodificacion(user.getVlogin());
                    }
                }
            }

            VinculoBaselegalHistorialService vserviceHist = (VinculoBaselegalHistorialService) ServiceFinder
                    .findBean("VinculoBaselegalHistorialService");
            VinculoBaselegalHist vinculoHist = new VinculoBaselegalHist();
            vinculoHist.setNvinculohistid(vserviceHist.getNextPK());
            vinculoHist.setNhistorialid(baseHist.getNhistorialid());
            vinculoHist.setNbaselegalid(baseHist.getNbaselegalid());
            vinculoHist.setNbaselegalvinculadaid(v.getNbaselegalid());
            vinculoHist.setNtipovinculo(v.getNestadoid());
            vinculoHist.setDfechacreacion(new Date());
            vinculoHist.setVusuariocreacion(user.getVlogin());
            vserviceHist.saveOrUpdate(vinculoHist);
        }

        this.setListaBaseLegal(service.getBaselegales());
        for (BaseLegal bl : this.getListaBaseLegal()) {
            bl.setArchivo(aservice.getArchivoByBaseLegal(bl));
        }
        FacesContext.getCurrentInstance().getExternalContext().redirect("/gescon/pages/baselegal/lista.xhtml");
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * The Gamma function./* w w  w .j ava 2  s.  c o  m*/
 *
 * @param x The argument.
 * @return Gamma(x).
 */
static public BigDecimal Gamma(final BigDecimal x) {
    /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
     */
    if (x.compareTo(BigDecimal.ZERO) < 0) {
        return divideRound(Gamma(x.add(BigDecimal.ONE)), x);
    } else if (x.doubleValue() > 1.5) {
        /* Gamma(x) = Gamma(xmin+n) = Gamma(xmin)*Pochhammer(xmin,n).
         */
        int n = (int) (x.doubleValue() - 0.5);
        BigDecimal xmin1 = x.subtract(new BigDecimal(n));

        return multiplyRound(Gamma(xmin1), pochhammer(xmin1, n));

    } else {
        /* apply Abramowitz-Stegun 6.1.33
         */
        BigDecimal z = x.subtract(BigDecimal.ONE);
        /* add intermediately 2 digits to the partial sum accumulation
         */
        z = scalePrec(z, 2);
        MathContext mcloc = new MathContext(z.precision());
        /* measure of the absolute error is the relative error in the first, logarithmic term
         */

        double eps = x.ulp().doubleValue() / x.doubleValue();
        BigDecimal resul = log(scalePrec(x, 2)).negate();

        if (x.compareTo(BigDecimal.ONE) != 0) {
            BigDecimal gammCompl = BigDecimal.ONE.subtract(gamma(mcloc));
            resul = resul.add(multiplyRound(z, gammCompl));

            for (int n = 2;; n++) {
                /* multiplying z^n/n by zeta(n-1) means that the two relative errors add.
                 * so the requirement in the relative error of zeta(n)-1 is that this is somewhat
                 * smaller than the relative error in z^n/n (the absolute error of thelatter is the
                 * absolute error in z)
                 */
                BigDecimal c = divideRound(z.pow(n, mcloc), n);
                MathContext m = new MathContext(err2prec(n * z.ulp().doubleValue() / 2. / z.doubleValue()));
                c = c.round(m);
                /* At larger n, zeta(n)-1 is roughly 1/2^n. The product is c/2^n.
                 * The relative error in c is c.ulp/2/c . The error in the product should be small versus eps/10.
                 * Error from 1/2^n is c*err(sigma-1).
                 * We need a relative error of zeta-1 of the order of c.ulp/50/c. This is an absolute
                 * error in zeta-1 of c.ulp/50/c/2^n, and also the absolute error in zeta, because zeta is
                 * of the order of 1.
                 */

                if (eps / 100. / c.doubleValue() < 0.01) {
                    m = new MathContext(err2prec(eps / 100. / c.doubleValue()));
                } else {
                    m = new MathContext(2);
                }
                /* zeta(n) -1 */
                BigDecimal zetm1 = zeta(n, m).subtract(BigDecimal.ONE);
                c = multiplyRound(c, zetm1);

                if (n % 2 == 0) {
                    resul = resul.add(c);
                } else {
                    resul = resul.subtract(c);
                }
                /* alternating sum, so truncating as eps is reached suffices
                 */

                if (Math.abs(c.doubleValue()) < eps) {
                    break;
                }

            }
        }
        /* The relative error in the result is the absolute error in the
         * input variable times the digamma (psi) value at that point.
         */
        double psi = 0.5772156649;

        double zdbl = z.doubleValue();

        for (int n = 1; n < 5; n++) {
            psi += zdbl / n / (n + zdbl);
        }
        eps = psi * x.ulp().doubleValue() / 2.;
        mcloc = new MathContext(err2prec(eps));

        return exp(resul).round(mcloc);

    }
}

From source file:org.marketcetera.strategy.LanguageTestBase.java

/**
 * Tests a strategy's ability to send arbitrary objects.
 *
 * @throws Exception if an error occurs/*  ww  w.  ja va 2 s  .c  o  m*/
 */
@Test
public void other() throws Exception {
    theStrategy = createStrategy(getOtherStrategy().getName(), getLanguage(), getOtherStrategy().getFile(),
            null, null, outputURN);
    // run the strategy with nothing set
    setPropertiesToNull();
    doOtherTest(theStrategy, new Object[0]);
    assertTrue(
            "Expected properties to be empty, but was: " + AbstractRunningStrategy.getProperties().toString(),
            AbstractRunningStrategy.getProperties().isEmpty());
    // have the strategy send null
    AbstractRunningStrategy.setProperty("sendNull", "true");
    doOtherTest(theStrategy, new Object[0]);
    // make sure only the property we set above is set
    assertEquals(1, AbstractRunningStrategy.getProperties().size());
    assertEquals(AbstractRunningStrategy.getProperty("sendNull"), "true");
    // have the strategy send a string
    setPropertiesToNull();
    AbstractRunningStrategy.setProperty("sendString", "true");
    doOtherTest(theStrategy, new Object[] { "test string" });
    assertEquals("Properties were " + AbstractRunningStrategy.getProperties(), 1,
            AbstractRunningStrategy.getProperties().size());
    assertEquals(AbstractRunningStrategy.getProperty("sendString"), "true");
    // have the strategy send two BigDecimals
    setPropertiesToNull();
    AbstractRunningStrategy.setProperty("sendTwo", "true");
    doOtherTest(theStrategy, new Object[] { BigDecimal.ONE, BigDecimal.TEN });
    assertEquals("Properties was " + AbstractRunningStrategy.getProperties(), 1,
            AbstractRunningStrategy.getProperties().size());
    assertEquals(AbstractRunningStrategy.getProperty("sendTwo"), "true");
    // route orders to strategy and check output
    setPropertiesToNull();
    theStrategy = createStrategy(getOtherStrategy().getName(), getLanguage(), getOtherStrategy().getFile(),
            null, true, outputURN);
    AbstractRunningStrategy.setProperty("sendTwo", "true");
    doOtherTest(theStrategy, new Object[] { BigDecimal.ONE, BigDecimal.TEN });
    assertEquals("Properties was " + AbstractRunningStrategy.getProperties(), 1,
            AbstractRunningStrategy.getProperties().size());
    assertEquals(AbstractRunningStrategy.getProperty("sendTwo"), "true");
}

From source file:org.efaps.esjp.accounting.transaction.FieldValue_Base.java

/**
 * @param _parameter Parameter as passed from the eFaps API
 * @return  default value for the currency field
 * @throws EFapsException on error/* w w w. j  ava  2  s.c  om*/
 */
public Return getRateFieldValue(final Parameter _parameter) throws EFapsException {
    final Return ret = new Return();
    ret.put(ReturnValues.VALUES, BigDecimal.ONE);
    return ret;
}

From source file:org.nd4j.linalg.util.BigDecimalMath.java

/**
 * Pochhammers function.//w  ww.ja v  a  2s .  c  o  m
 *
 * @param x The main argument.
 * @param n The non-negative index.
 * @return (x)_n = x(x+1)(x+2)*...*(x+n-1).
 */
static public BigDecimal pochhammer(final BigDecimal x, final int n) {
    /* reduce to interval near 1.0 with the functional relation, Abramowitz-Stegun 6.1.33
     */
    if (n < 0) {
        throw new ProviderException("Unimplemented pochhammer with negative index " + n);
    } else if (n == 0) {
        return BigDecimal.ONE;
    } else {
        /* internally two safety digits
         */
        BigDecimal xhighpr = scalePrec(x, 2);
        BigDecimal resul = xhighpr;

        double xUlpDbl = x.ulp().doubleValue();

        double xDbl = x.doubleValue();
        /* relative error of the result is the sum of the relative errors of the factors
         */

        double eps = 0.5 * xUlpDbl / Math.abs(xDbl);

        for (int i = 1; i < n; i++) {
            eps += 0.5 * xUlpDbl / Math.abs(xDbl + i);

            resul = resul.multiply(xhighpr.add(new BigDecimal(i)));
            final MathContext mcloc = new MathContext(4 + err2prec(eps));
            resul = resul.round(mcloc);

        }
        return resul.round(new MathContext(err2prec(eps)));

    }
}