Example usage for java.lang Integer shortValue

List of usage examples for java.lang Integer shortValue

Introduction

In this page you can find the example usage for java.lang Integer shortValue.

Prototype

public short shortValue() 

Source Link

Document

Returns the value of this Integer as a short after a narrowing primitive conversion.

Usage

From source file:org.mifos.application.servicefacade.LoanAccountServiceFacadeWebTier.java

private LoanCreationResultDto createLoanAccount(CreateLoanAccount loanAccountInfo,
        List<LoanPaymentDto> backdatedLoanPayments, List<QuestionGroupDetail> questionGroups,
        LoanAccountCashFlow loanAccountCashFlow, List<DateTime> loanScheduleInstallmentDates,
        List<Number> totalInstallmentAmounts, List<GroupMemberAccountDto> memberDetails,
        boolean isBackdatedLoan) {

    DateTime creationDate = new DateTime();

    // 0. verify member details for GLIM group accounts
    for (GroupMemberAccountDto groupMemberAccount : memberDetails) {
        ClientBO member = this.customerDao.findClientBySystemId(groupMemberAccount.getGlobalId());
        if (creationDate.isBefore(new DateTime(member.getCreatedDate()))) {
            throw new BusinessRuleException("errors.cannotCreateLoan.because.clientsAreCreatedInFuture");
        }//from   w w  w.j a v  a  2  s.  c  o  m
    }

    // 1. assemble loan details
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    OfficeBO userOffice = this.officeDao.findOfficeById(user.getBranchId());
    PersonnelBO createdBy = this.personnelDao.findPersonnelById(userContext.getId());
    CustomerBO customer = this.customerDao.findCustomerById(loanAccountInfo.getCustomerId());
    if (customer.isGroup()) {
        customer = this.customerDao.findGroupBySystemId(customer.getGlobalCustNum());
    }

    // assemble
    LoanAccountDetail loanAccountDetail = assembleLoanAccountDetail(loanAccountInfo);

    List<AccountFeesEntity> accountFeeEntities = assembleAccountFees(loanAccountInfo.getAccountFees());
    List<AccountPenaltiesEntity> accountPenaltyEntities = assembleAccountPenalties(
            loanAccountInfo.getAccountPenalties());
    LoanProductOverridenDetail overridenDetail = new LoanProductOverridenDetail(
            loanAccountDetail.getLoanAmount(), loanAccountInfo.getDisbursementDate(),
            loanAccountInfo.getInterestRate(), loanAccountInfo.getNumberOfInstallments(),
            loanAccountInfo.getGraceDuration(), accountFeeEntities, accountPenaltyEntities);

    Integer interestDays = Integer.valueOf(AccountingRules.getNumberOfInterestDays().intValue());
    boolean loanScheduleIndependentOfCustomerMeetingEnabled = loanAccountInfo
            .isRepaymentScheduleIndependentOfCustomerMeeting();
    LoanScheduleConfiguration configuration = new LoanScheduleConfiguration(
            loanScheduleIndependentOfCustomerMeetingEnabled, interestDays);

    MeetingBO repaymentDayMeeting = loanAccountDetail.getCustomer().getCustomerMeetingValue();
    if (loanScheduleIndependentOfCustomerMeetingEnabled) {
        repaymentDayMeeting = this.createNewMeetingForRepaymentDay(loanAccountInfo.getDisbursementDate(),
                loanAccountInfo, loanAccountDetail.getCustomer());
    }

    List<DateTime> loanScheduleDates = new ArrayList<DateTime>(loanScheduleInstallmentDates);

    LoanSchedule loanSchedule = assembleLoanSchedule(loanAccountDetail.getCustomer(),
            loanAccountDetail.getLoanProduct(), overridenDetail, configuration, repaymentDayMeeting, userOffice,
            loanScheduleDates, loanAccountInfo.getDisbursementDate(), totalInstallmentAmounts);

    // 2. create loan
    InstallmentRange installmentRange = new MaxMinNoOfInstall(
            loanAccountInfo.getMinAllowedNumberOfInstallments().shortValue(),
            loanAccountInfo.getMaxAllowedNumberOfInstallments().shortValue(), null);
    AmountRange amountRange = new MaxMinLoanAmount(loanAccountInfo.getMaxAllowedLoanAmount().doubleValue(),
            loanAccountInfo.getMinAllowedLoanAmount().doubleValue(), null);

    if (isBackdatedLoan) {
        creationDate = loanAccountInfo.getDisbursementDate().toDateMidnight().toDateTime();
    }
    CreationDetail creationDetail = new CreationDetail(creationDate, Integer.valueOf(user.getUserId()));
    LoanBO loan = LoanBO.openStandardLoanAccount(loanAccountDetail.getLoanProduct(),
            loanAccountDetail.getCustomer(), repaymentDayMeeting, loanSchedule,
            loanAccountDetail.getAccountState(), loanAccountDetail.getFund(), overridenDetail, configuration,
            installmentRange, amountRange, creationDetail, createdBy);
    loan.setBusinessActivityId(loanAccountInfo.getLoanPurposeId());
    loan.setExternalId(loanAccountInfo.getExternalId());
    loan.setCollateralNote(loanAccountInfo.getCollateralNotes());
    loan.setCollateralTypeId(loanAccountInfo.getCollateralTypeId());

    if (isBackdatedLoan) {
        loan.markAsCreatedWithBackdatedPayments();
    }

    try {
        transactionHelper.startTransaction();
        this.loanDao.save(loan);
        transactionHelper.flushSession();
        try {
            loan.setGlobalAccountNum(loan.generateId(userOffice.getGlobalOfficeNum()));
        } catch (AccountException e) {
            throw new BusinessRuleException(e.getMessage());
        }
        this.loanDao.save(loan);
        transactionHelper.flushSession();

        // for GLIM loans only
        List<GroupMemberLoanDetail> individualMembersOfGroupLoan = new ArrayList<GroupMemberLoanDetail>();
        List<BigDecimal> radio = new ArrayList<BigDecimal>(loan.getNoOfInstallments());
        for (GroupMemberAccountDto groupMemberAccount : memberDetails) {
            ClientBO member = this.customerDao.findClientBySystemId(groupMemberAccount.getGlobalId());
            Money loanAmount = new Money(loanAccountDetail.getLoanProduct().getCurrency(),
                    groupMemberAccount.getLoanAmount());
            List<CreateAccountFeeDto> defaultAccountFees = new ArrayList<CreateAccountFeeDto>();
            List<CreateAccountPenaltyDto> defaultAccountPenalties = new ArrayList<CreateAccountPenaltyDto>();

            radio.add(loanAmount.divide(loan.getLoanAmount()));

            for (CreateAccountFeeDto createAccountFeeDto : loanAccountInfo.getAccountFees()) {
                Integer feeId = createAccountFeeDto.getFeeId();
                String amount = createAccountFeeDto.getAmount();
                FeeBO feeBO = this.feeDao.findById(feeId.shortValue());

                if (feeBO instanceof AmountFeeBO) {
                    amount = String.valueOf(Double.valueOf(createAccountFeeDto.getAmount())
                            * (loanAmount.divide(loanAccountInfo.getLoanAmount()).getAmount().doubleValue()));
                }

                defaultAccountFees.add(new CreateAccountFeeDto(feeId, amount));
            }

            for (CreateAccountPenaltyDto createAccountPenaltyDto : loanAccountInfo.getAccountPenalties()) {
                Integer penaltyId = createAccountPenaltyDto.getPenaltyId();
                String amount = createAccountPenaltyDto.getAmount();
                PenaltyBO penaltyBO = this.penaltyDao.findPenaltyById(penaltyId.shortValue());

                if (penaltyBO instanceof AmountPenaltyBO) {
                    amount = String.valueOf(Double.valueOf(createAccountPenaltyDto.getAmount())
                            * (loanAmount.divide(loanAccountInfo.getLoanAmount()).getAmount().doubleValue()));
                }

                defaultAccountPenalties.add(new CreateAccountPenaltyDto(penaltyId, amount));
            }

            List<AccountFeesEntity> feeEntities = assembleAccountFees(defaultAccountFees);
            List<AccountPenaltiesEntity> penaltyEntities = assembleAccountPenalties(defaultAccountPenalties);
            LoanProductOverridenDetail memberOverridenDetail = new LoanProductOverridenDetail(loanAmount,
                    feeEntities, overridenDetail, penaltyEntities);

            LoanSchedule memberSchedule = assembleLoanSchedule(member, loanAccountDetail.getLoanProduct(),
                    memberOverridenDetail, configuration, repaymentDayMeeting, userOffice,
                    new ArrayList<DateTime>(), loanAccountInfo.getDisbursementDate(), new ArrayList<Number>());

            GroupMemberLoanDetail groupMemberLoanDetail = new GroupMemberLoanDetail(member,
                    memberOverridenDetail, memberSchedule, groupMemberAccount.getLoanPurposeId());
            individualMembersOfGroupLoan.add(groupMemberLoanDetail);
        }

        checkScheduleForMembers(loanSchedule, loan, individualMembersOfGroupLoan, radio);

        for (GroupMemberLoanDetail groupMemberAccount : individualMembersOfGroupLoan) {

            LoanBO memberLoan = LoanBO.openGroupMemberLoanAccount(loan, loanAccountDetail.getLoanProduct(),
                    groupMemberAccount.getMember(), repaymentDayMeeting, groupMemberAccount.getMemberSchedule(),
                    groupMemberAccount.getMemberOverridenDetail(), configuration, installmentRange, amountRange,
                    creationDetail, createdBy);
            if (groupMemberAccount.getLoanPurposeId() > 0) {
                memberLoan.setBusinessActivityId(groupMemberAccount.getLoanPurposeId());
            }
            if (!backdatedLoanPayments.isEmpty()) {
                memberLoan.markAsCreatedWithBackdatedPayments();
            }
            this.loanDao.save(memberLoan);
            transactionHelper.flushSession();
            try {
                memberLoan.setGlobalAccountNum(memberLoan.generateId(userOffice.getGlobalOfficeNum()));
            } catch (AccountException e) {
                throw new BusinessRuleException(e.getMessage());
            }
            this.loanDao.save(memberLoan);
            transactionHelper.flushSession();
        }

        // save question groups
        if (!questionGroups.isEmpty()) {
            Integer eventSourceId = questionnaireServiceFacade.getEventSourceId("Create", "Loan");
            QuestionGroupDetails questionGroupDetails = new QuestionGroupDetails(
                    Integer.valueOf(user.getUserId()).shortValue(), loan.getAccountId(), eventSourceId,
                    questionGroups);
            questionnaireServiceFacade.saveResponses(questionGroupDetails);
            transactionHelper.flushSession();
        }

        if (loanAccountCashFlow != null && !loanAccountCashFlow.getMonthlyCashFlow().isEmpty()) {

            List<MonthlyCashFlowDetail> monthlyCashFlowDetails = new ArrayList<MonthlyCashFlowDetail>();
            for (MonthlyCashFlowDto monthlyCashFlow : loanAccountCashFlow.getMonthlyCashFlow()) {
                MonthlyCashFlowDetail monthlyCashFlowDetail = new MonthlyCashFlowDetail(
                        monthlyCashFlow.getMonthDate(), monthlyCashFlow.getRevenue(),
                        monthlyCashFlow.getExpenses(), monthlyCashFlow.getNotes());

                monthlyCashFlowDetails.add(monthlyCashFlowDetail);
            }

            org.mifos.platform.cashflow.service.CashFlowDetail cashFlowDetail = new org.mifos.platform.cashflow.service.CashFlowDetail(
                    monthlyCashFlowDetails);
            cashFlowDetail.setTotalCapital(loanAccountCashFlow.getTotalCapital());
            cashFlowDetail.setTotalLiability(loanAccountCashFlow.getTotalLiability());
            cashFlowService.save(cashFlowDetail);
            transactionHelper.flushSession();
        }

        if (isBackdatedLoan) {
            // 3. auto approve loan
            String comment = "Automatic Status Update (Redo Loan)";
            LocalDate approvalDate = loanAccountInfo.getDisbursementDate();
            loan.approve(createdBy, comment, approvalDate);

            // 4. disburse loan
            String receiptNumber = null;
            Date receiptDate = null;
            PaymentTypeEntity paymentType = new PaymentTypeEntity(PaymentTypes.CASH.getValue());
            if (loanAccountInfo.getDisbursalPaymentTypeId() != null) {
                paymentType = new PaymentTypeEntity(loanAccountInfo.getDisbursalPaymentTypeId());
            }
            Date paymentDate = loanAccountInfo.getDisbursementDate().toDateMidnight().toDate();
            AccountPaymentEntity disbursalPayment = new AccountPaymentEntity(loan, loan.getLoanAmount(),
                    receiptNumber, receiptDate, paymentType, paymentDate);
            disbursalPayment.setCreatedByUser(createdBy);

            // refactoring of loan disbursal
            if (customer
                    .isDisbursalPreventedDueToAnyExistingActiveLoansForTheSameProduct(loan.getLoanOffering())) {
                throw new AccountException("errors.cannotDisburseLoan.because.otherLoansAreActive");
            }

            try {
                loan.updateCustomer(customer);
                new ProductMixValidator().checkIfProductsOfferingCanCoexist(loan);
            } catch (ServiceException e1) {
                throw new AccountException(e1.getMessage());
            }

            loan.disburse(createdBy, disbursalPayment);

            customer.updatePerformanceHistoryOnDisbursement(loan, loan.getLoanAmount());
            // end of refactoring of loan disbural

            this.loanDao.save(loan);
            transactionHelper.flushSession();

            // 5. apply each payment
            for (LoanPaymentDto loanPayment : backdatedLoanPayments) {
                Money amountPaidToDate = new Money(loan.getCurrency(), loanPayment.getAmount());
                PaymentData paymentData = new PaymentData(amountPaidToDate, createdBy,
                        loanPayment.getPaymentTypeId(), loanPayment.getPaymentDate().toDateMidnight().toDate());
                loan.applyPayment(paymentData);
                this.loanDao.save(loan);
            }
        }
        transactionHelper.commitTransaction();

        return new LoanCreationResultDto(false, loan.getAccountId(), loan.getGlobalAccountNum());
    } catch (BusinessRuleException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getMessageKey(), e);
    } catch (Exception e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } finally {
        this.transactionHelper.closeSession();
    }
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

