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:och.front.service.FrontAppTest.java

private void test_billing_paySync() throws Exception {

     MapProps props = new MapProps();
     props.putVal(admin_Emails, "some@host");
     props.putVal(paypal_sync_debug_DisableTimer, true);
     props.putVal(mail_storeToDisc, false);

     MailServiceStub mailService = new MailServiceStub(mailSender, props);

     PaypalClientStub clientStub = new PaypalClientStub();
     ArrayList<PaymentExt> syncPaymentsByDate = new ArrayList<PaymentExt>();
     ArrayList<PaymentExt> syncPaymentsById = new ArrayList<PaymentExt>();
     boolean[] canSync = { false };

     //service//  w  w  w  .  ja  v  a 2s.c  o m
     PaypalPaymentsSynchService syncService = new PaypalPaymentsSynchService() {
         @Override
         protected void syncPaymentsByDate(List<PaymentExt> list, Date now) {
             syncPaymentsByDate.clear();
             syncPaymentsByDate.addAll(list);
             if (canSync[0])
                 super.syncPaymentsByDate(list, now);
         }

         @Override
         protected void syncPaymentsByIdAsync(List<PaymentExt> list, Date now) {
             syncPaymentsById.clear();
             syncPaymentsById.addAll(list);
             if (canSync[0])
                 super.syncPaymentsByIdAsync(list, now);
         }
     };
     syncService.setCacheServerContext(new CacheServerContext(props, cacheSever, db, mailService));
     syncService.setClient(clientStub);
     syncService.init();

     Date now = new Date();
     Date minuteAgo = new Date(now.getTime() - DateUtil.ONE_MINUTE);
     Date twoHoursAgo = new Date(now.getTime() - DateUtil.ONE_HOUR * 2);
     Date monthAgo = DateUtil.addDays(now, -31);

     long userId = 103L;
     //fill db
     universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p1",
             WAIT, minuteAgo, minuteAgo, BigDecimal.ONE)));
     universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p2",
             WAIT, twoHoursAgo, twoHoursAgo, BigDecimal.ONE)));
     universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p3",
             WAIT, monthAgo, monthAgo, BigDecimal.ONE)));

     //check filter logic
     pushToSecurityContext_SYSTEM_USER();
     try {

         assertEquals(0, billing.getUserBalance(userId).intValue());

         //first call -- all payments to sync
         {
             syncService.doSyncWork(now);
             assertEquals(2, syncPaymentsByDate.size());
             assertEquals(1, syncPaymentsById.size());
             assertEquals("p1", syncPaymentsByDate.get(0).externalId);
             assertEquals("p2", syncPaymentsByDate.get(1).externalId);
             assertEquals("p3", syncPaymentsById.get(0).externalId);
             syncPaymentsByDate.clear();
             syncPaymentsById.clear();
         }

         //second call -- only new
         now = new Date(now.getTime() + 1000);
         {
             syncService.doSyncWork(now);
             assertEquals(1, syncPaymentsByDate.size());
             assertEquals(0, syncPaymentsById.size());
             assertEquals("p1", syncPaymentsByDate.get(0).externalId);
             syncPaymentsByDate.clear();
             syncPaymentsById.clear();
         }

         //next call -- same
         now = new Date(now.getTime() + 1000);
         {
             syncService.doSyncWork(now);
             assertEquals(1, syncPaymentsByDate.size());
             assertEquals(0, syncPaymentsById.size());
             assertEquals("p1", syncPaymentsByDate.get(0).externalId);
             syncPaymentsByDate.clear();
             syncPaymentsById.clear();
         }

         //after long delta -- all
         now = new Date(now.getTime() + 1000);
         props.putVal(paypal_sync_longUpdateDelta, 0);
         {
             syncService.doSyncWork(now);
             assertEquals(2, syncPaymentsByDate.size());
             assertEquals(1, syncPaymentsById.size());
             syncPaymentsByDate.clear();
             syncPaymentsById.clear();
         }

         now = new Date(now.getTime() + 1000);
         props.putVal(paypal_sync_longUpdateDelta, paypal_sync_longUpdateDelta.longDefVal());
         {
             syncService.doSyncWork(now);
             assertEquals(1, syncPaymentsByDate.size());
             assertEquals(0, syncPaymentsById.size());
             assertEquals("p1", syncPaymentsByDate.get(0).externalId);
             syncPaymentsByDate.clear();
             syncPaymentsById.clear();
         }
     } finally {
         popUserFromSecurityContext();
     }

     //sync by 
     pushToSecurityContext_SYSTEM_USER();
     try {

         canSync[0] = true;

         //update by date
         now = new Date(now.getTime() + 1000);
         assertEquals(WAIT, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p1")).paymentStatus);
         clientStub.paymentHistory = list(new PaymentBase("p1", COMPLETED));
         syncService.doSyncWork(now);
         assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p1")).paymentStatus);
         assertEquals(1, universal.selectOne(new SelectUserBalanceById(userId)).balance.intValue());
         assertEquals(1, billing.getUserBalance(userId).intValue());

         //update by ids
         now = new Date(now.getTime() + 1000);
         props.putVal(paypal_sync_longUpdateDelta, 0);
         clientStub.paymentHistory = list(new PaymentBase("p2", COMPLETED));
         clientStub.paymentId = "p3";
         clientStub.payment = new PaymentBase(clientStub.paymentId, COMPLETED);
         syncService.doSyncWork(now);
         assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p2")).paymentStatus);
         assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p3")).paymentStatus);
         assertEquals(3, billing.getUserBalance(userId).intValue());

         now = new Date(now.getTime() + 1000);
         syncPaymentsByDate.clear();
         syncPaymentsById.clear();
         syncService.doSyncWork(now);
         assertEquals(0, syncPaymentsByDate.size());
         assertEquals(0, syncPaymentsById.size());

     } finally {
         popUserFromSecurityContext();
     }

     //test timers
     props.putVal(paypal_sync_debug_DisableTimer, false);
     props.putVal(paypal_sync_timerDelay, 1L);
     props.putVal(paypal_sync_timerDelta, 20L);
     syncService.stop();
     syncService.init();
     pushToSecurityContext_SYSTEM_USER();
     try {
         canSync[0] = true;
         clientStub.paymentHistory = list(new PaymentBase("p4", COMPLETED));
         universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p4",
                 WAIT, minuteAgo, minuteAgo, BigDecimal.ONE)));

         Thread.sleep(50);

         assertEquals(COMPLETED, universal.selectOne(new GetPaymentByExternalId(PAYPAL, "p4")).paymentStatus);
         assertEquals(4, billing.getUserBalance(userId).intValue());
     } finally {
         syncService.stop();
         popUserFromSecurityContext();
     }

     //test send errors to admin
     props.putVal(paypal_sync_sendErrorsDelay, 1L);
     props.putVal(paypal_sync_sendErrorsDelta, 20L);
     syncService.init();
     try {
         universal.update(new CreatePayment(new PaymentExt(universal.nextSeqFor(payments), userId, PAYPAL, "p5",
                 WAIT, minuteAgo, minuteAgo, BigDecimal.ONE)));

         mailSender.tasks.clear();
         clientStub.paymentHistory = null;

         Thread.sleep(100);
         assertTrue(mailSender.tasks.size() > 0);

         //dissable send errors
         props.putVal(paypal_sync_debug_DisableSendErrors, true);
         Thread.sleep(50);
         mailSender.tasks.clear();
         Thread.sleep(50);
         assertTrue(mailSender.tasks.size() == 0);

         //enable again
         props.putVal(paypal_sync_debug_DisableSendErrors, false);
         Thread.sleep(50);
         assertTrue(mailSender.tasks.size() > 0);

         //set filter
         props.putVal(paypal_sync_skipErrorTerms, "empty history by daysBefore");
         Thread.sleep(50);
         mailSender.tasks.clear();
         Thread.sleep(50);
         assertTrue(mailSender.tasks.size() == 0);

         //remove filter
         props.putVal(paypal_sync_skipErrorTerms, (String) null);
         Thread.sleep(50);
         assertTrue(mailSender.tasks.size() > 0);

     } finally {
         syncService.stop();
     }

 }

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

