Example usage for java.lang Long intValue

List of usage examples for java.lang Long intValue

Introduction

In this page you can find the example usage for java.lang Long intValue.

Prototype

public int intValue() 

Source Link

Document

Returns the value of this Long as an int after a narrowing primitive conversion.

Usage

From source file:gr.abiss.calipso.CalipsoServiceImpl.java

/**
 * Save new Items. This method is not intended for updates.
 *//*from w w  w  . j ava 2  s.  com*/
@Override
public synchronized void storeItem(Item item, Map<String, FileUpload> fileUploadsMap) {
    try {

        if (item.getLoggedBy() != null && item.getLoggedBy().isAnonymous()) {
            item.setLoggedBy(null);
        }
        if (item.getReportedBy() != null && item.getReportedBy().isAnonymous()) {
            item.setReportedBy(null);
        }

        // run plugins
        runPreStateChangePlugins(item);
        History history = new History(item);
        // copy attachments
        copyAttachmentsToHistory(item, history);

        Date now = new Date();
        item.setTimeStamp(now);
        history.setTimeStamp(now);
        item.add(history);
        SpaceSequence spaceSequence = dao.loadSpaceSequence(item.getSpace().getSpaceSequence().getId());
        item.setSequenceNum(spaceSequence.next());
        // the synchronize for this storeItem method and the hibernate flush()
        // call in the dao implementation
        // are important to prevent duplicate sequence numbers
        dao.storeSpaceSequence(spaceSequence);
        // just call attachment.setPermanent false in case we had temp
        // attachments for some reason
        makeAttachmentsPermanent(history);

        // due to, state due to
        Map<Integer, Long> stateDurations = dao.getCachedMetadataForSpace(item.getSpace())
                .getStatesDurationMap();
        if (MapUtils.isNotEmpty(stateDurations)) {
            Long stateDuration = stateDurations.get(item.getStatus());
            if (stateDuration != null) {
                Date stateDeadline = new Date(now.getTime() + stateDuration.intValue());
                item.setStateDueTo(stateDeadline);
            }
        }

        // set default duration if the space offers one and the item has none
        // set
        if (item.getDueTo() == null && item.getSpace().getDefaultDuration() != null) {
            item.setDueTo(new Date(now.getTime() + item.getSpace().getDefaultDuration().longValue()));
        }

        // this will at the moment execute unnecessary updates (bug in Hibernate
        // handling of "version" property)
        // see
        // http://opensource.atlassian.com/projects/hibernate/browse/HHH-1401
        // TODO confirm if above does not happen anymore
        dao.storeItem(item);
        // maybe no file uploads were given,
        // e.g. when just updating Assets
        if (fileUploadsMap != null) {
            // store the physical files *after* database persistence to
            // produce proper ID-based file paths
            //
            //            logger.debug("makePermanentAttachmentFiles, attachments: "
            //                  + history.getAttachments() + ", uploadsMap: "
            //                  + fileUploadsMap);
            AttachmentUtils.makePermanentAttachmentFiles(history.getAttachments(), fileUploadsMap, calipsoHome);
        } else if (history.getAttachments() != null) {
            // we got attachments but no file uploads?
            throw new RuntimeException("Attachments contain no physical files");
        } else {
            logger.debug("No attachment files were given");
        }
        // update attachment info
        this.dao.saveOrUpdateAll(history.getAttachments());
        //
        //         logger.debug("storeItem: Before calling runStatePlugins, itemStatus: "
        //               + item.getStatusValue() + ", historyStatus: "
        //               + history.getStatusValue());
        // run any plugins as neccessary
        runPostStateChangePlugins(history, item);

        // update indexes
        indexer.index(item);
        indexer.index(history);
        if (item.isSendNotifications()) {
            mailSender.send(item);
        }

    } catch (RuntimeException e) {
        logger.error("Failed to persist item", e);
    }

}

From source file:gr.abiss.calipso.CalipsoServiceImpl.java

