Example usage for java.lang Short equals

List of usage examples for java.lang Short equals

Introduction

In this page you can find the example usage for java.lang Short equals.

Prototype

public boolean equals(Object obj) 

Source Link

Document

Compares this object to the specified object.

Usage

From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java

@Override
public void applyCharge(Integer accountId, Short chargeId, Double chargeAmount, boolean isPenaltyType) {

    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);

    try {/*from   ww  w  .  java2 s  .c o m*/
        AccountBO account = new AccountBusinessService().getAccount(accountId);

        if (account instanceof LoanBO && !account.isGroupLoanAccount()) {
            List<LoanBO> individualLoans = this.loanDao.findIndividualLoans(account.getAccountId());

            if (individualLoans != null && individualLoans.size() > 0) {
                for (LoanBO individual : individualLoans) {
                    individual.updateDetails(userContext);

                    if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                        PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                        individual.addAccountPenalty(
                                new AccountPenaltiesEntity(individual, penalty, chargeAmount));
                    } else {
                        FeeBO fee = this.feeDao.findById(chargeId);

                        if (fee instanceof RateFeeBO) {
                            individual.applyCharge(chargeId, chargeAmount);
                        } else {
                            Double radio = individual.getLoanAmount().getAmount().doubleValue()
                                    / ((LoanBO) account).getLoanAmount().getAmount().doubleValue();

                            individual.applyCharge(chargeId, chargeAmount * radio);
                        }
                    }
                }
            }
        }

        account.updateDetails(userContext);

        CustomerLevel customerLevel = null;
        if (account.isCustomerAccount()) {
            customerLevel = account.getCustomer().getLevel();
        }
        if (account.getPersonnel() != null) {
            checkPermissionForApplyCharges(account.getType(), customerLevel, userContext,
                    account.getOffice().getOfficeId(), account.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(account.getType(), customerLevel, userContext,
                    account.getOffice().getOfficeId(), userContext.getId());
        }

        this.transactionHelper.startTransaction();

        if (isPenaltyType && account instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) account).addAccountPenalty(new AccountPenaltiesEntity(account, penalty, chargeAmount));
        } else {
            account.applyCharge(chargeId, chargeAmount);
        }

        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }
}

From source file:org.mifos.application.collectionsheet.struts.uihelpers.BulkEntryDisplayHelper.java