public String update() throws Exception {
    String pagina = "";
    try {/*from   w w  w  . j a v  a  2  s .c om*/
        /* 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());
        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().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());
        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 " + 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);

        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:com.ugam.collage.plus.service.people_count.impl.PeopleAccountingServiceImpl.java

/**
 * @param yearId/*  w ww .  j  a v a2 s . c o m*/
 * @param monthId
 * @param costCentreId
 * @param empcntClientProjectDataList
 * @param employee
 * @param month
 * @param year
 * @param costCentre
 * @param countType
 * @param allignedTimeOne
 * @param assistedTimeOne
 * @param apportionedTimeOne
 * @param totalTimeOne
 */
private void getZeroProjectsDetail(Integer yearId, Integer monthId, String costCentreId,
        List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal allignedTimeZero,
        BigDecimal assistedTimeZero, BigDecimal apportionedTimeOne, BigDecimal totalTimeOne,
        Integer countTypeId, Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getZeroProjectsDetail START====>");
    Integer employeeId = employee.getEmployeeId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    logger.debug("getZeroProjectsDetail parameter===>" + employeeId + "::" + yearId + "::" + monthId + "::"
            + costCentreId + "::" + deviderHour);

    // 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 (projectIdList.isEmpty()) {
        BigDecimal remainProportion = BigDecimal.ONE;
        Map<Integer, BigDecimal> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList, employee,
                month, year, costCentre, countType, remainProportion, assignedProjectsHour, countTypeId,
                employeePcTagsTeamStructMap);
    } else {
        // logger.debug("Else Project details present in execution data ===>");
        // 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);
            }

        }
        // 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> assignedProjectsHour = new HashMap<Integer, BigDecimal>();
        Map<Integer, Integer> assignedProjectsCompany = new HashMap<Integer, Integer>();
        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 (validAllProjects.contains(projectId)) {
                // logger.debug("UnAssignedProjects===>" +
                // projectId+"::"+hour+"::"+companyId);
                assignedProjectsHour.put(projectId, hour);
                assignedProjectsCompany.put(projectId, companyId);
            }

        }
        /*
         * Do the calculation as per time spent on projects and put it to
         * assisted count
         */
        // 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 : assignedProjectsCompany.keySet()) {
                // Get time spent on each project by employee id
                Integer projectId = key;
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("1254 :Both in assigned and unassigned projects======>"+totalTimeOne);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedTimeZero, apportionedTimeOne, totalTimeOne);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
        } else {
            // logger.debug("Worked hours===> <168");
            BigDecimal revenueProportion = BigDecimal.ZERO;

            for (Integer key : assignedProjectsHour.keySet()) {
                Integer projectId = key;
                // logger.debug("projectId===> "+projectId);
                BigDecimal timeByProject = assignedProjectsHour.get(key);
                Integer companyIdByProject = assignedProjectsCompany.get(key);
                ProjectMaster projectMaster = new ProjectMaster();
                projectMaster.setProjectId(projectId);
                CompanyMaster companyMaster = new CompanyMaster();
                companyMaster.setCompanyId(companyIdByProject);
                // logger.debug("timeByProject===> "+timeByProject);
                BigDecimal assistedHours = timeByProject.divide(deviderHour, 2, RoundingMode.HALF_EVEN);
                assistedHours = assistedHours.setScale(2, RoundingMode.CEILING);
                // logger.debug("assignedProjectsHour===> "+assingnedHours);
                revenueProportion = revenueProportion.add(assistedHours);
                logger.debug("1338 :======>" + revenueProportion);
                EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                        companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                        assistedHours, allignedTimeZero, assistedHours);
                if (countTypeId == 1) {
                    empOpenCntClientProjectDataList.add(empcntClientProjectData);
                }
                if (countTypeId == 2) {
                    empCloseCntClientProjectDataList.add(empcntClientProjectData);
                }
            }
            /*
             * Revenue count put it to apportioned count
             */
            // logger.debug("revenueProportion===> "+revenueProportion);
            if (revenueProportion.compareTo(BigDecimal.ONE) == -1) {
                BigDecimal remainProportion = BigDecimal.ONE.subtract(revenueProportion);
                logger.debug("remainProportion===> " + remainProportion);
                getRevenueCountProportion(empOpenCntClientProjectDataList, empCloseCntClientProjectDataList,
                        employee, month, year, costCentre, countType, remainProportion, assignedProjectsHour,
                        countTypeId, employeePcTagsTeamStructMap);
            }
        }
    }
    // logger.debug("<====getZeroProjectDetail END====>");
}

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