@Override
public synchronized void storeHistoryForItem(long itemId, Map<String, FileUpload> fileUploads,
        History history) {/*ww  w .j  ava  2  s  . c om*/
    try {

        Date now = new Date();

        Item item = dao.loadItem(itemId);
        this.runPreStateChangePlugins(item);
        // keep a ref to file uploads
        for (String filename : fileUploads.keySet()) {
            FileUpload upload = fileUploads.get(filename);
            String extention = upload.getClientFileName()
                    .substring(upload.getClientFileName().lastIndexOf('.'));
            // String filename = upload.getClientFileName();
            Attachment attachment = new Attachment();
            attachment.setSpace(item.getSpace());
            attachment.setItem(item);
            attachment.setHistory(history);

            attachment.setFileName(filename + extention);
            attachment.setOriginalFileName(upload.getClientFileName());
            attachment.setSimple(filename.equalsIgnoreCase(Field.FIELD_TYPE_SIMPLE_ATTACHEMENT));
            // logger.debug("storeHistoryForItem: making attachment with filename: "
            // + attachment.getFileName());
            attachment.setTemporary(false);
            // attachments to Item, replacing others with the same name if
            // needed
            AttachmentUtils.addAndReplaceSameNamed(history, attachment);
        }

        // first apply edits onto item record before we change the item
        // status
        // the item.getEditableFieldList routine depends on the current
        // State of
        // the item
        for (Field field : item.getEditableFieldList(history.getLoggedBy())) {
            Object value = history.getValue(field.getName());
            // logger.info("Before setting item's '"+field.getName()+"' value from:"
            // + item.getValue(field.getName())+", to:"+value);
            if (value != null) {
                item.setValue(field.getName(), value);
            }
        }
        if (history.getStatus() != null) {
            // in case of state change, update the state due to
            if (!history.getStatus().equals(item.getStatus())) {
                // reset notifications
                item.setSentDueToNotifications(false);

                // get the new (i.e. the history) state duration
                Map<Integer, Long> stateDurations = item.getSpace().getMetadata().getStatesDurationMap();
                if (MapUtils.isNotEmpty(stateDurations)) {
                    Long stateDuration = stateDurations.get(history.getStatus());
                    if (stateDuration != null) {
                        Date stateDeadline = new Date(now.getTime() + stateDuration.intValue());
                        item.setStateDueTo(stateDeadline);
                    }
                }
            }
            item.setStatus(history.getStatus());
            item.setAssignedTo(history.getAssignedTo()); // this may be
            // null,
            // when closing
        }
        if (history.getDueTo() != null) {
            item.setDueTo(history.getDueTo());
        }
        if (history.getActualEffort() != null && history.getActualEffort().intValue() == 0) {
            history.setActualEffort(null);
        }
        if (history.getPlannedEffort() != null && history.getPlannedEffort().intValue() > 0) {
            item.setPlannedEffort(history.getPlannedEffort());
        }

        item.setItemUsers(history.getItemUsers());
        history.setTimeStamp(new Date());
        // replace and move to permanent storage
        item.add(history);

        this.runPreHistorySavePlugins(history);
        dao.save(history);
        // update item with the latest, replacing name conflicts
        AttachmentUtils.replaceAttachments(item, history.getAttachments());
        dao.update(item);
        // maybe no file uploads were given,
        // e.g. when just updating Assets
        if (fileUploads != null) {
            // store the physical files *after* database persistence to
            // produce proper ID-based file paths
            if (logger.isDebugEnabled()) {
                logger.debug("makePermanentAttachmentFiles, attachments: " + history.getAttachments()
                        + ", uploadsMap: " + fileUploads);
            }
            AttachmentUtils.makePermanentAttachmentFiles(history.getAttachments(), fileUploads, calipsoHome);
        }

        runPostStateChangePlugins(history, item);

        indexer.index(history);
        indexer.index(item);
        if (history.isSendNotifications()) {
            mailSender.send(item);
        }

    } catch (Exception w) {
        logger.error("storeHistoryForItem failed to persist", w);
        throw RuntimeException.class.isAssignableFrom(w.getClass()) ? (RuntimeException) w
                : new RuntimeException(w);
    }
}

From source file:com.youanmi.scrm.smp.facade.org.OrgInfoFacade.java

/**
 *
 * ?/*from  ww w  . j a  va2s  . com*/
 *
 * @param param ?
 */