private void getTotalForRow(final StringBuilder builder, final CollectionSheetEntryDto collectionSheetEntryDto,
        final Money[] totals, final int rows, final String method, final UserContext userContext,
        final int loanProductsSize, final int savingsProductSize) {
    Short customerLevel = collectionSheetEntryDto.getCustomerDetail().getCustomerLevelId();
    ResourceBundle resources = ResourceBundle.getBundle(FilePaths.BULKENTRY_RESOURCE,
            userContext.getPreferredLocale());
    String totalStr = resources.getString(CollectionSheetEntryConstants.TOTAL_GROUP_CENTER);
    String group = getLabel(ConfigurationConstants.GROUP, userContext);
    String center = getLabel(ConfigurationConstants.CENTER, userContext);
    String groupTotalStr = totalStr.format(totalStr, group);
    groupTotalStr = " " + groupTotalStr + " ";
    String centerTotalStr = totalStr.format(totalStr, center);
    centerTotalStr = " " + centerTotalStr + " ";
    if (!method.equals(CollectionSheetEntryConstants.PREVIEWMETHOD)) {
        if (customerLevel.equals(CustomerLevel.GROUP.getValue())) {
            BulkEntryTagUIHelper.getInstance().generateStartTR(builder);
            builder.append("<td align=\"right\" class=\"drawtablerowSmall\">"
                    + "<span class=\"fontnormal8pt\"><em>" + groupTotalStr + "</em></span></td>");
            builder.append("<td height=\"30\" class=\"drawtablerow\">&nbsp;&nbsp;</td>");
            for (int i = 0; i < loanProductsSize + savingsProductSize; i++) {
                Money groupTotalMoney = totals[i] == null
                        ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                        : totals[i];/*  w  w  w . jav a  2  s .c o m*/
                builder.append("<td class=\"drawtablerow\">");
                builder.append("<input name=\"group[" + rows + "][" + i
                        + "]\" type=\"text\" style=\"width:40px\"" + " value=\""
                        + ConversionUtil.formatNumber(groupTotalMoney.toString()) + "\" size=\"6\" disabled>");
                builder.append("</td>");
            }
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            for (int i = loanProductsSize + savingsProductSize; i < 2
                    * (loanProductsSize + savingsProductSize); i++) {
                Money groupTotalMoney = totals[i] == null
                        ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                        : totals[i];
                builder.append("<td class=\"drawtablerow\">");
                builder.append("<input name=\"group[" + rows + "][" + i
                        + "]\" type=\"text\" style=\"width:40px\"" + " value=\""
                        + ConversionUtil.formatNumber(groupTotalMoney.toString()) + "\" size=\"6\" disabled>");
                builder.append("</td>");
            }
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            Money groupTotalMoney = totals[(2 * (loanProductsSize + savingsProductSize))] == null
                    ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                    : totals[(2 * (loanProductsSize + savingsProductSize))];
            builder.append("<td class=\"drawtablerow\">");
            builder.append("<input name=\"group[" + rows + "][" + 2 * (loanProductsSize + savingsProductSize)
                    + "]\" type=\"text\" style=\"width:40px\"" + " value=\""
                    + ConversionUtil.formatNumber(groupTotalMoney.toString()) + "\" size=\"6\" disabled>");
            builder.append("</td>");
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        } else if (customerLevel.equals(CustomerLevel.CENTER.getValue())) {
            BulkEntryTagUIHelper.getInstance().generateStartTR(builder);
            builder.append("<td align=\"right\" class=\"drawtablerowSmall\">"
                    + "<span class=\"fontnormal8pt\"><em>" + centerTotalStr + "</em></span></td>");
            builder.append("<td height=\"30\" class=\"drawtablerow\">&nbsp;&nbsp;</td>");

            for (int i = 0; i < loanProductsSize + savingsProductSize; i++) {
                Money centerTotalMoney = totals[i] == null
                        ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                        : totals[i];
                builder.append("<td class=\"drawtablerow\">");
                builder.append("<input name=\"center[" + i + "]\" type=\"text\" style=\"width:40px\""
                        + " value=\"" + ConversionUtil.formatNumber(centerTotalMoney.toString())
                        + "\" size=\"6\" disabled>");
                builder.append("</td>");
            }
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            for (int i = loanProductsSize + savingsProductSize; i < 2
                    * (loanProductsSize + savingsProductSize); i++) {
                Money centerTotalMoney = totals[i] == null
                        ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                        : totals[i];
                builder.append("<td class=\"drawtablerow\">");
                builder.append("<input name=\"center[" + i + "]\" type=\"text\" style=\"width:40px\""
                        + " value=\"" + ConversionUtil.formatNumber(centerTotalMoney.toString())
                        + "\" size=\"6\" disabled>");
                builder.append("</td>");
            }
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            Money centerTotalMoney = totals[(2 * (loanProductsSize + savingsProductSize))] == null
                    ? new Money(collectionSheetEntryDto.getCurrency(), "0.0")
                    : totals[(2 * (loanProductsSize + savingsProductSize))];
            builder.append("<td class=\"drawtablerow\">");
            builder.append("<input name=\"center[" + 2 * (loanProductsSize + savingsProductSize)
                    + "]\" type=\"text\" style=\"width:40px\"" + " value=\""
                    + ConversionUtil.formatNumber(centerTotalMoney.toString()) + "\" size=\"6\" disabled>");
            builder.append("</td>");
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
            BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        }
    } else {
        BulkEntryTagUIHelper.getInstance().generateStartTR(builder);
        builder.append(
                "<td align=\"right\" class=\"drawtablerowSmall\">" + "<span class=\"fontnormal8pt\"><em>");
        if (customerLevel.equals(CustomerLevel.GROUP.getValue())) {
            builder.append(groupTotalStr);
        } else if (customerLevel.equals(CustomerLevel.CENTER.getValue())) {
            builder.append(centerTotalStr);
        }
        builder.append("</em></span></td>");
        builder.append("<td height=\"30\" class=\"drawtablerow\">&nbsp;&nbsp;</td>");

        for (int i = 0; i < loanProductsSize + savingsProductSize; i++) {
            Money totalMoney = totals[i] == null ? new Money(collectionSheetEntryDto.getCurrency(), "0")
                    : totals[i];
            builder.append("<td class=\"drawtablerow\">");
            builder.append(ConversionUtil.formatNumber(totalMoney.toString()));
            builder.append("</td>");
        }
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        for (int i = loanProductsSize + savingsProductSize; i < 2
                * (loanProductsSize + savingsProductSize); i++) {
            Money totalMoney = totals[i] == null ? new Money(collectionSheetEntryDto.getCurrency(), "0")
                    : totals[i];
            builder.append("<td class=\"drawtablerow\">");
            builder.append(ConversionUtil.formatNumber(totalMoney.toString()));
            builder.append("</td>");
        }
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        Money totalMoney = totals[(2 * (loanProductsSize + savingsProductSize))] == null
                ? new Money(collectionSheetEntryDto.getCurrency(), "0")
                : totals[(2 * (loanProductsSize + savingsProductSize))];
        builder.append("<td class=\"drawtablerow\">");
        builder.append(ConversionUtil.formatNumber(totalMoney.toString()));
        builder.append("</td>");
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
        BulkEntryTagUIHelper.getInstance().generateTD(builder, 19, "&nbsp;", true);
    }
    BulkEntryTagUIHelper.getInstance().generateEmptyTD(builder, true);
    BulkEntryTagUIHelper.getInstance().generateEndTR(builder);
}