public void post(ActionEvent event) {
    try {/* w  w  w .jav  a  2  s  .  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()
                .setNestadoid(BigDecimal.valueOf(Long.valueOf(Constante.ESTADO_BASELEGAL_PUBLICADO)));
        this.getSelectedBaseLegal().setDfechapublicacion(new Date());
        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.setDfechapublicacion(this.getSelectedBaseLegal().getDfechapublicacion());
        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);
        }

        List<Asignacion> listaAsignacion = service.obtenerBaseLegalxAsig(
                this.getSelectedBaseLegal().getNbaselegalid(), user.getNusuarioid(), Constante.BASELEGAL);
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(listaAsignacion)) {
            Asignacion asignacion = listaAsignacion.get(0);
            asignacion.setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
            if (asignacion.getDfecharecepcion() == null) {
                asignacion.setDfecharecepcion(new Date());
            }
            asignacion.setDfechaatencion(new Date());
            asignacion.setNaccionid(BigDecimal.valueOf(Long.parseLong("8")));
            AsignacionService asignacionService = (AsignacionService) ServiceFinder
                    .findBean("AsignacionService");
            asignacionService.saveOrUpdate(asignacion);
        }

        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:pe.gob.mef.gescon.web.ui.PendienteMB.java

public String DevEsp() {
    String pagina = null;//from w  w  w . j a  va  2s . c  o  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 "";
            }
        }
        PreguntaService service = (PreguntaService) ServiceFinder.findBean("PreguntaService");
        this.getSelectedPregunta().setNdestacado(this.getChkDestacado() ? BigDecimal.ONE : BigDecimal.ZERO);
        this.getSelectedPregunta().setNsituacionid(BigDecimal.valueOf((long) 2));
        service.saveOrUpdate(this.getSelectedPregunta());

        AsignacionService serviceasig = (AsignacionService) ServiceFinder.findBean("AsignacionService");
        this.getSelectedAsignacion().setNestadoid(BigDecimal.valueOf(Long.parseLong("2")));
        this.getSelectedAsignacion().setNaccionid(BigDecimal.valueOf(Long.parseLong("12")));
        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())
                .getNespecialista());
        asignacion.setDfechacreacion(new Date());
        asignacion.setDfechaasignacion(new Date());
        serviceasig.saveOrUpdate(asignacion);

        LoginMB loginMB = (LoginMB) JSFUtils.getSessionAttribute("loginMB");
        loginMB.refreshNotifications();

        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

/**
 *
 *///from ww  w . ja v a  2s .c o m
private void getRevenueCountProportion(List<EmpcntClientProjectData> empOpenCntClientProjectDataList,
        List<EmpcntClientProjectData> empCloseCntClientProjectDataList, EmployeeMaster employee, TabMonth month,
        TabYear year, CostCentre costCentre, CountClassification countType, BigDecimal remainProportion,
        Map<Integer, BigDecimal> unAssignedProjects, Integer countTypeId,
        Map<String, EmployeePcTagsTeamStruct> employeePcTagsTeamStructMap) {

    logger.debug("<====getRevenueCountProportion Start====>");
    logger.debug("unAssignedProjects:" + unAssignedProjects.size());
    // get the EmpCntPcApportionApproach for the employee
    Integer employeeId = employee.getEmployeeId();
    Integer yearId = year.getYearId();
    Integer monthId = month.getMonthId();
    String costCentreId = costCentre.getCostCentreId();
    BigDecimal deviderHour = new BigDecimal(Constants.TOTAL_WORKING_HOURS);
    Integer apportionApproach = 0;
    BigDecimal allignedTimeZero = BigDecimal.ZERO;
    BigDecimal asistededTimeZero = BigDecimal.ZERO;
    List<EmpCntPcApportionApproach> empCntPcApportionApproachList = empCntPcApportionApproachDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);
    if (!empCntPcApportionApproachList.isEmpty()) {
        apportionApproach = empCntPcApportionApproachList.get(0).getApportionApproach();
    } else {
        return;
    }

    // logger.debug("1363 : apportionApproach===> "+apportionApproach);
    // get the EmployeePcTagsTeamStruct for the employee
    List<EmployeePcTagsTeamStruct> employeePcTagsTeamStructList = employeePcTagsTeamStructDao
            .findByYearIdMonthIdEmployeeId(yearId, monthId, employeeId);

    if (apportionApproach == 1) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();

            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);

            // asissted projects on count
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {
                // Select valid project id
                for (CollageProjectRevenue proRevenue : collageProjectRevenueList) {
                    Integer projectId = proRevenue.getProjectMaster().getProjectId();
                    if (unAssignedProjects.isEmpty()) {
                        revenueMap.put(projectId, proRevenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            revenueMap.put(projectId, proRevenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                        }
                    }

                }

                Integer projectCount = revenueMap.size();
                count = new BigDecimal(projectCount);
                if (projectCount > 0) {
                    for (Integer key : revenueMap.keySet()) {
                        BigDecimal projectValue = BigDecimal.ONE.divide(count, 2, RoundingMode.HALF_EVEN);
                        projectValue = projectValue.multiply(pcProportion);
                        ProjectMaster projectMaster = projectMap.get(key);
                        CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                        projectValue = projectValue.setScale(2, RoundingMode.CEILING);
                        // logger.debug("1406 projectValue:======>"+projectValue);
                        EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                                companyMaster, countType, month, projectMaster, year, costCentre,
                                allignedTimeZero, asistededTimeZero, projectValue, projectValue);
                        if (countTypeId == 1) {
                            empOpenCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        if (countTypeId == 2) {
                            empCloseCntClientProjectDataList.add(empcntClientProjectData);
                        }
                        // copy proprotion
                        String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                        EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                        employeePcTagsTeamStructCopy.setApportionedCnt(projectValue);
                        employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                    }
                }
            }
        }
    } else if (apportionApproach == 2) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            BigDecimal count = BigDecimal.ZERO;
            Map<Integer, BigDecimal> hoursMap = new HashMap<Integer, BigDecimal>();
            Map<Integer, Integer> companyMap = new HashMap<Integer, Integer>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal hoursSum = BigDecimal.ZERO;

            List<Object[]> objectList = executionDataDao.findByYearIdMonthIdCostCentreIdProfitCentreId(yearId,
                    monthId, costCentreId, profitcentreId);

            if (!objectList.isEmpty()) {

                for (Object[] result : objectList) {
                    Integer projectId = (Integer) result[0];
                    BigDecimal hour = (BigDecimal) result[1];
                    Integer companyId = (Integer) result[2];
                    if (unAssignedProjects.isEmpty()) {
                        hoursMap.put(projectId, hour);
                        companyMap.put(projectId, companyId);
                        hoursSum.add(hour);
                    } else {
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            hoursMap.put(projectId, hour);
                            companyMap.put(projectId, companyId);
                            hoursSum.add(hour);
                        }
                    }
                }
                for (Integer projectId : hoursMap.keySet()) {
                    BigDecimal hour = hoursMap.get(projectId);
                    ProjectMaster projectMaster = new ProjectMaster();
                    projectMaster.setProjectId(projectId);
                    Integer companyId = companyMap.get(projectId);
                    CompanyMaster companyMaster = new CompanyMaster();
                    companyMaster.setCompanyId(companyId);
                    BigDecimal resultHour = hour.divide(hoursSum, 2, RoundingMode.HALF_EVEN);
                    resultHour = resultHour.multiply(pcProportion);
                    resultHour = resultHour.setScale(2, RoundingMode.CEILING);
                    // logger.debug("1462 :resultHour=====>"+resultHour);
                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, asistededTimeZero,
                            allignedTimeZero, resultHour, resultHour);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(resultHour);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }
    } else if (apportionApproach == 3) {
        for (EmployeePcTagsTeamStruct employeePcTagsTeamStruct : employeePcTagsTeamStructList) {
            Map<Integer, CollageProjectRevenue> revenueMap = new HashMap<Integer, CollageProjectRevenue>();
            Map<Integer, ProjectMaster> projectMap = new HashMap<Integer, ProjectMaster>();

            BigDecimal proportion = employeePcTagsTeamStruct.getProportion();
            BigDecimal devider = new BigDecimal(100);
            proportion = proportion.divide(devider);
            logger.debug("===========================================>" + proportion);
            String profitcentreId = employeePcTagsTeamStruct.getProfitCentre().getProfitCentreId();
            // Calculate for each profit centre
            BigDecimal pcProportion = proportion.multiply(remainProportion);
            BigDecimal revenueSum = BigDecimal.ZERO;
            List<CollageProjectRevenue> collageProjectRevenueList = collageProjectRevenueDao
                    .findByYearIdMonthIdProfitCentreIdCostCentreId(yearId, monthId, profitcentreId,
                            costCentreId);
            if (!collageProjectRevenueList.isEmpty()) {

                for (CollageProjectRevenue revenue : collageProjectRevenueList) {
                    if (unAssignedProjects.isEmpty()) {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        logger.debug("1497 =projectId====>" + projectId);
                        revenueMap.put(projectId, revenue);
                        List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                        projectMap.put(projectId, projectList.get(0));
                        BigDecimal revenueVal = revenue.getRevenueValue();
                        // logger.debug("1503 =RevenueValue====>"+revenueVal);
                        revenueSum = revenueSum.add(revenueVal);
                    } else {
                        Integer projectId = revenue.getProjectMaster().getProjectId();
                        if (unAssignedProjects.containsKey(projectId) == false) {
                            // logger.debug("1507 =projectId====>"+projectId);
                            revenueMap.put(projectId, revenue);
                            List<ProjectMaster> projectList = projectMasterDao.findByProjectId(projectId);
                            projectMap.put(projectId, projectList.get(0));
                            BigDecimal revenueVal = revenue.getRevenueValue();
                            // logger.debug("1514 =RevenueValue====>"+revenue.getRevenueValue()
                            // +" : "+revenueVal);
                            revenueSum = revenueSum.add(revenueVal);

                        }
                    }
                }
                logger.debug("1543 =revenueSum====>" + revenueSum);
                for (Integer projectId : revenueMap.keySet()) {
                    CollageProjectRevenue collageProjectRevenue = revenueMap.get(projectId);
                    ProjectMaster projectMaster = projectMap.get(projectId);
                    CompanyMaster companyMaster = projectMaster.getCompanyMaster();
                    BigDecimal revenueValue = collageProjectRevenue.getRevenueValue();

                    logger.debug("1516 =revenueSum : revenueValue====>" + revenueSum + " : " + revenueValue);
                    revenueValue = revenueValue.divide(revenueSum, 2, RoundingMode.HALF_EVEN);
                    revenueValue = revenueValue.multiply(pcProportion);
                    revenueValue = revenueValue.setScale(2, RoundingMode.CEILING);
                    logger.debug("1515 :Aportioned Count======>" + revenueValue);

                    EmpcntClientProjectData empcntClientProjectData = new EmpcntClientProjectData(employee,
                            companyMaster, countType, month, projectMaster, year, costCentre, allignedTimeZero,
                            asistededTimeZero, revenueValue, revenueValue);
                    if (countTypeId == 1) {
                        empOpenCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    if (countTypeId == 2) {
                        empCloseCntClientProjectDataList.add(empcntClientProjectData);
                    }
                    // copy proprotion
                    String mapId = yearId + "-" + monthId + "-" + employeeId + "-" + profitcentreId;
                    EmployeePcTagsTeamStruct employeePcTagsTeamStructCopy = employeePcTagsTeamStruct;
                    employeePcTagsTeamStructCopy.setApportionedCnt(revenueValue);
                    employeePcTagsTeamStructMap.put(mapId, employeePcTagsTeamStructCopy);
                }
            }

        }

    }
    // logger.debug("<====getRevenueCountProportion End====>");
}