public void orgDetailSingleEdit(OrgDetailParam param) {
    Long currentTimeStamp = System.currentTimeMillis();

    // Long orgId = param.getOrgId();
    Long orgId = UserTokenThreadLocal.get().getOrgId();
    String name = param.getName();
    Long provinceId = param.getProvinceId();
    Long cityId = param.getCityId();
    Long areaId = param.getAreaId();
    String address = param.getAddress();

    // 1.
    if (orgId == null) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "id");
    }
    if (StringUtils.isBlank(name)) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "??");
    }
    if (provinceId == null) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "?");
    }
    if (cityId == null) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "");
    }
    if (areaId == null) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "");
    }
    if (StringUtils.isBlank(address)) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_NOT_NULL, "?");
    }

    // ??50
    if (address.length() > AccountTableConstants.Org.MAX_DETAIL_ADDRESS_LENGTH) {
        throw new ViewExternalDisplayException(ResultCode.System.PARAMETER_LENGTH_BEYOND, "?");
    }

    // ??????
    boolean flag = this.uniqueneOrgName(name, orgId);
    if (!flag) {
        throw new ViewExternalDisplayException(ResultCode.Org.ORG_NAME_REPEAT);
    }

    // 2.?
    OrgDetailInfoDto dto = new OrgDetailInfoDto();
    dto.setOrgId(orgId);
    dto.setProvinceId(provinceId);
    dto.setCityId(cityId);
    dto.setAreaId(areaId);
    dto.setAddress(address);

    String provinceName = null;
    GeogProvincePo provincePo = geogProvinceService.selectByPrimaryKey(provinceId.intValue());
    if (provincePo != null) {
        provinceName = provincePo.getName();
        dto.setProvinceName(provinceName);
    }

    String cityName = null;
    GeogCityPo cityPo = geogCityService.selectByPrimaryKey(cityId.intValue());
    if (cityPo != null) {
        cityName = cityPo.getName();
        dto.setCityName(cityName);
    }

    String areaName = null;
    GeogAreaPo areaPo = geogAreaService.selectByPrimaryKey(areaId.intValue());
    if (areaPo != null) {
        areaName = areaPo.getName();
        dto.setAreaName(areaName);
    }

    // ????
    if (StringUtils.isBlank(provinceName) || StringUtils.isBlank(cityName) || StringUtils.isBlank(areaName)) {
        throw new ViewExternalDisplayException(ResultCode.System.ILLEGALITY_REQUEST);
    }

    dto.setUpdateTime(currentTimeStamp);
    orgDetailInfoService.updateByParam(dto);

    // 3.org
    OrgInfoDto updateOrgInfoDto = new OrgInfoDto();
    updateOrgInfoDto.setId(orgId);
    updateOrgInfoDto.setOrgName(name);
    updateOrgInfoDto.setUpdateTime(currentTimeStamp);
    orgInfoService.updateByPrimaryKeySelective(updateOrgInfoDto);

}

From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasicPlus.CatBasicPlusControllerImpl.java