From source file:org.mifos.accounts.business.AccountBO.java

/**
 *
 * @param installmentDates/*w ww .  j av a 2 s  .c  o m*/
 *            dates adjusted for holidays
 * @param nonAdjustedInstallmentDates
 *            dates not adjusted for holidays
 */
protected final List<FeeInstallment> getFeeInstallments(final List<InstallmentDate> installmentDates,
        final List<InstallmentDate> nonAdjustedInstallmentDates) throws AccountException {
    List<FeeInstallment> feeInstallmentList = new ArrayList<FeeInstallment>();
    for (AccountFeesEntity accountFeesEntity : getAccountFees()) {
        if (accountFeesEntity.isActive()) {
            Short accountFeeType = accountFeesEntity.getFees().getFeeFrequency().getFeeFrequencyType().getId();
            if (accountFeeType.equals(FeeFrequencyType.ONETIME.getValue())) {
                feeInstallmentList.add(handleOneTime(accountFeesEntity, installmentDates));
            } else if (accountFeeType.equals(FeeFrequencyType.PERIODIC.getValue())) {
                feeInstallmentList.addAll(
                        handlePeriodic(accountFeesEntity, installmentDates, nonAdjustedInstallmentDates));
            }
        }
    }
    return feeInstallmentList;
}

From source file:org.mifos.accounts.business.AccountBO.java

private void setFinancialEntries(final FinancialTransactionBO financialTrxn,
        final TransactionHistoryDto transactionHistory) {
    String debit = "-";
    String credit = "-";
    String notes = "-";
    if (financialTrxn.isDebitEntry()) {
        debit = String.valueOf(removeSign(financialTrxn.getPostedAmount()));
    } else if (financialTrxn.isCreditEntry()) {
        credit = String.valueOf(removeSign(financialTrxn.getPostedAmount()));
    }/* w  w  w  .  j  a v  a 2 s .  co  m*/
    Short entityId = financialTrxn.getAccountTrxn().getAccountActionEntity().getId();
    if (financialTrxn.getNotes() != null && !financialTrxn.getNotes().equals("")
            && !entityId.equals(AccountActionTypes.CUSTOMER_ACCOUNT_REPAYMENT.getValue())
            && !entityId.equals(AccountActionTypes.LOAN_REPAYMENT.getValue())) {
        notes = financialTrxn.getNotes();
    }

    transactionHistory.setFinancialEnteries(financialTrxn.getTrxnId(), financialTrxn.getActionDate(),
            financialTrxn.getFinancialAction().getName(), financialTrxn.getGlcode().getGlcode(), debit, credit,
            financialTrxn.getPostedDate(), notes);

}

From source file:org.mifos.accounts.servicefacade.WebTierAccountServiceFacade.java