@Override
public short configureEndPointSync(long timeout, SimpleDescriptor desc)
        throws IOException, Exception, GatewayException {
    ByteArrayObject _res = new ByteArrayObject();
    _res.addByte(desc.getEndPoint().byteValue());/* End Point */
    _res.addBytesShort(Short.reverseBytes(desc.getApplicationProfileIdentifier().shortValue()), 2);
    _res.addBytesShort(Short.reverseBytes(desc.getApplicationDeviceIdentifier().shortValue()), 2);
    _res.addByte(desc.getApplicationDeviceVersion().byteValue());/* DeviceVersion */
    _res.addByte((byte) desc.getApplicationInputCluster().size());/* ClusterInputSize */
    if (desc.getApplicationInputCluster().size() > 0) {
        for (Integer x : desc.getApplicationInputCluster())
            _res.addBytesShort(Short.reverseBytes(x.shortValue()), 2);
    }/*from  ww  w.  ja  v  a2 s.  co m*/
    _res.addByte((byte) desc.getApplicationOutputCluster().size());/* ClusterOutputSize */
    if (desc.getApplicationOutputCluster().size() > 0) {
        for (Integer x : desc.getApplicationOutputCluster())
            _res.addBytesShort(Short.reverseBytes(x.shortValue()), 2);
    }
    _res.addByte((byte) 0x01);/* Maximum Window Size */

    _res = Set_SequenceStart_And_FSC(_res, FreescaleConstants.APSRegisterEndPointRequest);/*
                                                                                          * StartSequence
                                                                                          * +
                                                                                          * Control
                                                                                          */
    /* APS-RegisterEndPoint.Request */
    if (gal.getPropertiesManager().getDebugEnabled()) {
        logger.info("Configure EndPoint command:" + _res.ToHexString());
    }
    short _endPoint = 0;

    ParserLocker lock = new ParserLocker();
    lock.setType(TypeMessage.CONFIGURE_END_POINT);
    Status status = null;
    try {
        synchronized (listLocker) {
            listLocker.add(lock);
        }
        addToSendDataQueue(_res);
        synchronized (lock) {
            try {
                lock.wait(timeout);
            } catch (InterruptedException e) {

            }
        }
        status = lock.getStatus();
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    } catch (Exception e) {
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    }
    if (status.getCode() == ParserLocker.INVALID_ID) {

        if (gal.getPropertiesManager().getDebugEnabled()) {
            logger.error("Timeout expired in Configure End Point");
        }
        throw new GatewayException("Timeout expired in Configure End Point");
    } else {
        if (status.getCode() != 0) {
            if (gal.getPropertiesManager().getDebugEnabled()) {
                logger.info("Returned Status: " + status.getCode());
            }
            throw new GatewayException("Error on  APS-RegisterEndPoint.Request. Status code:" + status.getCode()
                    + " Status Message: " + status.getMessage());
        } else
            _endPoint = desc.getEndPoint();
    }
    return _endPoint;
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

@Override
public Status addBinding(long timeout, Binding binding) throws IOException, Exception, GatewayException {
    byte[] _reversed;

    ByteArrayObject _res = new ByteArrayObject();
    _res.addBytesShort(Short.reverseBytes(
            gal.getShortAddress_FromNetworkCache(binding.getSourceIEEEAddress()).shortValue()), 2);

    byte[] ieeeAddress = DataManipulation.toByteVect(binding.getSourceIEEEAddress(), 8);
    _reversed = DataManipulation.reverseBytes(ieeeAddress);
    for (byte b : _reversed)
        /* Source IEEEAddress */
        _res.addByte(b);/*from  w w  w.  j  a v a 2  s.c  o m*/

    _res.addByte((byte) binding.getSourceEndpoint());/* Source EndPoint */

    Integer _clusterID = binding.getClusterID();
    _res.addBytesShort(Short.reverseBytes(_clusterID.shortValue()), 2);/* ClusterID */

    if (binding.getDeviceDestination().size() > 0 && binding.getGroupDestination().size() > 0)
        throw new GatewayException("The Address mode can only be one between Group or Device!");
    else if (binding.getDeviceDestination().size() == 1) {
        _res.addByte((byte) 0x03);/*
                                  * Destination AddressMode IeeeAddress +
                                  * EndPoint
                                  */

        byte[] _DestinationieeeAddress = DataManipulation
                .toByteVect(binding.getDeviceDestination().get(0).getAddress(), 8);
        _reversed = DataManipulation.reverseBytes(_DestinationieeeAddress);
        for (byte b : _reversed)
            /* Destination IEEEAddress */
            _res.addByte(b);
        _res.addByte((byte) binding.getDeviceDestination().get(0).getEndpoint());/*
                                                                                 * Destination
                                                                                 * EndPoint
                                                                                 */

    } else if (binding.getGroupDestination().size() == 1) {
        _res.addByte((byte) 0x01);/* Destination AddressMode Group */

        byte[] _DestinationGroupAddress = DataManipulation
                .toByteVect(binding.getGroupDestination().get(0).longValue(), 8);
        _reversed = DataManipulation.reverseBytes(_DestinationGroupAddress);
        for (byte b : _reversed)
            /* Destination Group */
            _res.addByte(b);

    } else {
        throw new GatewayException("The Address mode can only be one Group or one Device!");

    }

    _res = Set_SequenceStart_And_FSC(_res, FreescaleConstants.ZDPBindRequest);/*
                                                                              * StartSequence
                                                                              * +
                                                                              * Control
                                                                              */
    ParserLocker lock = new ParserLocker();
    lock.setType(TypeMessage.ADD_BINDING);
    Status status = null;
    try {
        synchronized (listLocker) {
            listLocker.add(lock);
        }
        addToSendDataQueue(_res);
        synchronized (lock) {
            try {
                lock.wait(timeout);
            } catch (InterruptedException e) {

            }
        }
        status = lock.getStatus();
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    } catch (Exception e) {
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }

    }
    if (status.getCode() == ParserLocker.INVALID_ID) {

        if (gal.getPropertiesManager().getDebugEnabled()) {
            logger.error("Timeout expired in ZDP-BIND.Response");
        }
        throw new GatewayException("Timeout expired in ZDP-BIND.Request");
    } else {
        if (status.getCode() != 0) {
            if (gal.getPropertiesManager().getDebugEnabled()) {
                logger.info("Returned Status: " + status.getCode());
            }
            throw new GatewayException("Error on ZDP-BIND.Request. Status code:" + status.getCode()
                    + " Status Message: " + status.getMessage());
        } else {
            return lock.getStatus();

        }
    }
}