private boolean validateBasicPlusTechnical(LomAvanzadoVO lomAdvanced, Locale locale, Collection errorMessages) {
    // Validate the LOM technical section with the criteria specified
    // for the BasicPlus cataloguer. This code is borrowed from the Advanced
    // Cataloguer with a few modifications.   

    ResourceBundle datosResources = I18n.getInstance().getResource("application-resources", locale);
    String resultado = "";
    boolean ok = true;

    String nombre = "";
    String tipo = "";

    AvTechnicalVO tec = lomAdvanced.getTechnical();

    //TIPO+NOMBRE
    ok = true;//from  ww  w .  j  av a2 s  . c  om
    int i = 0;
    while ((ok) && (tec.getRequisitos() != null && i < tec.getRequisitos().length)) {
        AgregadorORVO[] cat = tec.getRequisitos()[i].getAgregadoresOR();
        if (cat != null && cat.length > 0) {
            int j = 0;
            while ((ok) && (j < cat.length)) {
                SourceValueVO sNombre = cat[j].getNombre();
                SourceValueVO sTipo = cat[j].getTipo();
                if (sNombre != null) {
                    nombre = sNombre.getValor();
                }

                if (nombre == null || nombre.length() == 0) {
                    errorMessages.add(datosResources.getString("CAV.4.4.1.2"));
                }

                if (sTipo != null) {
                    tipo = sTipo.getValor();
                }

                if (tipo == null || tipo.length() == 0) {
                    errorMessages.add(datosResources.getString("CAV.4.4.1.1"));
                }
                if (resultado.length() != 0) {
                    ok = false;
                } else {
                    j++;
                }

            }
        }
        if (resultado.length() != 0) {
            ok = false;
        } else
            i++;

    }

    //DURACION
    boolean todosVacios = true;
    boolean duracionVacia = false;

    String descripcion;
    if (tec.getDuracion() != null) {
        if ((tec.getDuracion().getDescripcion() != null)
                && (tec.getDuracion().getDescripcion().getTextos() != null)
                && (tec.getDuracion().getDescripcion().getTextos().length > 0)) {
            for (i = 0; i < tec.getDuracion().getDescripcion().getTextos().length && todosVacios; i++) {
                descripcion = tec.getDuracion().getDescripcion().getTextos()[i].getTexto();
                if (descripcion != null && descripcion.trim().length() != 0) {
                    todosVacios = false;
                }
            }
        }

        //DURACION

        // MCA: Note that technical duration is optional (only for continuous play media)
        // MCA: Use the new CataloguerDuration class to handle this easily :)
        CataloguerDuration cd = new CataloguerDuration(tec.getDuracion().getDuracion());

        if ((cd.getYears() == null || cd.getYears().trim().length() == 0)
                && (cd.getMonths() == null || cd.getMonths().trim().length() == 0)
                && (cd.getDays() == null || cd.getDays().trim().length() == 0)
                && (cd.getHours() == null || cd.getHours().trim().length() == 0)
                && (cd.getMinutes() == null || cd.getMinutes().trim().length() == 0)
                && (cd.getSeconds() == null || cd.getSeconds().trim().length() == 0)) {
            //si alguno de los campos dia, mes o anyo esta vacio, fecha esta vacio
            duracionVacia = true;
        }

        if (todosVacios && !duracionVacia)
            errorMessages.add(datosResources.getString("CAV.4.7.2"));//La descripci&oacute;n dela duraci&oacute;n es obligatoria si existe una duraci&oacute;n
        if (!todosVacios && duracionVacia)
            errorMessages.add(datosResources.getString("CAV.4.7.1"));//La duraci&oacute;n es obligatoria si existe una descripci&oacute;n de duraci&oacute;n
    }

    // Size
    TamanioVO size = tec.getTamanio();
    if (size != null && size.getTexto() != null && size.getTexto().length() != 0) {
        try {
            Long bigSize = new Long(size.getTexto());
            if (bigSize.intValue() < 0) {
                errorMessages.add(datosResources.getString("CAV.4.1"));//Meterle la validacin del integer no negativo
            }
        } catch (Exception e) {
            errorMessages.add(datosResources.getString("CAV.4.1"));//Meterle la validacin del integer no negativo
        }
    }

    if (errorMessages.size() > 0) {
        return false;
    } else {
        return true;
    }

}

From source file:com.archsystemsinc.ipms.sec.webapp.controller.HomeController.java