@Override
public void applyGroupCharge(Map<Integer, String> idsAndValues, Short chargeId, boolean isPenaltyType) {
    MifosUser user = (MifosUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserContext userContext = toUserContext(user);
    TreeMap<Integer, String> idsAndValueAsTreeMap = new TreeMap<Integer, String>(idsAndValues);

    try {//from w  ww . j a v  a  2  s .  c o  m
        AccountBO parentAccount = ((LoanBO) legacyAccountDao.getAccount(
                new AccountBusinessService().getAccount(idsAndValueAsTreeMap.firstKey()).getAccountId()))
                        .getParentAccount();
        BigDecimal parentAmount = ((LoanBO) parentAccount).getLoanAmount().getAmount();
        BigDecimal membersAmount = BigDecimal.ZERO;

        for (Map.Entry<Integer, String> entry : idsAndValues.entrySet()) {
            LoanBO individual = loanDao.findById(entry.getKey());
            Double chargeAmount = Double.valueOf(entry.getValue());
            if (chargeAmount.equals(0.0)) {
                continue;
            }
            membersAmount = membersAmount.add(individual.getLoanAmount().getAmount());
            individual.updateDetails(userContext);

            if (isPenaltyType && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                individual.addAccountPenalty(new AccountPenaltiesEntity(individual, penalty, chargeAmount));
            } else {
                individual.applyCharge(chargeId, chargeAmount);
            }
        }

        boolean isRateCharge = false;

        if (!chargeId.equals(Short.valueOf(AccountConstants.MISC_FEES))
                && !chargeId.equals(Short.valueOf(AccountConstants.MISC_PENALTY))) {

            if (isPenaltyType) {
                PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
                if (penalty instanceof RatePenaltyBO) {
                    isRateCharge = true;
                }
            } else {
                FeeBO fee = feeDao.findById(chargeId);
                if (fee.getFeeType().equals(RateAmountFlag.RATE)) {
                    isRateCharge = true;
                }
            }
        }

        Double chargeAmount = null;

        if (!isRateCharge) {
            chargeAmount = sumCharge(idsAndValues);
        } else {
            chargeAmount = Double.valueOf(idsAndValueAsTreeMap.firstEntry().getValue());
            BigDecimal chargeAmountBig = new BigDecimal(chargeAmount);
            membersAmount = membersAmount.multiply(chargeAmountBig);
            int scale = Money.getInternalPrecision();
            chargeAmountBig = membersAmount.divide(parentAmount, scale, RoundingMode.HALF_EVEN);
            chargeAmount = chargeAmountBig.doubleValue();
        }

        parentAccount.updateDetails(userContext);

        CustomerLevel customerLevel = null;
        if (parentAccount.isCustomerAccount()) {
            customerLevel = parentAccount.getCustomer().getLevel();
        }
        if (parentAccount.getPersonnel() != null) {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), parentAccount.getPersonnel().getPersonnelId());
        } else {
            checkPermissionForApplyCharges(parentAccount.getType(), customerLevel, userContext,
                    parentAccount.getOffice().getOfficeId(), userContext.getId());
        }

        this.transactionHelper.startTransaction();

        if (isPenaltyType && parentAccount instanceof LoanBO) {
            PenaltyBO penalty = this.penaltyDao.findPenaltyById(chargeId.intValue());
            ((LoanBO) parentAccount)
                    .addAccountPenalty(new AccountPenaltiesEntity(parentAccount, penalty, chargeAmount));
        } else {
            parentAccount.applyCharge(chargeId, chargeAmount);
        }

        this.transactionHelper.commitTransaction();
    } catch (ServiceException e) {
        this.transactionHelper.rollbackTransaction();
        throw new MifosRuntimeException(e);
    } catch (ApplicationException e) {
        this.transactionHelper.rollbackTransaction();
        throw new BusinessRuleException(e.getKey(), e);
    }

}

From source file:org.opendaylight.controller.routing.dijkstrav2_implementation.internal.DijkstraImplementation.java

private static boolean updateTopo(Edge edge, Short bw, UpdateType type,
        ConcurrentMap<Short, Graph<Node, Edge>> topologyBWAware,
        ConcurrentHashMap<Short, DijkstraShortestPath<Node, Edge>> sptBWAware) {
    Short baseBW = Short.valueOf((short) 0);
    Graph<Node, Edge> topo = topologyBWAware.get(baseBW);
    DijkstraShortestPath<Node, Edge> spt = sptBWAware.get(baseBW);
    boolean edgePresentInGraph = false;

    if (topo == null) {
        // Create topology for this BW
        Graph<Node, Edge> g = new SparseMultigraph();
        topologyBWAware.put(bw, g);//  w  w w  .ja v  a  2  s . c o  m
        topo = topologyBWAware.get(bw);
        sptBWAware.put(bw, new DijkstraShortestPath(g));
        spt = sptBWAware.get(bw);
    }
    if (topo != null) {
        NodeConnector src = edge.getTailNodeConnector();
        NodeConnector dst = edge.getHeadNodeConnector();
        if (spt == null) {
            spt = new DijkstraShortestPath(topo);
            sptBWAware.put(bw, spt);
        }

        switch (type) {
        case ADDED:
            // Make sure the vertex are there before adding the edge
            topo.addVertex(src.getNode());
            topo.addVertex(dst.getNode());
            // Add the link between
            edgePresentInGraph = topo.containsEdge(edge);
            if (edgePresentInGraph == false) {
                try {
                    topo.addEdge(new Edge(src, dst), src.getNode(), dst.getNode(), EdgeType.DIRECTED);
                } catch (final ConstructionException e) {
                    log.error("", e);
                    return edgePresentInGraph;
                }
            }
        case CHANGED:
            // Mainly raised only on properties update, so not really useful
            // in this case
            break;
        case REMOVED:
            // Remove the edge
            try {
                topo.removeEdge(new Edge(src, dst));
            } catch (final ConstructionException e) {
                log.error("", e);
                return edgePresentInGraph;
            }

            // If the src and dst vertex don't have incoming or
            // outgoing links we can get ride of them
            if (topo.containsVertex(src.getNode()) && (topo.inDegree(src.getNode()) == 0)
                    && (topo.outDegree(src.getNode()) == 0)) {
                log.debug("Removing vertex {}", src);
                topo.removeVertex(src.getNode());
            }

            if (topo.containsVertex(dst.getNode()) && (topo.inDegree(dst.getNode()) == 0)
                    && (topo.outDegree(dst.getNode()) == 0)) {
                log.debug("Removing vertex {}", dst);
                topo.removeVertex(dst.getNode());
            }
            break;
        }
        spt.reset();
        if (bw.equals(baseBW)) {
            //TODO: for now this doesn't work
            //                clearMaxThroughput();
        }
    } else {
        log.error("Cannot find topology for BW {} this is unexpected!", bw);
    }
    return edgePresentInGraph;
}