From source file:org.apache.ofbiz.shipment.thirdparty.usps.UspsServices.java

public static Integer[] convertPoundsToPoundsOunces(BigDecimal decimalPounds) {
    if (decimalPounds == null)
        return null;
    Integer[] poundsOunces = new Integer[2];
    poundsOunces[0] = Integer.valueOf(decimalPounds.setScale(0, BigDecimal.ROUND_FLOOR).toPlainString());
    // (weight % 1) * 16 rounded up to nearest whole number
    poundsOunces[1] = Integer.valueOf(decimalPounds.remainder(BigDecimal.ONE).multiply(new BigDecimal("16"))
            .setScale(0, BigDecimal.ROUND_CEILING).toPlainString());
    return poundsOunces;
}

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

public void savePregEdit(ActionEvent event) {
    String pagina = "/gescon/index.xhtml";
    try {/*from w w w.  j  av  a2 s.  c  om*/
        //this.getSelectedPregunta().setVrespuesta(JSFUtils.getRequestParameter("descHtml"));
        /* 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());
            cat_nueva = this.getSelectedPregunta().getNcategoriaid();
        } else {
            this.getSelectedPregunta().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
            cat_nueva = this.getSelectedPregunta().getNcategoriaid();
        }
        this.getSelectedPregunta().setVasunto(this.getSelectedPregunta().getVasunto().trim());
        this.getSelectedPregunta().setVdetalle(this.getSelectedPregunta().getVdetalle().trim());
        this.getSelectedPregunta().setNentidadid(this.getSelectedPregunta().getNentidadid());
        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().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());
        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);

        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);

        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_savepreg.getVlogin());
                vinculopreguntaService.saveOrUpdate(vinculopregunta);
            }
        }

        if (cat_antigua != cat_nueva) {
            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("12")));
            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.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);
        }
        loginMB.refreshNotifications();
        FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "INFO.",
                "Actualizacin exitosa!.");
        FacesContext.getCurrentInstance().addMessage(null, message);
        FacesContext.getCurrentInstance().getExternalContext().redirect(pagina);
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }

}

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

public String savePregEditE() {
    String pagina = null;//  w  ww .ja  v  a  2  s. c om
    try {

        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());
            cat_nueva = this.getSelectedPregunta().getNcategoriaid();
        } else {
            this.getSelectedPregunta().setNcategoriaid(this.getSelectedCategoria().getNcategoriaid());
            cat_nueva = this.getSelectedPregunta().getNcategoriaid();
        }
        this.getSelectedPregunta().setVasunto(this.getSelectedPregunta().getVasunto().trim());
        this.getSelectedPregunta().setVdetalle(this.getSelectedPregunta().getVdetalle().trim());
        this.getSelectedPregunta().setNentidadid(this.getSelectedPregunta().getNentidadid());
        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().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());
        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);

        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);

        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_savepreg.getVlogin());
                vinculopreguntaService.saveOrUpdate(vinculopregunta);
            }
        }

        if (cat_antigua != cat_nueva) {
            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("12")));
            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()).getNespecialista());
            asignacion.setDfechaasignacion(new Date());
            asignacion.setDfechacreacion(new Date());
            serviceasig.saveOrUpdate(asignacion);

            pagina = "/index.xhtml";
        } else {
            pagina = "";
        }
        loginMB.refreshNotifications();
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
    }
    return pagina;

}

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

public String toView() {
    try {/*  ww w.ja v  a 2 s .  co m*/
        this.cleanAttributes();
        int index = Integer.parseInt((String) JSFUtils.getRequestParameter("index"));
        if (!CollectionUtils.isEmpty(this.getFilteredListaBaseLegal())) {
            this.setSelectedBaseLegal(this.getFilteredListaBaseLegal().get(index));
        } else {
            this.setSelectedBaseLegal(this.getListaBaseLegal().get(index));
        }
        CategoriaService categoriaService = (CategoriaService) ServiceFinder.findBean("CategoriaService");
        this.setSelectedCategoria(
                categoriaService.getCategoriaById(this.getSelectedBaseLegal().getNcategoriaid()));
        index = this.getSelectedBaseLegal().getVnumero().indexOf("-");
        this.setTipoNorma(this.getSelectedBaseLegal().getVnumero().substring(0, index).trim());
        this.setNumeroNorma(this.getSelectedBaseLegal().getVnumero().substring(index + 1).trim());
        this.setChkGobNacional(this.getSelectedBaseLegal().getNgobnacional().equals(BigDecimal.ONE));
        this.setChkGobRegional(this.getSelectedBaseLegal().getNgobregional().equals(BigDecimal.ONE));
        this.setChkGobLocal(this.getSelectedBaseLegal().getNgoblocal().equals(BigDecimal.ONE));
        this.setChkMancomunidades(this.getSelectedBaseLegal().getNmancomunidades().equals(BigDecimal.ONE));
        this.setChkDestacado(this.getSelectedBaseLegal().getNdestacado().equals(BigDecimal.ONE));
        RangoService rangoService = (RangoService) ServiceFinder.findBean("RangoService");
        this.setListaRangos(
                new Items(rangoService.getRangosActivosByTipo(this.getSelectedBaseLegal().getNtiporangoid()),
                        null, "nrangoid", "vnombre").getItems());
        BaseLegalService service = (BaseLegalService) ServiceFinder.findBean("BaseLegalService");
        this.setListaTarget(service.getTbaselegalesLinkedById(this.getSelectedBaseLegal().getNbaselegalid()));
        this.setFilteredListaBaseLegal(new ArrayList());
    } catch (Exception e) {
        e.getMessage();
        e.printStackTrace();
    }
    return "/pages/baselegal/ver?faces-redirect=true";
}