@RequestMapping(value = "/dashboard/{id}", method = RequestMethod.GET)
public String home(@PathVariable("id") final Long id, final Model model, final Principal principal) {
    try {/* w  w w . j a  v  a  2 s.c o  m*/
        final com.archsystemsinc.ipms.sec.model.Principal currentUser = principalService
                .findByName(principal.getName());

        //         OrganizationGroup organizationGroup = organizationGroupService.findOne(id);
        //         List<String> entityTypes = new ArrayList<String>();
        //         entityTypes.add("Project");
        //         entityTypes.add("Program");
        //         
        //         model.addAttribute("programs", programService.findProgramListByOrganizationGroup(organizationGroup));
        //         
        ////         final List<Program> programs = projectService.findUserProjects(currentUser);
        ////         for (Project aProject : projects) {
        ////            final Project project = projectService.findOne(aProject.getId());
        ////            List<ProjectEvm> projectEvmList = projectEvmService.findByProjectOrderByDateAsc(project);
        ////            projectEvmMap.put(aProject.getId(), projectEvmList);
        ////         }
        //         
        //         model.addAttribute("artifactEvents",
        //               userActivityService.findByEntityTypeInOrderByDateCreatedDesc(entityTypes));
        //         model.addAttribute("meetings", meetingService.findByInvited(currentUser.getName()));
        //         model.addAttribute("tasks", taskService.findCurrentUserTasks(currentUser));
        //         
        //         final List<Project> projects = projectService.findUserProjects(currentUser);
        //         model.addAttribute("actionItems", actionItemService.findCurrentUserActionItems(currentUser));
        //         model.addAttribute("referenceData", referenceData());
        //         Map<Long, List<ProjectEvm>> projectEvmMap = new HashMap<Long, List<ProjectEvm>>();
        //         for (Project aProject : projects) {
        //            final Project project = projectService.findOne(aProject.getId());
        //            List<ProjectEvm> projectEvmList = projectEvmService.findByProjectOrderByDateAsc(project);
        //            projectEvmMap.put(aProject.getId(), projectEvmList);
        //         }
        //         model.addAttribute("projects", projects);
        //         model.addAttribute("projectEvmMap", projectEvmMap);
        // dev-ops testing

        OrganizationGroup organizationGroup = organizationGroupService.findOne(id);
        List<String> entityTypes = new ArrayList<String>();
        List<Program> programs = new ArrayList<Program>();
        entityTypes.add("Project");
        entityTypes.add("Program");

        List<Program> allPrograms = programService
                .findProgramListByOrganizationGroup(organizationGroupService.findOne(1L));

        for (Program aProgram : allPrograms) {
            switch (id.intValue()) {
            case 2:
                switch (aProgram.getName()) {
                case "Seamless Care Models Group(CEC)":
                case "Seamless Care Models Group (NextGen)":
                    programs.add(aProgram);
                    break;
                default:
                    break;
                }
                break;
            case 4:
                break;
            default:
                break;
            }
        }

        model.addAttribute("programs", programs);

        model.addAttribute("artifactEvents",
                userActivityService.findByEntityTypeInOrderByDateCreatedDesc(entityTypes));
        model.addAttribute("meetings", meetingService.findByInvited(currentUser.getName()));
        model.addAttribute("tasks", taskService.findCurrentUserTasks(currentUser));

        final List<Project> projects = projectService.findUserProjects(currentUser);
        model.addAttribute("actionItems", actionItemService.findCurrentUserActionItems(currentUser));
        model.addAttribute("referenceData", referenceData());
        Map<Long, List<ProjectEvm>> projectEvmMap = new HashMap<Long, List<ProjectEvm>>();
        for (Project aProject : projects) {
            //            switch(programService.findOne(aProject.getProgramId()).getName()){
            //               case "Seamless Care Models Group(CEC)":
            //               case "Seamless Care Models Group (NextGEN)":               
            //                  final Project project = projectService.findOne(aProject.getId());
            //                  List<ProjectEvm> projectEvmList = projectEvmService.findByProjectOrderByDateAsc(project);
            //                  projectEvmMap.put(aProject.getId(), projectEvmList);
            //                   break;            
            //               default:               
            //                   break;
            //            }
            //            if( programService.findOne(aProject.getProgramId()).getName() == id){
            //               final Project project = projectService.findOne(aProject.getId());
            //               List<ProjectEvm> projectEvmList = projectEvmService.findByProjectOrderByDateAsc(project);
            //               projectEvmMap.put(aProject.getId(), projectEvmList);
            //            }
        }
        model.addAttribute("projects", projects);
        model.addAttribute("projectEvmMap", projectEvmMap);
        switch (id.intValue()) {
        case 1:
            model.addAttribute("view", "dashboard");
            break;
        case 2:
            model.addAttribute("view", "seamless");
            break;
        default:
            model.addAttribute("view", "dashboard");
            break;
        }
        //model.addAttribute("view", "dashboard");
        model.addAttribute("currentUser", currentUser);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "dashboard";
}

From source file:com.netscape.ca.CertificateAuthority.java

/**
 * read ca cert from path, converts and bytes
 *//* w ww  .j ava2  s . c o m*/
byte[] getCertFromFile(String path) throws FileNotFoundException, IOException {

    File file = new File(path);
    Long l = Long.valueOf(file.length());
    byte[] b = new byte[l.intValue()];
    FileInputStream in = null;
    try {
        in = new FileInputStream(path);
        in.read(b);
    } finally {
        if (in != null)
            in.close();
    }
    return b;
}

From source file:com.gst.portfolio.loanaccount.service.LoanWritePlatformServiceJpaRepositoryImpl.java

public LoanOverdueDTO applyChargeToOverdueLoanInstallment(final Long loanId, final Long loanChargeId,
        final Integer periodNumber, final JsonCommand command, Loan loan,
        final List<Long> existingTransactionIds, final List<Long> existingReversedTransactionIds) {
    boolean runInterestRecalculation = false;
    final Charge chargeDefinition = this.chargeRepository.findOneWithNotFoundDetection(loanChargeId);

    Collection<Integer> frequencyNumbers = loanChargeReadPlatformService
            .retrieveOverdueInstallmentChargeFrequencyNumber(loanId, chargeDefinition.getId(), periodNumber);

    Integer feeFrequency = chargeDefinition.feeFrequency();
    final ScheduledDateGenerator scheduledDateGenerator = new DefaultScheduledDateGenerator();
    Map<Integer, LocalDate> scheduleDates = new HashMap<>();
    final Long penaltyWaitPeriodValue = this.configurationDomainService.retrievePenaltyWaitPeriod();
    final Long penaltyPostingWaitPeriodValue = this.configurationDomainService
            .retrieveGraceOnPenaltyPostingPeriod();
    final LocalDate dueDate = command.localDateValueOfParameterNamed("dueDate");
    Long diff = penaltyWaitPeriodValue + 1 - penaltyPostingWaitPeriodValue;
    if (diff < 0) {
        diff = 0L;/* w w w . j  a  v a2 s .c o m*/
    }
    LocalDate startDate = dueDate.plusDays(penaltyWaitPeriodValue.intValue() + 1);
    Integer frequencyNunber = 1;
    if (feeFrequency == null) {
        scheduleDates.put(frequencyNunber++, startDate.minusDays(diff.intValue()));
    } else {
        while (DateUtils.getLocalDateOfTenant().isAfter(startDate)) {
            scheduleDates.put(frequencyNunber++, startDate.minusDays(diff.intValue()));
            LocalDate scheduleDate = scheduledDateGenerator.getRepaymentPeriodDate(
                    PeriodFrequencyType.fromInt(feeFrequency), chargeDefinition.feeInterval(), startDate, null,
                    null);

            startDate = scheduleDate;
        }
    }

    for (Integer frequency : frequencyNumbers) {
        scheduleDates.remove(frequency);
    }

    LoanRepaymentScheduleInstallment installment = null;
    LocalDate lastChargeAppliedDate = dueDate;
    if (!scheduleDates.isEmpty()) {
        if (loan == null) {
            loan = this.loanAssembler.assembleFrom(loanId);
            checkClientOrGroupActive(loan);
            existingTransactionIds.addAll(loan.findExistingTransactionIds());
            existingReversedTransactionIds.addAll(loan.findExistingReversedTransactionIds());
        }
        installment = loan.fetchRepaymentScheduleInstallment(periodNumber);
        lastChargeAppliedDate = installment.getDueDate();
    }
    LocalDate recalculateFrom = DateUtils.getLocalDateOfTenant();

    if (loan != null) {
        this.businessEventNotifierService.notifyBusinessEventToBeExecuted(
                BUSINESS_EVENTS.LOAN_APPLY_OVERDUE_CHARGE, constructEntityMap(BUSINESS_ENTITY.LOAN, loan));
        for (Map.Entry<Integer, LocalDate> entry : scheduleDates.entrySet()) {

            final LoanCharge loanCharge = LoanCharge.createNewFromJson(loan, chargeDefinition, command,
                    entry.getValue());

            LoanOverdueInstallmentCharge overdueInstallmentCharge = new LoanOverdueInstallmentCharge(loanCharge,
                    installment, entry.getKey());
            loanCharge.updateOverdueInstallmentCharge(overdueInstallmentCharge);

            boolean isAppliedOnBackDate = addCharge(loan, chargeDefinition, loanCharge);
            runInterestRecalculation = runInterestRecalculation || isAppliedOnBackDate;
            if (entry.getValue().isBefore(recalculateFrom)) {
                recalculateFrom = entry.getValue();
            }
            if (entry.getValue().isAfter(lastChargeAppliedDate)) {
                lastChargeAppliedDate = entry.getValue();
            }
        }
    }

    return new LoanOverdueDTO(loan, runInterestRecalculation, recalculateFrom, lastChargeAppliedDate);
}

From source file:com.flexive.ejb.beans.AccountEngineBean.java

private void _updateUser(long accountId, String password, boolean hashPassword, String name, String loginName,
        String email, Long lang) throws FxApplicationException {
    // Load the account to update
    Account account = load(accountId);//  ww  w . j a  v  a2s  .c o  m

    final UserTicket ticket = FxContext.getUserTicket();
    if (ticket.getUserId() != accountId) {
        if (!ticket.isGlobalSupervisor()
                || !(ticket.isMandatorSupervisor() && account.getMandatorId() == ticket.getMandatorId()))
            throw new FxNoAccessException(LOG, "ex.account.update.noPermission", account.getName());
    }

    // Parameter checks
    if (loginName != null)
        loginName = checkLoginName(loginName);
    if (email != null)
        email = FxFormatUtils.checkEmail(email);
    if (password != null && hashPassword) {
        password = FxFormatUtils.encodePassword(accountId, account.getLoginName(), password.trim());
    }

    if (lang != null && !language.isValid(lang))
        throw new FxInvalidParameterException("LANGUAGE", "ex.account.languageInvalid", lang);

    Connection con = null;
    PreparedStatement stmt = null;
    String curSql;

    if (name == null)
        name = account.getName();
    if (loginName == null)
        loginName = account.getLoginName();
    if (email == null)
        email = account.getEmail();
    if (lang == null)
        lang = account.getLanguage().getId();

    try {
        // Obtain a database connection
        con = Database.getDbConnection();

        curSql = "UPDATE " + TBL_ACCOUNTS + " SET " +
        // 1      2           3            4              5             6                                    7
                "EMAIL=?,LANG=?, USERNAME=?,LOGIN_NAME=?, MODIFIED_BY=?,MODIFIED_AT=?"
                + ((password != null) ? ",PASSWORD=?" : "") + " WHERE ID=" + accountId;
        stmt = con.prepareStatement(curSql);
        stmt.setString(1, email);
        stmt.setInt(2, lang.intValue());
        stmt.setString(3, name);
        stmt.setString(4, loginName);

        stmt.setLong(5, ticket.getUserId());
        stmt.setLong(6, System.currentTimeMillis());

        if (password != null)
            stmt.setString(7, password);
        stmt.executeUpdate();

        // Ensure any active ticket of the updated user are refreshed
        UserTicketStore.flagDirtyHavingUserId(account.getId());
    } catch (SQLException exc) {
        final boolean uniqueConstraintViolation = StorageManager.isUniqueConstraintViolation(exc);
        EJBUtils.rollback(ctx);
        if (uniqueConstraintViolation) {
            throw new FxEntryExistsException(LOG, "ex.account.userExists", name, loginName);
        } else {
            throw new FxUpdateException(LOG, "ex.account.update.failed.sql", account.getLoginName(),
                    exc.getMessage());
        }
    } finally {
        Database.closeObjects(AccountEngineBean.class, con, stmt);
    }
}

From source file:com.cloud.host.dao.HostDaoImpl.java

@Override
@DB//from  www .  j  a  v  a 2s  . co  m
public List<HostVO> findAndUpdateDirectAgentToLoad(long lastPingSecondsAfter, Long limit,
        long managementServerId) {
    TransactionLegacy txn = TransactionLegacy.currentTxn();

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Resetting hosts suitable for reconnect");
    }
    // reset hosts that are suitable candidates for reconnect
    resetHosts(managementServerId, lastPingSecondsAfter);
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Completed resetting hosts suitable for reconnect");
    }

    List<HostVO> assignedHosts = new ArrayList<HostVO>();

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Acquiring hosts for clusters already owned by this management server");
    }
    List<Long> clusters = findClustersOwnedByManagementServer(managementServerId);
    txn.start();
    if (clusters.size() > 0) {
        // handle clusters already owned by @managementServerId
        SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
        sc.setParameters("lastPinged", lastPingSecondsAfter);
        sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
        sc.setParameters("clusterIn", clusters.toArray());
        List<HostVO> unmanagedHosts = lockRows(sc, new Filter(HostVO.class, "clusterId", true, 0L, limit),
                true); // host belongs to clusters owned by @managementServerId
        StringBuilder sb = new StringBuilder();
        for (HostVO host : unmanagedHosts) {
            host.setManagementServerId(managementServerId);
            update(host.getId(), host);
            assignedHosts.add(host);
            sb.append(host.getId());
            sb.append(" ");
        }
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Following hosts got acquired for clusters already owned: " + sb.toString());
        }
    }
    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Completed acquiring hosts for clusters already owned by this management server");
    }

    if (assignedHosts.size() < limit) {
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Acquiring hosts for clusters not owned by any management server");
        }
        // for remaining hosts not owned by any MS check if they can be owned (by owning full cluster)
        clusters = findClustersForHostsNotOwnedByAnyManagementServer();
        List<Long> updatedClusters = clusters;
        if (clusters.size() > limit) {
            updatedClusters = clusters.subList(0, limit.intValue());
        }
        if (updatedClusters.size() > 0) {
            SearchCriteria<HostVO> sc = UnmanagedDirectConnectSearch.create();
            sc.setParameters("lastPinged", lastPingSecondsAfter);
            sc.setJoinParameters("ClusterManagedSearch", "managed", Managed.ManagedState.Managed);
            sc.setParameters("clusterIn", updatedClusters.toArray());
            List<HostVO> unmanagedHosts = lockRows(sc, null, true);

            // group hosts based on cluster
            Map<Long, List<HostVO>> hostMap = new HashMap<Long, List<HostVO>>();
            for (HostVO host : unmanagedHosts) {
                if (hostMap.get(host.getClusterId()) == null) {
                    hostMap.put(host.getClusterId(), new ArrayList<HostVO>());
                }
                hostMap.get(host.getClusterId()).add(host);
            }

            StringBuilder sb = new StringBuilder();
            for (Long clusterId : hostMap.keySet()) {
                if (canOwnCluster(clusterId)) { // cluster is not owned by any other MS, so @managementServerId can own it
                    List<HostVO> hostList = hostMap.get(clusterId);
                    for (HostVO host : hostList) {
                        host.setManagementServerId(managementServerId);
                        update(host.getId(), host);
                        assignedHosts.add(host);
                        sb.append(host.getId());
                        sb.append(" ");
                    }
                }
                if (assignedHosts.size() > limit) {
                    break;
                }
            }
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Following hosts got acquired from newly owned clusters: " + sb.toString());
            }
        }
        if (s_logger.isDebugEnabled()) {
            s_logger.debug("Completed acquiring hosts for clusters not owned by any management server");
        }
    }
    txn.commit();

    return assignedHosts;
}