From source file:org.opendaylight.controller.routing.dijkstrav2_implementation.internal.DijkstraImplementation.java

@SuppressWarnings({ "unchecked" })
private synchronized boolean updateTopo(Edge edge, Short bw, UpdateType type) {
    Graph<Node, Edge> topo = this.topologyBWAware.get(bw);
    DijkstraShortestPath<Node, Edge> spt = this.sptBWAware.get(bw);
    boolean edgePresentInGraph = false;
    Short baseBW = Short.valueOf((short) 0);

    if (topo == null) {
        // Create topology for this BW
        Graph<Node, Edge> g = new SparseMultigraph();
        this.topologyBWAware.put(bw, g);
        topo = this.topologyBWAware.get(bw);
        this.sptBWAware.put(bw, new DijkstraShortestPath(g));
        spt = this.sptBWAware.get(bw);
    }/*from   w ww  .j  a v a2  s  .c  om*/

    if (topo != null) {
        NodeConnector src = edge.getTailNodeConnector();
        NodeConnector dst = edge.getHeadNodeConnector();
        if (spt == null) {
            spt = new DijkstraShortestPath(topo);
            this.sptBWAware.put(bw, spt);
        }

        switch (type) {
        case ADDED:
            // Make sure the vertex are there before adding the edge
            topo.addVertex(src.getNode());
            topo.addVertex(dst.getNode());
            // Add the link between
            edgePresentInGraph = topo.containsEdge(edge);
            if (edgePresentInGraph == false) {
                try {
                    topo.addEdge(new Edge(src, dst), src.getNode(), dst.getNode(), EdgeType.DIRECTED);
                } catch (final ConstructionException e) {
                    log.error("", e);
                    return edgePresentInGraph;
                }
            }
        case CHANGED:
            // Mainly raised only on properties update, so not really useful
            // in this case
            break;
        case REMOVED:
            // Remove the edge
            try {
                topo.removeEdge(new Edge(src, dst));
            } catch (final ConstructionException e) {
                log.error("", e);
                return edgePresentInGraph;
            }

            // If the src and dst vertex don't have incoming or
            // outgoing links we can get ride of them
            if (topo.containsVertex(src.getNode()) && (topo.inDegree(src.getNode()) == 0)
                    && (topo.outDegree(src.getNode()) == 0)) {
                log.debug("Removing vertex {}", src);
                topo.removeVertex(src.getNode());
            }

            if (topo.containsVertex(dst.getNode()) && (topo.inDegree(dst.getNode()) == 0)
                    && (topo.outDegree(dst.getNode()) == 0)) {
                log.debug("Removing vertex {}", dst);
                topo.removeVertex(dst.getNode());
            }
            break;
        }
        spt.reset();
        if (bw.equals(baseBW)) {
            clearMaxThroughput();
        }
    } else {
        log.error("Cannot find topology for BW {} this is unexpected!", bw);
    }
    return edgePresentInGraph;
}

From source file:org.mifos.accounts.business.AccountBO.java