From source file:org.energy_home.jemma.javagal.layers.data.implementations.IDataLayerImplementation.DataFreescale.java

@Override
public Status removeBinding(long timeout, Binding binding) throws IOException, Exception, GatewayException {
    byte[] _reversed;

    ByteArrayObject _res = new ByteArrayObject();

    _res.addBytesShort(Short.reverseBytes(
            gal.getShortAddress_FromNetworkCache(binding.getSourceIEEEAddress()).shortValue()), 2);

    byte[] ieeeAddress = DataManipulation.toByteVect(binding.getSourceIEEEAddress(), 8);
    _reversed = DataManipulation.reverseBytes(ieeeAddress);
    for (byte b : _reversed)
        /* Source IEEEAddress */
        _res.addByte(b);//  w  w w  . ja  v a 2s .c o  m

    _res.addByte((byte) binding.getSourceEndpoint());/* Source EndPoint */

    Integer _clusterID = binding.getClusterID();
    _res.addBytesShort(Short.reverseBytes(_clusterID.shortValue()), 2);/* ClusterID */

    if (binding.getDeviceDestination().size() > 0 && binding.getGroupDestination().size() > 0)
        throw new GatewayException("The Address mode can only be one between Group or Device!");
    else if (binding.getDeviceDestination().size() == 1) {
        _res.addByte((byte) 0x03);/*
                                  * Destination AddressMode IeeeAddress +
                                  * EndPoint
                                  */

        byte[] _DestinationieeeAddress = DataManipulation
                .toByteVect(binding.getDeviceDestination().get(0).getAddress(), 8);
        _reversed = DataManipulation.reverseBytes(_DestinationieeeAddress);
        for (byte b : _reversed)
            /* Destination IEEEAddress */
            _res.addByte(b);
        _res.addByte((byte) binding.getDeviceDestination().get(0).getEndpoint());/*
                                                                                 * Destination
                                                                                 * EndPoint
                                                                                 */

    } else if (binding.getGroupDestination().size() == 1) {
        _res.addByte((byte) 0x01);/* Destination AddressMode Group */

        byte[] _DestinationGroupAddress = DataManipulation
                .toByteVect(binding.getGroupDestination().get(0).longValue(), 8);
        _reversed = DataManipulation.reverseBytes(_DestinationGroupAddress);
        for (byte b : _reversed)
            /* Destination Group */
            _res.addByte(b);

    } else {
        throw new GatewayException("The Address mode can only be one Group or one Device!");

    }

    _res = Set_SequenceStart_And_FSC(_res, FreescaleConstants.ZDPUnbindRequest);/*
                                                                                * StartSequence
                                                                                * +
                                                                                * Control
                                                                                */
    ParserLocker lock = new ParserLocker();
    lock.setType(TypeMessage.REMOVE_BINDING);
    Status status = null;
    try {
        synchronized (listLocker) {
            listLocker.add(lock);
        }
        addToSendDataQueue(_res);
        synchronized (lock) {
            try {
                lock.wait(timeout);
            } catch (InterruptedException e) {

            }
        }
        status = lock.getStatus();
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    } catch (Exception e) {
        synchronized (listLocker) {
            if (listLocker.contains(lock))
                listLocker.remove(lock);
        }
    }
    if (status.getCode() == ParserLocker.INVALID_ID) {

        if (gal.getPropertiesManager().getDebugEnabled()) {
            logger.error("Timeout expired in ZDP-UNBIND.Response");
        }
        throw new GatewayException("Timeout expired in ZDP-UNBIND.Request");
    } else {
        if (status.getCode() != 0) {
            if (gal.getPropertiesManager().getDebugEnabled()) {
                logger.info("Returned Status: " + status.getCode());
            }
            throw new GatewayException("Error on ZDP-UNBIND.Request. Status code:" + status.getCode()
                    + " Status Message: " + status.getMessage());
        } else {
            return lock.getStatus();

        }
    }
}