From source file:org.opennms.ng.services.capsd.BroadcastEventProcessor.java

/**
 * Helper method that takes IP address from the force rescan event,
 * retrieves the nodeid (JDBC) and adds it to the rescan schedule for immediate
 * processing when the next thread is available.
 *
 * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
 * @throws org.opennms.netmgt.capsd.InsufficientInformationException if any.
 *//* ww  w  . j av  a 2s . co m*/
@EventHandler(uei = EventConstants.FORCE_RESCAN_EVENT_UEI)
public void handleForceRescan(Event event) throws InsufficientInformationException {
    // If the event has a node identifier use it otherwise
    // will need to use the interface to lookup the node id
    // from the database
    Long nodeid = -1L;

    if (event.hasNodeid()) {
        nodeid = event.getNodeid();
    } else {
        // Extract interface from the event and use it to
        // lookup the node identifier associated with the
        // interface from the database.
        //

        // ensure the ipaddr is set
        EventUtils.checkInterface(event);

        // Get database connection and retrieve nodeid
        Connection dbc = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        final DBUtils d = new DBUtils(getClass());
        try {
            dbc = getConnection();
            d.watch(dbc);

            // Retrieve node id
            stmt = dbc.prepareStatement(SQL_RETRIEVE_NODEID);
            d.watch(stmt);
            stmt.setString(1, event.getInterface());
            rs = stmt.executeQuery();
            d.watch(rs);
            if (rs.next()) {
                nodeid = rs.getLong(1);
            }
        } catch (SQLException sqlE) {
            LOG.error("handleForceRescan: Database error during nodeid retrieval for interface {}",
                    event.getInterface(), sqlE);
        } finally {
            d.cleanUp();
        }
    }

    if (nodeid == null || nodeid == -1) {
        LOG.error("handleForceRescan: Nodeid retrieval for interface {} failed.  Unable to perform rescan.",
                event.getInterface());
        return;
    }

    // discard this forceRescan if one is already enqueued for the same node ID
    if (RescanProcessor.isRescanQueuedForNode(nodeid.intValue())) {
        LOG.info(
                "Ignoring forceRescan event for node {} because a forceRescan for that node already exists in the queue",
                nodeid);
        return;
    }

    // Rescan the node.
    m_scheduler.forceRescan(nodeid.intValue());
}