public final void changeStatus(final Short newStatusId, final Short flagId, final String comment,
        final PersonnelBO loggedInUser, final Date argumentDate) throws AccountException {
    Date transactionDate = argumentDate;
    if (transactionDate == null) {
        transactionDate = getDateTimeService().getCurrentJavaDateTime();
    }/*from w  w w . j  a v  a2s . co m*/
    Short oldStatusId = this.getState().getValue();
    if (getUserContext() == null) {
        throw new IllegalStateException("userContext is not set for account.");
    }

    try {
        logger.debug("In the change status method of AccountBO:: new StatusId= " + newStatusId);

        activationDateHelper(newStatusId);
        LegacyMasterDao legacyMasterDao = getlegacyMasterDao();
        AccountStateEntity accountStateEntity = legacyMasterDao.getPersistentObject(AccountStateEntity.class,
                newStatusId);
        AccountStateFlagEntity accountStateFlagEntity = null;
        if (flagId != null) {
            accountStateFlagEntity = legacyMasterDao.getPersistentObject(AccountStateFlagEntity.class, flagId);
        }

        AccountStatusChangeHistoryEntity historyEntity = new AccountStatusChangeHistoryEntity(
                this.getAccountState(), accountStateEntity, loggedInUser, this);
        AccountNotesEntity accountNotesEntity = new AccountNotesEntity(transactionDate, comment, loggedInUser,
                this);
        this.addAccountStatusChangeHistory(historyEntity);
        this.setAccountState(accountStateEntity);
        this.addAccountNotes(accountNotesEntity);
        if (accountStateFlagEntity != null) {
            setFlag(accountStateFlagEntity);
        }
        if (newStatusId.equals(AccountState.LOAN_CANCELLED.getValue())
                || newStatusId.equals(AccountState.LOAN_CLOSED_OBLIGATIONS_MET.getValue())
                || newStatusId.equals(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue())
                || newStatusId.equals(AccountState.SAVINGS_CANCELLED.getValue())
                || newStatusId.equals(AccountState.CUSTOMER_ACCOUNT_INACTIVE.getValue())) {
            this.setClosedDate(transactionDate);
        }
        if (newStatusId.equals(AccountState.LOAN_CLOSED_WRITTEN_OFF.getValue())) {
            writeOff(transactionDate);
        }

        if (newStatusId.equals(AccountState.LOAN_CLOSED_RESCHEDULED.getValue())) {
            reschedule(transactionDate);
        }

        if (newStatusId.equals(AccountState.SAVINGS_INACTIVE.getValue())) {
            ((SavingsBO) this).removeRecommendedAmountOnFutureInstallments();
        }

        if (oldStatusId.equals(AccountState.SAVINGS_INACTIVE.getValue())
                && newStatusId.equals(AccountState.SAVINGS_ACTIVE.getValue())) {
            ((SavingsBO) this).resetRecommendedAmountOnFutureInstallments();
        }

        logger.debug("Coming out successfully from the change status method of AccountBO");
    } catch (PersistenceException e) {
        throw new AccountException(e);
    }
}

From source file:org.sdntest.app.SDNTest.java

private void installRule(PacketContext context, PortNumber portNumber, DeviceId device, Boolean mapVlan,
        Short vlanIn, Short vlanOut, int timeout) {
    log.info("install rule: device: {}, port: {}, map: {}, vIn: {}, vout: {}", device, portNumber, mapVlan,
            vlanIn, vlanOut);//w  w  w  . j a va 2s .  c o  m

    Ethernet inPkt = context.inPacket().parsed();
    TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();

    if (false) {
        selectorBuilder.matchEthDst(inPkt.getDestinationMAC());
    } else {
        selectorBuilder.matchEthSrc(inPkt.getSourceMAC()).matchEthDst(inPkt.getDestinationMAC());

        // Match Vlan ID
        selectorBuilder.matchVlanId(VlanId.vlanId(vlanIn));

        //
        // If configured and EtherType is IPv4 - Match IPv4 and
        // TCP/UDP/ICMP fields
        //
        // not currently used
        if (matchIpv4Address && inPkt.getEtherType() == Ethernet.TYPE_IPV4) {
            IPv4 ipv4Packet = (IPv4) inPkt.getPayload();
            byte ipv4Protocol = ipv4Packet.getProtocol();
            Ip4Prefix matchIp4SrcPrefix = Ip4Prefix.valueOf(ipv4Packet.getSourceAddress(),
                    Ip4Prefix.MAX_MASK_LENGTH);
            Ip4Prefix matchIp4DstPrefix = Ip4Prefix.valueOf(ipv4Packet.getDestinationAddress(),
                    Ip4Prefix.MAX_MASK_LENGTH);
            selectorBuilder.matchEthType(Ethernet.TYPE_IPV4).matchIPSrc(matchIp4SrcPrefix)
                    .matchIPDst(matchIp4DstPrefix);

            if (matchIpv4Dscp) {
                byte dscp = ipv4Packet.getDscp();
                byte ecn = ipv4Packet.getEcn();
                selectorBuilder.matchIPDscp(dscp).matchIPEcn(ecn);
            }

            if (matchTcpUdpPorts && ipv4Protocol == IPv4.PROTOCOL_TCP) {
                TCP tcpPacket = (TCP) ipv4Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv4Protocol).matchTcpSrc((short) tcpPacket.getSourcePort())
                        .matchTcpDst((short) tcpPacket.getDestinationPort());
            }
            if (matchTcpUdpPorts && ipv4Protocol == IPv4.PROTOCOL_UDP) {
                UDP udpPacket = (UDP) ipv4Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv4Protocol).matchUdpSrc((short) udpPacket.getSourcePort())
                        .matchUdpDst((short) udpPacket.getDestinationPort());
            }
            if (matchIcmpFields && ipv4Protocol == IPv4.PROTOCOL_ICMP) {
                ICMP icmpPacket = (ICMP) ipv4Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv4Protocol).matchIcmpType(icmpPacket.getIcmpType())
                        .matchIcmpCode(icmpPacket.getIcmpCode());
            }
        }

        //
        // If configured and EtherType is IPv6 - Match IPv6 and
        // TCP/UDP/ICMP fields
        //
        // not currently used
        if (matchIpv6Address && inPkt.getEtherType() == Ethernet.TYPE_IPV6) {
            IPv6 ipv6Packet = (IPv6) inPkt.getPayload();
            byte ipv6NextHeader = ipv6Packet.getNextHeader();
            Ip6Prefix matchIp6SrcPrefix = Ip6Prefix.valueOf(ipv6Packet.getSourceAddress(),
                    Ip6Prefix.MAX_MASK_LENGTH);
            Ip6Prefix matchIp6DstPrefix = Ip6Prefix.valueOf(ipv6Packet.getDestinationAddress(),
                    Ip6Prefix.MAX_MASK_LENGTH);
            selectorBuilder.matchEthType(Ethernet.TYPE_IPV6).matchIPv6Src(matchIp6SrcPrefix)
                    .matchIPv6Dst(matchIp6DstPrefix);

            if (matchIpv6FlowLabel) {
                selectorBuilder.matchIPv6FlowLabel(ipv6Packet.getFlowLabel());
            }

            if (matchTcpUdpPorts && ipv6NextHeader == IPv6.PROTOCOL_TCP) {
                TCP tcpPacket = (TCP) ipv6Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv6NextHeader).matchTcpSrc((short) tcpPacket.getSourcePort())
                        .matchTcpDst((short) tcpPacket.getDestinationPort());
            }
            if (matchTcpUdpPorts && ipv6NextHeader == IPv6.PROTOCOL_UDP) {
                UDP udpPacket = (UDP) ipv6Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv6NextHeader).matchUdpSrc((short) udpPacket.getSourcePort())
                        .matchUdpDst((short) udpPacket.getDestinationPort());
            }
            if (matchIcmpFields && ipv6NextHeader == IPv6.PROTOCOL_ICMP6) {
                ICMP6 icmp6Packet = (ICMP6) ipv6Packet.getPayload();
                selectorBuilder.matchIPProtocol(ipv6NextHeader).matchIcmpv6Type(icmp6Packet.getIcmpType())
                        .matchIcmpv6Code(icmp6Packet.getIcmpCode());
            }
        }
    }

    // remap vlan if needed
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    if (mapVlan && !vlanIn.equals(vlanOut)) {
        treatment = treatment.setVlanId(VlanId.vlanId(vlanOut));
    }
    // set output port on device
    treatment = treatment.setOutput(portNumber);

    ForwardingObjective forwardingObjective = DefaultForwardingObjective.builder()
            .withSelector(selectorBuilder.build()).withTreatment(treatment.build()).withPriority(flowPriority)
            .withFlag(ForwardingObjective.Flag.VERSATILE).fromApp(appId).makeTemporary(timeout).add();

    flowObjectiveService.forward(device, forwardingObjective);
}