From source file:org.apache.hadoop.hive.metastore.MetaStoreDirectSql.java

/**
 * Get partition objects for the query using direct SQL queries, to avoid bazillion
 * queries created by DN retrieving stuff for each object individually.
 * @param dbName Metastore db name./*from   w w w .j a  v  a  2 s .  co m*/
 * @param tblName Metastore table name.
 * @param isView Whether table is a view. Can be passed as null if not immediately
 *               known, then this method will get it only if necessary.
 * @param sqlFilter SQL filter to use. Better be SQL92-compliant.
 * @param paramsForFilter params for ?-s in SQL filter text. Params must be in order.
 * @param joinsForFilter if the filter needs additional join statement, they must be in
 *                       this list. Better be SQL92-compliant.
 * @param max The maximum number of partitions to return.
 * @return List of partition objects.
 */
private List<Partition> getPartitionsViaSqlFilterInternal(String dbName, String tblName, final Boolean isView,
        String sqlFilter, List<? extends Object> paramsForFilter, List<String> joinsForFilter, Integer max)
        throws MetaException {
    boolean doTrace = LOG.isDebugEnabled();
    final String dbNameLcase = dbName.toLowerCase(), tblNameLcase = tblName.toLowerCase();
    // We have to be mindful of order during filtering if we are not returning all partitions.
    String orderForFilter = (max != null) ? " order by \"PART_NAME\" asc" : "";

    // Get all simple fields for partitions and related objects, which we can map one-on-one.
    // We will do this in 2 queries to use different existing indices for each one.
    // We do not get table and DB name, assuming they are the same as we are using to filter.
    // TODO: We might want to tune the indexes instead. With current ones MySQL performs
    // poorly, esp. with 'order by' w/o index on large tables, even if the number of actual
    // results is small (query that returns 8 out of 32k partitions can go 4sec. to 0sec. by
    // just adding a \"PART_ID\" IN (...) filter that doesn't alter the results to it, probably
    // causing it to not sort the entire table due to not knowing how selective the filter is.
    String queryText = "select " + PARTITIONS + ".\"PART_ID\" from " + PARTITIONS + "" + "  inner join " + TBLS
            + " on " + PARTITIONS + ".\"TBL_ID\" = " + TBLS + ".\"TBL_ID\" " + "    and " + TBLS
            + ".\"TBL_NAME\" = ? " + "  inner join " + DBS + " on " + TBLS + ".\"DB_ID\" = " + DBS
            + ".\"DB_ID\" " + "     and " + DBS + ".\"NAME\" = ? " + join(joinsForFilter, ' ')
            + (StringUtils.isBlank(sqlFilter) ? "" : (" where " + sqlFilter)) + orderForFilter;
    Object[] params = new Object[paramsForFilter.size() + 2];
    params[0] = tblNameLcase;
    params[1] = dbNameLcase;
    for (int i = 0; i < paramsForFilter.size(); ++i) {
        params[i + 2] = paramsForFilter.get(i);
    }

    long start = doTrace ? System.nanoTime() : 0;
    Query query = pm.newQuery("javax.jdo.query.SQL", queryText);
    if (max != null) {
        query.setRange(0, max.shortValue());
    }
    List<Object> sqlResult = executeWithArray(query, params, queryText);
    long queryTime = doTrace ? System.nanoTime() : 0;
    timingTrace(doTrace, queryText, start, queryTime);
    if (sqlResult.isEmpty()) {
        return Collections.emptyList(); // no partitions, bail early.
    }

    // Get full objects. For Oracle/etc. do it in batches.
    List<Partition> result = runBatched(sqlResult, new Batchable<Object, Partition>() {
        public List<Partition> run(List<Object> input) throws MetaException {
            return getPartitionsFromPartitionIds(dbNameLcase, tblNameLcase, isView, input);
        }
    });

    query.closeAll();
    return result;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.TemplateEditor.java

/**
 * XXX FIX me currently updates everything, not just the changed ones.
 * @return updates all the templates for changes and returns the new template items.
 */// ww  w  .jav a 2  s  .co  m
public Collection<WorkbenchTemplateMappingItem> updateAndGetNewItems() {
    Vector<WorkbenchTemplateMappingItem> newItems = new Vector<WorkbenchTemplateMappingItem>();
    for (int i = 0; i < mapModel.size(); i++) {
        FieldMappingPanel fmp = mapModel.getElementAt(i);
        if (fmp.getFieldInfo() != null) {
            WorkbenchTemplateMappingItem item;
            FieldInfo fieldInfo = fmp.getFieldInfo();
            Integer origColNum = -1;
            if (fmp.getWbtmi() == null) {
                ImportColumnInfo colInfo = fmp.getColInfo();
                item = new WorkbenchTemplateMappingItem();
                item.initialize();

                //trim to fit. User will have been warned of truncation during import.
                String caption = colInfo.getCaption();
                int maxCapLen = DBTableIdMgr.getInstance().getInfoByTableName("workbenchtemplatemappingitem")
                        .getFieldByColumnName("Caption").getLength();
                int maxImportedColNameLen = DBTableIdMgr.getInstance()
                        .getInfoByTableName("workbenchtemplatemappingitem")
                        .getFieldByColumnName("ImportedColName").getLength();
                item.setCaption(caption.length() > maxCapLen ? caption.substring(0, maxCapLen) : caption);
                item.setImportedColName(
                        caption.length() > maxImportedColNameLen ? caption.substring(0, maxImportedColNameLen)
                                : caption);
                origColNum = fmp.isAdded() ? -1 : colInfo.getColInx();

                item.setXCoord(Integer.valueOf(colInfo.getFormXCoord()).shortValue());
                item.setYCoord(Integer.valueOf(colInfo.getFormYCoord()).shortValue());
                item.setFieldType(Integer.valueOf(colInfo.getFrmFieldType()).shortValue());
                item.setMetaData(colInfo.getFrmMetaData());

                newItems.add(item);

            } else {
                item = fmp.getWbtmi();
                //item.setCaption(fieldInfo.getTitle()); // removed lines for Bug 4833
                //item.setImportedColName(null);
            }

            item.setFieldName(fieldInfo.getFieldInfo().getName());
            item.setSrcTableId(fieldInfo.getTableinfo().getTableId());
            item.setTableName(fieldInfo.getTableinfo().getName());
            short len = (short) fieldInfo.getFieldInfo().getLength();
            item.setDataFieldLength(len == -1 ? 32767 : len);

            item.setViewOrder(fmp.getViewOrder());
            item.setOrigImportColumnIndex(origColNum.shortValue());

        }
    }

    return newItems;
}

From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java

/**
 * @param stats list of cell stats for row
 * @param wbRow /*from   w ww.  j  a  va 2 s . c om*/
 * @return list of updated data items
 */
protected Hashtable<Short, Short> updateCellStatuses(List<CellStatusInfo> stats, final WorkbenchRow wbRow) {
    Hashtable<Short, Short> exceptionalItems = new Hashtable<Short, Short>();
    if (stats != null && stats.size() > 0) {
        for (CellStatusInfo issue : stats) {
            for (Integer col : issue.getColumns()) {
                if (col >= 0) {
                    WorkbenchDataItem wbItem = wbRow.getItems().get(col.shortValue());
                    if (wbItem == null) {
                        //need to force creation of empty wbItem for blank cell
                        wbItem = wbRow.setData("", col.shortValue(), false, true);
                    }
                    if (wbItem != null) {
                        exceptionalItems.put(col.shortValue(), issue.getStatus());
                        //WorkbenchDataItems can be updated by GridCellEditor or by background validation initiated at load time or after find/replace ops         
                        synchronized (wbItem) {
                            wbItem.setStatusText(issue.getStatusText());
                            if (wbItem.getEditorValidationStatus() != issue.getStatus()) {
                                wbItem.setEditorValidationStatus(issue.getStatus());
                                if (issue.getStatus() == WorkbenchDataItem.VAL_ERROR
                                        || issue.getStatus() == WorkbenchDataItem.VAL_ERROR_EDIT) {
                                    invalidCellCount.getAndIncrement();
                                } else if (issue.getStatus() == WorkbenchDataItem.VAL_MULTIPLE_MATCH
                                        || issue.getStatus() == WorkbenchDataItem.VAL_NEW_DATA) {
                                    unmatchedCellCount.getAndIncrement();
                                }

                                //System.out.println("error " + invalidCellCount.get());
                            }
                        }
                    } else {
                        log.error("couldn't find workbench item for col " + col);
                    }
                } else {
                    log.error(issue.getStatusText() + " at " + col + "???");
                }
            }
        }
    }
    return exceptionalItems;
}