From source file:com.jd.survey.web.survey.PrivateSurveyController.java

/**
 * Updates a survey page /*from   w w w  . j av a  2 s .c o m*/
 * @param surveyPage
 * @param backAction
 * @param proceedAction
 * @param bindingResult
 * @param uiModel
 * @param principal
 * @param httpServletRequest
 * @return
 */
@Secured({ "ROLE_ADMIN", "ROLE_SURVEY_ADMIN", "ROLE_SURVEY_PARTICIPANT" })
@RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String updateSurveyPage(@Valid SurveyPage surveyPage,
        @RequestParam(value = "_back", required = false) String backAction,
        @RequestParam(value = "_proceed", required = false) String proceedAction, BindingResult bindingResult,
        Model uiModel, Principal principal, HttpServletRequest httpServletRequest) {
    try {
        String login = principal.getName();
        Short order = surveyPage.getOrder();
        if (proceedAction != null) { //next button
            Survey survey = surveyService.survey_findById(surveyPage.getSurvey().getId());
            //Check if the user is authorized
            if (!survey.getLogin().equals(login)) {
                log.warn(UNAUTHORIZED_ATTEMPT_TO_ACCESS_SURVEY_WARNING_MESSAGE + survey.getId()
                        + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                        + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                        + httpServletRequest.getLocalAddr());
                return "accessDenied";

            }

            //Check that the survey was not submitted
            if (!(survey.getStatus().equals(SurveyStatus.I) || survey.getStatus().equals(SurveyStatus.R))) {
                log.warn(UNAUTHORIZED_ATTEMPT_TO_EDIT_SUBMITTED_SURVEY_WARNING_MESSAGE + survey.getId()
                        + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                        + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                        + httpServletRequest.getLocalAddr());
                return "accessDenied";

            }

            List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyPage.getSurvey().getId(),
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
            surveyPage.setSurvey(survey);
            surveyPage = surveyService.surveyPage_updateSettings(surveyPage);

            //populate the uploaded files
            MultipartHttpServletRequest multiPartRequest = (MultipartHttpServletRequest) httpServletRequest;
            Iterator<String> fileNames = multiPartRequest.getFileNames();
            while (fileNames.hasNext()) {
                String fileName = fileNames.next();
                Long questionId = Long.parseLong(fileName.toUpperCase().replace("FILE", ""));
                for (QuestionAnswer questionAnswer : surveyPage.getQuestionAnswers()) {
                    if (questionAnswer.getQuestion().getId().equals(questionId)
                            && multiPartRequest.getFile(fileName).getBytes().length > 0) {
                        questionAnswer.setSurveyDocument(new SurveyDocument(survey.getId(), questionId,
                                multiPartRequest.getFile(fileName).getName(),
                                multiPartRequest.getFile(fileName).getContentType(),
                                multiPartRequest.getFile(fileName).getBytes()));
                    }
                }
            }

            Policy policy = Policy.getInstance(this.getClass().getResource(POLICY_FILE_LOCATION));
            AntiSamy as = new AntiSamy();
            for (QuestionAnswer questionAnswer : surveyPage.getQuestionAnswers()) {
                if (questionAnswer.getQuestion().getType().getIsTextInput()) {
                    CleanResults cr = as.scan(questionAnswer.getStringAnswerValue(), policy);
                    questionAnswer.setStringAnswerValue(cr.getCleanHTML());
                }
            }

            GlobalSettings globalSettings = applicationSettingsService.getSettings();

            SurveyPageValidator validator = new SurveyPageValidator(
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()),
                    globalSettings.getValidContentTypes(), globalSettings.getValidImageTypes(),
                    globalSettings.getMaximunFileSize(), globalSettings.getInvalidContentMessage(),
                    globalSettings.getInvalidFileSizeMessage());
            validator.validate(surveyPage, bindingResult);
            if (bindingResult.hasErrors()) {
                /*
                for (ObjectError err :bindingResult.getAllErrors()) {
                   log.info("getObjectName:" + err.getObjectName() + " getCode:" + err.getCode() + " getDefaultMessage:" + err.getDefaultMessage());
                   log.info("toString:" + err.toString());
                } 
                */
                uiModel.addAttribute("survey_base_path", "private");
                uiModel.addAttribute("survey", survey);
                uiModel.addAttribute("surveyPage", surveyPage);
                uiModel.addAttribute("surveyDefinition",
                        surveySettingsService.surveyDefinition_findById(surveyPage.getSurvey().getTypeId()));
                uiModel.addAttribute("surveyPages", surveyPages);
                return "surveys/page";
            }

            surveyService.surveyPage_update(surveyPage,
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
            //get the survey pages from the database again, prvious call updates visibility when there is  branching logic 
            surveyPages = surveyService.surveyPage_getAll(surveyPage.getSurvey().getId(),
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
            order = getNextPageOrder(surveyPages, order);

            if (order.equals((short) 0)) {
                //Submit page
                uiModel.asMap().clear();
                return "redirect:/private/submit/"
                        + encodeUrlPathSegment(surveyPage.getSurvey().getId().toString(), httpServletRequest);
            } else {
                //go to the next page
                uiModel.asMap().clear();
                return "redirect:/private/"
                        + encodeUrlPathSegment(surveyPage.getSurvey().getId().toString(), httpServletRequest)
                        + "/" + encodeUrlPathSegment(order.toString(), httpServletRequest);
            }

        } else {//back button
            Survey survey = surveyService.survey_findById(surveyPage.getSurvey().getId());
            //Check if the user is authorized
            if (!survey.getLogin().equals(login)) {
                log.warn(UNAUTHORIZED_ATTEMPT_TO_ACCESS_SURVEY_WARNING_MESSAGE + survey.getId()
                        + REQUEST_PATH_WARNING_MESSAGE + httpServletRequest.getPathInfo()
                        + FROM_USER_LOGIN_WARNING_MESSAGE + principal.getName() + FROM_IP_WARNING_MESSAGE
                        + httpServletRequest.getLocalAddr());
                return "accessDenied";

            }
            List<SurveyPage> surveyPages = surveyService.surveyPage_getAll(surveyPage.getSurvey().getId(),
                    messageSource.getMessage(DATE_FORMAT, null, LocaleContextHolder.getLocale()));
            order = getPreviousPageOrder(surveyPages, order);
            if (order.equals((short) 0)) {
                //Go to the surveyEntries page
                uiModel.asMap().clear();
                return "redirect:/private/"
                        + encodeUrlPathSegment(survey.getTypeId().toString(), httpServletRequest) + "?list";
            } else {
                //go to previous page
                uiModel.asMap().clear();
                return "redirect:/private/"
                        + encodeUrlPathSegment(survey.getId().toString(), httpServletRequest) + "/"
                        + encodeUrlPathSegment(order.toString(), httpServletRequest);

            }
        }

    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw (new RuntimeException(e));
    }

}