Example usage for java.lang StringBuffer delete

List of usage examples for java.lang StringBuffer delete

Introduction

In this page you can find the example usage for java.lang StringBuffer delete.

Prototype

@Override
public synchronized StringBuffer delete(int start, int end) 

Source Link

Usage

From source file:org.amnesty.aidoc.search.AidocSearch.java

/**
 * Execute the search/*from   w  w w.j  a  v  a  2 s  .  c  o m*/
 *
 * @param searchTerms
 * @param startPage
 *          Search page to start results on
 * @param itemsPerPage
 *          Number of items to display per search page
 * @param language
 *          Language to restrict search results by. If null search will
 *          return all results.
 * @return
 */
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, String language,
        WebScriptRequest req) {
    SearchResult searchResult = null;
    ResultSet results = null;

    logger.debug("invoking AidocSearch");

    try {

        Map<String, List<String>> queryMap = AidocSearchQueryStringParser.parse(searchTerms);
        StringBuffer query = new StringBuffer();

        /*
         * 1. First add the general restriction parameters so we query over
         * the right dataset
         */

        query.append("TYPE:\"{" + AICORE_CONTENT_TYPE + "}Document\" AND \n");
        query.append("ASPECT:\"{" + CONTENT_TYPE + "}effectivity\" AND \n");
        query.append("ASPECT:\"{" + CONTENT_TYPE + "}mlDocument\" AND \n");

        // Exclude documents without an effective date

        // Warning! We probably have timezone problems at the moment
        // See AIDOC-138

        /* Set the date range if provided */
        String fromDate = "1900-01-01T00:00:00";
        if (queryMap.get("from") != null) {
            List<String> fromList = queryMap.get("from");
            fromDate = (String) fromList.get(0);
        }
        String toDate = ISO8601DateFormat.format(new Date());
        if (queryMap.get("to") != null) {
            List<String> toList = queryMap.get("to");
            toDate = (String) toList.get(0);
        }

        query.append(" @cm\\:from:[" + fromDate + " TO " + toDate + "] AND");

        /*
         * Process language from query. If it exists this overrides form
         * parameter
         */
        if (queryMap.containsKey("lang")) {
            List<String> langList = (List<String>) queryMap.get("lang");
            String lang = langList.get(0);
            if (lang != null && lang.length() > 0)
                language = lang;
        }
        if (language != null && language.length() > 0) {
            language = language.replace("-", "_");
        }
        logger.debug("language: " + language);

        /* Process language */
        // Locale locale = I18NUtil.getLocale();
        Locale locale = null;
        if (language != null && language.length() > 0 && !language.equals("any")) {
            locale = new Locale(language);
            query.append(" @sys\\:locale:\"" + locale.getLanguage() + "_\" AND");
        }

        /*
         * 2. Now add the user's parameters
         */

        if (AidocSearchQueryStringParser.isDocumentIdQuery(searchTerms)) {
            query = buildIndexQuery(query, searchTerms);
        } else {
            query = buildStandardQuery(query, queryMap, language);
        }

        if (query.toString().trim().endsWith("AND")) {
            query.delete(query.length() - 4, query.length());
        }

        /*
         * Create SearchParameters to go with Lucene search string
         */
        SearchParameters parameters = new SearchParameters();
        parameters.addStore(SEARCH_STORE);
        parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
        // Doesn't work yet. See AIDOC-466
        // parameters.setDefaultOperator(SearchParameters.AND);
        parameters.setQuery(query.toString());

        /* Add locale clause if locale is set */
        // if (locale != null) {
        // parameters.addLocale(locale);
        // }
        // Add sort clause if sort:date specified
        if (queryMap.containsKey("sort")) {
            List<String> sortValues = (List<String>) queryMap.get("sort");

            boolean asc = false;
            if (queryMap.containsKey("order")) {
                List<String> orderValues = (List<String>) queryMap.get("order");
                if (orderValues.get(0).equals("asc"))
                    asc = true;
            }

            if (sortValues.get(0).equals("date")) {
                logger.debug("sort by date");
                if (asc) {
                    logger.debug("order descending");
                } else
                    logger.debug("order ascending");
                parameters.addSort("@" + QName.createQName(CONTENT_TYPE, "from"), asc);
            }
        } else
            parameters.addSort("@" + QName.createQName(CONTENT_TYPE, "from"), false);

        /*
         * Execute query
         */
        if (logger.isDebugEnabled()) {
            logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage
                    + ", itemsPerPage=" + itemsPerPage);
            logger.debug("Issuing lucene search: " + query);
        }

        results = searchService.query(parameters);
        int totalResults = results.length();

        logger.debug("Results: " + totalResults + " rows (limited: "
                + results.getResultSetMetaData().getLimitedBy() + ")");

        int totalPages = (totalResults / itemsPerPage);
        totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;

        /* construct search result */
        searchResult = new SearchResult();
        searchResult.setSearchTerms(searchTerms);
        searchResult.setLocale(locale);
        searchResult.setItemsPerPage(itemsPerPage);
        searchResult.setStartPage(startPage);
        searchResult.setTotalResults(totalResults);
        if (totalResults == 0) {
            searchResult.setTotalPages(0);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
            /* handle out-of-range by displaying no results */
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(0);
            searchResult.setTotalPageItems(0);
        } else {
            searchResult.setTotalPages(totalPages);
            searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
            searchResult
                    .setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
        }
        SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
        for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
            NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
            float score = results.getScore(i + searchResult.getStartIndex() - 1);
            nodes[i] = new SearchTemplateNode(node, score);
        }
        searchResult.setResults(nodes);
        return searchResult;
    } catch (Exception e) {
        logger.error("Search failed", e);
        return null;
    } finally {
        if (results != null) {
            results.close();
        }
    }
}

From source file:lcmc.cluster.ui.ClusterBrowser.java

public void parseClusterOutput(final String output, final StringBuffer clusterStatusOutput, final Host host,
        final CountDownLatch firstTime, final Application.RunMode runMode) {
    final ClusterStatus clusterStatus0 = this.clusterStatus;
    clStatusLock();/*from   w  ww. j  a va  2  s.co m*/
    if (crmStatusCanceledByUser || clusterStatus0 == null) {
        clStatusUnlock();
        firstTime.countDown();
        return;
    }
    if (output == null || "".equals(output)) {
        clusterStatus0.setOnlineNode(host.getName(), "no");
        setCrmStatus(host, false);
        firstTime.countDown();
    } else {
        // TODO: if we get ERROR:... show it somewhere
        clusterStatusOutput.append(output);
        /* removes the string from the output. */
        int s = clusterStatusOutput.indexOf(RESET_STRING);
        while (s >= 0) {
            clusterStatusOutput.delete(s, s + RESET_STRING_LEN);
            s = clusterStatusOutput.indexOf(RESET_STRING);
        }
        if (clusterStatusOutput.length() > 12) {
            final String e = clusterStatusOutput.substring(clusterStatusOutput.length() - 12);
            if (e.trim().equals("---done---")) {
                final int i = clusterStatusOutput.lastIndexOf("---start---");
                if (i >= 0) {
                    if (clusterStatusOutput.indexOf("is stopped") >= 0) {
                        /* TODO: heartbeat's not running. */
                    } else {
                        final String status = clusterStatusOutput.substring(i);
                        clusterStatusOutput.delete(0, clusterStatusOutput.length());
                        if (CLUSTER_STATUS_ERROR.equals(status)) {
                            final boolean oldStatus = host.isCrmStatusOk();
                            clusterStatus0.setOnlineNode(host.getName(), "no");
                            setCrmStatus(host, false);
                            if (oldStatus) {
                                crmGraph.repaint();
                            }
                        } else {
                            if (clusterStatus0.parseStatus(status)) {
                                LOG.debug1("processClusterOutput: host: " + host.getName());
                                final ServicesInfo ssi = servicesInfo;
                                rscDefaultsInfo.setParameters(clusterStatus0.getRscDefaultsValuePairs());
                                ssi.setGlobalConfig(clusterStatus0);
                                resourceUpdaterProvider.get().updateAllResources(ssi, ssi.getBrowser(),
                                        clusterStatus0, runMode);
                                if (firstTime.getCount() == 1) {
                                    /* one more time so that id-refs work.*/
                                    resourceUpdaterProvider.get().updateAllResources(ssi, ssi.getBrowser(),
                                            clusterStatus0, runMode);
                                }
                                treeMenuController.repaintMenuTree();
                                clusterHostsInfo.updateTable(ClusterHostsInfo.MAIN_TABLE);
                            }
                            final String online = clusterStatus0.isOnlineNode(host.getName());
                            if ("yes".equals(online)) {
                                setCrmStatus(host, true);
                                setCrmStatus();
                            } else {
                                setCrmStatus(host, false);
                            }
                        }
                    }
                    firstTime.countDown();
                }
            }
        }
        Tools.chomp(clusterStatusOutput);
    }
    clStatusUnlock();
}

From source file:org.openbravo.advpaymentmngt.process.FIN_PaymentProcess.java

private void processPayment(FIN_Payment payment, String strAction, Boolean isPosOrder, String paymentDate,
        String comingFrom, String selectedCreditLineIds) throws OBException {
    dao = new AdvPaymentMngtDao();
    String msg = "";
    try {//from  w w w .j  a  v  a2 s .  c o  m
        final boolean isReceipt = payment.isReceipt();
        if (strAction.equals("P") || strAction.equals("D")) {
            if (payment.getBusinessPartner() != null) {
                if (FIN_Utility.isBlockedBusinessPartner(payment.getBusinessPartner().getId(), isReceipt, 4)) {
                    // If the Business Partner is blocked for Payments, the Payment will not be completed.
                    msg = OBMessageUtils.messageBD("ThebusinessPartner") + " "
                            + payment.getBusinessPartner().getIdentifier() + " "
                            + OBMessageUtils.messageBD("BusinessPartnerBlocked");
                    throw new OBException(msg);
                }
            } else {
                OBContext.setAdminMode(true);
                try {
                    for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
                        for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                            BusinessPartner bPartner = null;
                            if (psd.getInvoicePaymentSchedule() != null) {
                                bPartner = psd.getInvoicePaymentSchedule().getInvoice().getBusinessPartner();
                            } else if (psd.getOrderPaymentSchedule() != null) {
                                bPartner = psd.getOrderPaymentSchedule().getOrder().getBusinessPartner();
                            }
                            if (bPartner != null && FIN_Utility.isBlockedBusinessPartner(bPartner.getId(),
                                    payment.isReceipt(), 4)) {
                                // If the Business Partner is blocked for Payments, the Payment will not be
                                // completed.
                                msg = OBMessageUtils.messageBD("ThebusinessPartner") + " "
                                        + bPartner.getIdentifier() + " "
                                        + OBMessageUtils.messageBD("BusinessPartnerBlocked");
                                throw new OBException(msg);
                            }
                        }
                    }
                } finally {
                    OBContext.restorePreviousMode();
                }
            }
        }

        if (strAction.equals("P") || strAction.equals("D")) {
            // Guess if this is a refund payment
            boolean isRefund = false;
            OBContext.setAdminMode(false);
            try {
                List<FIN_PaymentDetail> paymentDetailList = payment.getFINPaymentDetailList();
                if (paymentDetailList.size() > 0) {
                    for (FIN_PaymentDetail det : paymentDetailList) {
                        if (det.isRefund()) {
                            isRefund = true;
                            break;
                        }
                    }
                }
            } finally {
                OBContext.restorePreviousMode();
            }
            if (!isRefund) {
                // Undo Used credit as it will be calculated again
                payment.setUsedCredit(BigDecimal.ZERO);
                OBDal.getInstance().save(payment);
            }

            boolean documentEnabled = getDocumentConfirmation(null, payment.getId());
            boolean periodNotAvailable = documentEnabled
                    && !FIN_Utility.isPeriodOpen(payment.getClient().getId(),
                            payment.getDocumentType().getDocumentCategory(), payment.getOrganization().getId(),
                            OBDateUtils.formatDate(payment.getPaymentDate()))
                    && FIN_Utility.periodControlOpened(FIN_Payment.TABLE_NAME, payment.getId(),
                            FIN_Payment.TABLE_NAME + "_ID", "LE");
            if (periodNotAvailable) {
                msg = OBMessageUtils.messageBD("PeriodNotAvailable");
                throw new OBException(msg);
            }
            Set<String> documentOrganizations = OBContext.getOBContext()
                    .getOrganizationStructureProvider(payment.getClient().getId())
                    .getNaturalTree(payment.getOrganization().getId());
            if (!documentOrganizations.contains(payment.getAccount().getOrganization().getId())) {
                msg = OBMessageUtils.messageBD("APRM_FinancialAccountNotInNaturalTree");
                throw new OBException(msg);
            }
            Set<String> invoiceDocNos = new TreeSet<String>();
            Set<String> orderDocNos = new TreeSet<String>();
            Set<String> glitems = new TreeSet<String>();
            BigDecimal paymentAmount = BigDecimal.ZERO;
            BigDecimal paymentWriteOfAmount = BigDecimal.ZERO;

            // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
            // removed when new security implementation is done
            OBContext.setAdminMode();
            boolean flushDone = false;
            try {
                String strRefundCredit = "";
                // update payment schedule amount
                List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList();

                // Show error message when payment has no lines
                if (paymentDetails.size() == 0) {
                    msg = OBMessageUtils.messageBD("APRM_PaymentNoLines");
                    log4j.debug(msg);
                    throw new OBException(msg, false);
                }
                for (FIN_PaymentDetail paymentDetail : paymentDetails) {
                    for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                            .getFINPaymentScheduleDetailList()) {
                        paymentAmount = paymentAmount.add(paymentScheduleDetail.getAmount());
                        BigDecimal writeoff = paymentScheduleDetail.getWriteoffAmount();
                        if (writeoff == null)
                            writeoff = BigDecimal.ZERO;
                        paymentWriteOfAmount = paymentWriteOfAmount.add(writeoff);
                        if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                            final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
                                    .getInvoice();
                            invoiceDocNos
                                    .add(FIN_Utility.getDesiredDocumentNo(payment.getOrganization(), invoice));
                        }
                        if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                            orderDocNos.add(
                                    paymentScheduleDetail.getOrderPaymentSchedule().getOrder().getDocumentNo());
                        }
                        if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                && paymentScheduleDetail.getPaymentDetails().getGLItem() == null) {
                            if (paymentDetail.isRefund())
                                strRefundCredit = OBMessageUtils.messageBD("APRM_RefundAmount");
                            else {
                                strRefundCredit = OBMessageUtils.messageBD("APRM_CreditAmount");
                                payment.setGeneratedCredit(paymentDetail.getAmount());
                            }
                            strRefundCredit += ": " + paymentDetail.getAmount().toString();
                        }
                    }
                    if (paymentDetail.getGLItem() != null)
                        glitems.add(paymentDetail.getGLItem().getName());
                }
                // Set description
                if (!isPosOrder) {
                    StringBuffer description = new StringBuffer();

                    if (payment.getDescription() != null && !payment.getDescription().equals(""))
                        description.append(payment.getDescription()).append("\n");
                    if (!invoiceDocNos.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("InvoiceDocumentno"));
                        description.append(": ").append(
                                invoiceDocNos.toString().substring(1, invoiceDocNos.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!orderDocNos.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("OrderDocumentno"));
                        description.append(": ").append(
                                orderDocNos.toString().substring(1, orderDocNos.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!glitems.isEmpty()) {
                        description.append(OBMessageUtils.messageBD("APRM_GLItem"));
                        description.append(": ")
                                .append(glitems.toString().substring(1, glitems.toString().length() - 1));
                        description.append("\n");
                    }
                    if (!"".equals(strRefundCredit))
                        description.append(strRefundCredit).append("\n");

                    String truncateDescription = (description.length() > 255)
                            ? description.substring(0, 251).concat("...").toString()
                            : description.toString();
                    payment.setDescription(truncateDescription);
                }

                if (paymentAmount.compareTo(payment.getAmount()) != 0) {
                    payment.setUsedCredit(paymentAmount.subtract(payment.getAmount()));
                }
                if (payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                    updateUsedCredit(payment, selectedCreditLineIds);
                }

                payment.setWriteoffAmount(paymentWriteOfAmount);
                payment.setProcessed(true);
                payment.setAPRMProcessPayment("RE");
                if (payment.getGeneratedCredit() == null) {
                    payment.setGeneratedCredit(BigDecimal.ZERO);
                }
                if (BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0
                        || BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0) {
                    BusinessPartner businessPartner = payment.getBusinessPartner();
                    if (businessPartner == null) {
                        msg = OBMessageUtils.messageBD("APRM_CreditWithoutBPartner");
                        throw new OBException(msg);
                    }
                    String currency = null;
                    if (businessPartner.getCurrency() == null) {
                        currency = payment.getCurrency().getId();
                        businessPartner.setCurrency(payment.getCurrency());
                    } else {
                        currency = businessPartner.getCurrency().getId();
                    }
                    if (!payment.getCurrency().getId().equals(currency)) {
                        msg = String.format(OBMessageUtils.messageBD("APRM_CreditCurrency"),
                                businessPartner.getCurrency().getISOCode());
                        throw new OBException(msg);
                    }
                }
                // Execution Process
                if (!isPosOrder && dao.isAutomatedExecutionPayment(payment.getAccount(),
                        payment.getPaymentMethod(), payment.isReceipt())) {
                    try {
                        payment.setStatus("RPAE");

                        if (dao.hasNotDeferredExecutionProcess(payment.getAccount(), payment.getPaymentMethod(),
                                payment.isReceipt())) {
                            PaymentExecutionProcess executionProcess = dao.getExecutionProcess(payment);
                            if (dao.isAutomaticExecutionProcess(executionProcess)) {
                                final List<FIN_Payment> payments = new ArrayList<FIN_Payment>(1);
                                payments.add(payment);
                                FIN_ExecutePayment executePayment = new FIN_ExecutePayment();
                                executePayment.init("APP", executionProcess, payments, null,
                                        payment.getOrganization());
                                executePayment.addInternalParameter("comingFrom", comingFrom);
                                OBError result = executePayment.execute();
                                if ("Error".equals(result.getType())) {
                                    msg = OBMessageUtils.messageBD(result.getMessage());
                                } else if (!"".equals(result.getMessage())) {
                                    String execProcessMsg = OBMessageUtils.messageBD(result.getMessage());
                                    if (!"".equals(msg)) {
                                        msg += "<br>";
                                    }
                                    msg += execProcessMsg;
                                }
                            }
                        }
                    } catch (final NoExecutionProcessFoundException e) {
                        msg = OBMessageUtils.messageBD("NoExecutionProcessFound");
                        throw new OBException(msg);
                    } catch (final Exception e) {
                        msg = OBMessageUtils.messageBD("IssueOnExecutionProcess");
                        throw new OBException(msg);
                    }
                } else {
                    BusinessPartner businessPartner = payment.getBusinessPartner();
                    // When credit is used (consumed) we compensate so_creditused as this amount is already
                    // included in the payment details. Credit consumed should not affect to so_creditused
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                        if (isReceipt) {
                            increaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        } else {
                            decreaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        }
                    }

                    for (FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) {

                        List<FIN_PaymentScheduleDetail> orderPaymentScheduleDetails = new ArrayList<FIN_PaymentScheduleDetail>(
                                paymentDetail.getFINPaymentScheduleDetailList());

                        // Get payment schedule detail list ordered by amount asc.
                        // First negative if they exist and then positives
                        if (orderPaymentScheduleDetails.size() > 1) {
                            Collections.sort(orderPaymentScheduleDetails,
                                    new Comparator<FIN_PaymentScheduleDetail>() {
                                        @Override
                                        public int compare(FIN_PaymentScheduleDetail o1,
                                                FIN_PaymentScheduleDetail o2) {
                                            // TODO Auto-generated method stub
                                            return o1.getAmount().compareTo(o2.getAmount());
                                        }
                                    });
                        }

                        for (FIN_PaymentScheduleDetail paymentScheduleDetail : orderPaymentScheduleDetails) {
                            BigDecimal amount = paymentScheduleDetail.getAmount()
                                    .add(paymentScheduleDetail.getWriteoffAmount());
                            // Do not restore paid amounts if the payment is awaiting execution.
                            boolean invoicePaidAmounts = (FIN_Utility
                                    .seqnumberpaymentstatus(isReceipt ? "RPR" : "PPM")) >= (FIN_Utility
                                            .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
                            paymentScheduleDetail.setInvoicePaid(false);
                            // Payment = 0 when the payment is generated by a invoice that consume credit
                            if (invoicePaidAmounts
                                    || (payment.getAmount().compareTo(new BigDecimal("0.00")) == 0)) {
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                    // BP SO_CreditUsed
                                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getBusinessPartner();

                                    // Payments update credit opposite to invoices
                                    BigDecimal paidAmount = BigDecimal.ZERO;
                                    Invoice invoiceForConversion = paymentScheduleDetail
                                            .getInvoicePaymentSchedule() != null
                                                    ? paymentScheduleDetail.getInvoicePaymentSchedule()
                                                            .getInvoice()
                                                    : null;
                                    paidAmount = BigDecimal.ZERO;
                                    String fromCurrency = payment.getCurrency().getId();
                                    if (businessPartner.getCurrency() == null) {
                                        String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk", false);
                                        msg = String.format(errorMSG, businessPartner.getId(),
                                                businessPartner.getName());
                                        throw new OBException(msg);
                                    }
                                    String toCurrency = businessPartner.getCurrency().getId();
                                    if (!fromCurrency.equals(toCurrency)) {
                                        BigDecimal exchangeRate = BigDecimal.ZERO;
                                        // check at invoice document level
                                        List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice(
                                                invoiceForConversion);
                                        if (conversionRateDocumentForInvoice.size() > 0) {
                                            exchangeRate = conversionRateDocumentForInvoice.get(0).getRate();
                                        } else {
                                            // global
                                            exchangeRate = getConversionRate(payment.getOrganization().getId(),
                                                    fromCurrency, toCurrency,
                                                    invoiceForConversion != null
                                                            ? invoiceForConversion.getInvoiceDate()
                                                            : payment.getPaymentDate());
                                        }
                                        if (exchangeRate == BigDecimal.ZERO) {
                                            msg = OBMessageUtils.messageBD("NoCurrencyConversion");
                                            throw new OBException(msg);
                                        }
                                        paidAmount = amount.multiply(exchangeRate);
                                    } else {
                                        paidAmount = amount;
                                    }
                                    if (isReceipt) {
                                        decreaseCustomerCredit(businessPartner, paidAmount);
                                    } else {
                                        increaseCustomerCredit(businessPartner, paidAmount);
                                    }
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getInvoicePaymentSchedule(),
                                            paymentScheduleDetail.getAmount(),
                                            paymentScheduleDetail.getWriteoffAmount());
                                    paymentScheduleDetail.setInvoicePaid(true);
                                }

                                if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getOrderPaymentSchedule(),
                                            paymentScheduleDetail.getAmount(),
                                            paymentScheduleDetail.getWriteoffAmount());
                                    paymentScheduleDetail.setInvoicePaid(true);
                                }
                                // when generating credit for a BP SO_CreditUsed is also updated
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                        && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                        && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
                                        && !paymentDetail.isRefund()) {
                                    // BP SO_CreditUsed
                                    if (isReceipt) {
                                        decreaseCustomerCredit(businessPartner, amount);
                                    } else {
                                        increaseCustomerCredit(businessPartner, amount);
                                    }
                                }
                            }
                        }
                    }
                    payment.setStatus(isReceipt ? "RPR" : "PPM");

                    if ((strAction.equals("D") || FIN_Utility.isAutomaticDepositWithdrawn(payment))
                            && payment.getAmount().compareTo(BigDecimal.ZERO) != 0
                            && !"TRANSACTION".equals(comingFrom)) {
                        triggerAutomaticFinancialAccountTransaction(payment);
                        flushDone = true;
                    }
                }
                if (!payment.getAccount().getCurrency().equals(payment.getCurrency())
                        && getConversionRateDocument(payment).size() == 0) {
                    insertConversionRateDocument(payment);
                    flushDone = true;
                }
            } finally {
                if (!flushDone) {
                    OBDal.getInstance().flush();
                }
                OBContext.restorePreviousMode();
            }

            // ***********************
            // Reverse Payment
            // ***********************
        } else if (strAction.equals("RV")) {
            FIN_Payment reversedPayment = (FIN_Payment) DalUtil.copy(payment, false);
            OBContext.setAdminMode();
            try {
                if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0
                        && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) != 0) {
                    throw new OBException("@APRM_CreditConsumed@");
                } else if (BigDecimal.ZERO.compareTo(payment.getGeneratedCredit()) != 0
                        && BigDecimal.ZERO.compareTo(payment.getUsedCredit()) == 0) {
                    reversedPayment.setUsedCredit(payment.getGeneratedCredit());
                    reversedPayment.setGeneratedCredit(BigDecimal.ZERO);
                } else {
                    reversedPayment.setUsedCredit(BigDecimal.ZERO);
                    reversedPayment.setGeneratedCredit(BigDecimal.ZERO);
                }
                reversedPayment.setDocumentNo(
                        "*R*" + FIN_Utility.getDocumentNo(payment.getDocumentType(), "FIN_Payment"));
                reversedPayment.setPaymentDate(FIN_Utility.getDate(paymentDate));
                reversedPayment.setDescription("");
                reversedPayment.setProcessed(false);
                reversedPayment.setPosted("N");
                reversedPayment.setProcessNow(false);
                reversedPayment.setAPRMProcessPayment("P");
                reversedPayment.setStatus("RPAP");
                // Amounts
                reversedPayment.setAmount(payment.getAmount().negate());
                reversedPayment.setWriteoffAmount(payment.getWriteoffAmount().negate());
                reversedPayment.setFinancialTransactionAmount(payment.getFinancialTransactionAmount().negate());
                OBDal.getInstance().save(reversedPayment);

                List<FIN_PaymentDetail> reversedDetails = new ArrayList<FIN_PaymentDetail>();

                OBDal.getInstance().save(reversedPayment);
                List<FIN_Payment_Credit> credits = payment.getFINPaymentCreditList();

                for (FIN_PaymentDetail pd : payment.getFINPaymentDetailList()) {
                    FIN_PaymentDetail reversedPaymentDetail = (FIN_PaymentDetail) DalUtil.copy(pd, false);
                    reversedPaymentDetail.setFinPayment(reversedPayment);
                    reversedPaymentDetail.setAmount(pd.getAmount().negate());
                    reversedPaymentDetail.setWriteoffAmount(pd.getWriteoffAmount().negate());
                    if (pd.isRefund()) {
                        reversedPaymentDetail.setPrepayment(true);
                        reversedPaymentDetail.setRefund(false);
                        reversedPayment
                                .setGeneratedCredit(reversedPayment.getGeneratedCredit().add(pd.getAmount()));
                        credits = new ArrayList<FIN_Payment_Credit>();
                        OBDal.getInstance().save(reversedPayment);
                    } else if (pd.isPrepayment()
                            && pd.getFINPaymentScheduleDetailList().get(0).getOrderPaymentSchedule() == null) {
                        reversedPaymentDetail.setPrepayment(true);
                        reversedPaymentDetail.setRefund(true);
                    }
                    List<FIN_PaymentScheduleDetail> reversedSchedDetails = new ArrayList<FIN_PaymentScheduleDetail>();
                    OBDal.getInstance().save(reversedPaymentDetail);
                    // Create or update PSD of orders and invoices to set the new outstanding amount
                    for (FIN_PaymentScheduleDetail psd : pd.getFINPaymentScheduleDetailList()) {
                        if (psd.getInvoicePaymentSchedule() != null || psd.getOrderPaymentSchedule() != null) {
                            OBCriteria<FIN_PaymentScheduleDetail> unpaidSchedDet = OBDal.getInstance()
                                    .createCriteria(FIN_PaymentScheduleDetail.class);
                            if (psd.getInvoicePaymentSchedule() != null)
                                unpaidSchedDet.add(Restrictions.eq(
                                        FIN_PaymentScheduleDetail.PROPERTY_INVOICEPAYMENTSCHEDULE,
                                        psd.getInvoicePaymentSchedule()));
                            if (psd.getOrderPaymentSchedule() != null)
                                unpaidSchedDet.add(
                                        Restrictions.eq(FIN_PaymentScheduleDetail.PROPERTY_ORDERPAYMENTSCHEDULE,
                                                psd.getOrderPaymentSchedule()));
                            unpaidSchedDet.add(
                                    Restrictions.isNull(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS));
                            List<FIN_PaymentScheduleDetail> openPSDs = unpaidSchedDet.list();
                            // If invoice/order not fully paid, update outstanding amount
                            if (openPSDs.size() > 0) {
                                FIN_PaymentScheduleDetail openPSD = openPSDs.get(0);
                                BigDecimal openAmount = openPSD.getAmount()
                                        .add(psd.getAmount().add(psd.getWriteoffAmount()));
                                if (openAmount.compareTo(BigDecimal.ZERO) == 0) {
                                    OBDal.getInstance().remove(openPSD);
                                } else {
                                    openPSD.setAmount(openAmount);
                                }
                            } else {
                                // If invoice is fully paid create a new schedule detail.
                                FIN_PaymentScheduleDetail openPSD = (FIN_PaymentScheduleDetail) DalUtil
                                        .copy(psd, false);
                                openPSD.setPaymentDetails(null);
                                // Amounts
                                openPSD.setWriteoffAmount(BigDecimal.ZERO);
                                openPSD.setAmount(psd.getAmount().add(psd.getWriteoffAmount()));

                                openPSD.setCanceled(false);
                                OBDal.getInstance().save(openPSD);
                            }
                        }

                        FIN_PaymentScheduleDetail reversedPaymentSchedDetail = (FIN_PaymentScheduleDetail) DalUtil
                                .copy(psd, false);
                        reversedPaymentSchedDetail.setPaymentDetails(reversedPaymentDetail);
                        // Amounts
                        reversedPaymentSchedDetail.setWriteoffAmount(psd.getWriteoffAmount().negate());
                        reversedPaymentSchedDetail.setAmount(psd.getAmount().negate());
                        OBDal.getInstance().save(reversedPaymentSchedDetail);
                        reversedSchedDetails.add(reversedPaymentSchedDetail);

                        if ((FIN_Utility.invoicePaymentStatus(reversedPayment)
                                .equals(reversedPayment.getStatus()))) {
                            reversedPaymentSchedDetail.setInvoicePaid(true);

                        } else {
                            reversedPaymentSchedDetail.setInvoicePaid(false);
                        }
                        OBDal.getInstance().save(reversedPaymentSchedDetail);

                    }

                    reversedPaymentDetail.setFINPaymentScheduleDetailList(reversedSchedDetails);
                    OBDal.getInstance().save(reversedPaymentDetail);
                    reversedDetails.add(reversedPaymentDetail);
                }
                reversedPayment.setFINPaymentDetailList(reversedDetails);
                OBDal.getInstance().save(reversedPayment);

                List<FIN_Payment_Credit> reversedCredits = new ArrayList<FIN_Payment_Credit>();
                for (FIN_Payment_Credit pc : credits) {
                    FIN_Payment_Credit reversedPaymentCredit = (FIN_Payment_Credit) DalUtil.copy(pc, false);
                    reversedPaymentCredit.setAmount(pc.getAmount().negate());
                    reversedPaymentCredit.setCreditPaymentUsed(pc.getCreditPaymentUsed());
                    pc.getCreditPaymentUsed().setUsedCredit(
                            pc.getCreditPaymentUsed().getUsedCredit().add(pc.getAmount().negate()));
                    reversedPaymentCredit.setPayment(reversedPayment);
                    OBDal.getInstance().save(pc.getCreditPaymentUsed());
                    OBDal.getInstance().save(reversedPaymentCredit);
                    reversedCredits.add(reversedPaymentCredit);
                }

                reversedPayment.setFINPaymentCreditList(reversedCredits);
                OBDal.getInstance().save(reversedPayment);

                List<ConversionRateDoc> conversions = new ArrayList<ConversionRateDoc>();
                for (ConversionRateDoc cr : payment.getCurrencyConversionRateDocList()) {
                    ConversionRateDoc reversedCR = (ConversionRateDoc) DalUtil.copy(cr, false);
                    reversedCR.setForeignAmount(cr.getForeignAmount().negate());
                    reversedCR.setPayment(reversedPayment);
                    OBDal.getInstance().save(reversedCR);
                    conversions.add(reversedCR);
                }
                reversedPayment.setCurrencyConversionRateDocList(conversions);
                OBDal.getInstance().save(reversedPayment);

                OBDal.getInstance().flush();
            } finally {
                OBContext.restorePreviousMode();
            }

            payment.setReversedPayment(reversedPayment);
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();

            String newStrAction = "P";
            FIN_PaymentProcess fpp = WeldUtils.getInstanceFromStaticBeanManager(FIN_PaymentProcess.class);
            fpp.processPayment(reversedPayment, newStrAction, isPosOrder, paymentDate, comingFrom,
                    selectedCreditLineIds);

            return;

            // ***********************
            // Reactivate Payment
            // ***********************
        } else if (strAction.equals("R") || strAction.equals("RE")) {
            // Already Posted Document
            if ("Y".equals(payment.getPosted())) {
                msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo());
                throw new OBException(msg);
            }
            // Reversed Payment
            if (payment.getReversedPayment() != null) {
                msg = OBMessageUtils.messageBD("APRM_PaymentReversed");
                throw new OBException(msg);
            }
            // Reverse Payment
            if (strAction.equals("RE") && FIN_Utility.isReversePayment(payment)) {
                msg = OBMessageUtils.messageBD("APRM_ReversePayment");
                throw new OBException(msg);
            }

            // Do not reactive the payment if it is tax payment
            if (payment.getFinancialMgmtTaxPaymentList().size() != 0) {
                msg = OBMessageUtils.messageBD("APRM_TaxPaymentReactivation");
                throw new OBException(msg);
            }

            // Transaction exists
            if (hasTransaction(payment)) {
                msg = OBMessageUtils.messageBD("APRM_TransactionExists");
                throw new OBException(msg);
            }
            // Payment with generated credit already used on other payments.
            if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1
                    && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed");
                throw new OBException(msg);
            }

            if (FIN_Utility.invoicePaymentStatus(payment) == null) {
                msg = String.format(OBMessageUtils.messageBD("APRM_NoPaymentMethod"),
                        payment.getPaymentMethod().getIdentifier(), payment.getDocumentNo(),
                        payment.getAccount().getName());
                throw new OBException(msg);
            }
            // Do not restore paid amounts if the payment is awaiting execution.
            boolean restorePaidAmounts = (FIN_Utility
                    .seqnumberpaymentstatus(payment.getStatus())) == (FIN_Utility
                            .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
            // Initialize amounts
            payment.setProcessed(false);
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();
            payment.setWriteoffAmount(BigDecimal.ZERO);

            payment.setDescription("");

            // if all line are deleted then update amount to zero
            if (strAction.equals("R")) {
                payment.setAmount(BigDecimal.ZERO);
            }

            payment.setStatus("RPAP");
            payment.setAPRMProcessPayment("P");
            OBDal.getInstance().save(payment);
            OBDal.getInstance().flush();

            final List<FIN_PaymentDetail> removedPD = new ArrayList<FIN_PaymentDetail>();
            List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
            final List<String> removedPDIds = new ArrayList<String>();
            // FIXME: added to access the FIN_PaymentSchedule and FIN_PaymentScheduleDetail tables to be
            // removed when new security implementation is done
            OBContext.setAdminMode();
            try {
                BusinessPartner businessPartner = payment.getBusinessPartner();
                BigDecimal paidAmount = BigDecimal.ZERO;
                if (!(businessPartner == null)) {
                    // When credit is used (consumed) we compensate so_creditused as this amount is already
                    // included in the payment details. Credit consumed should not affect to so_creditused
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                        if (isReceipt) {
                            decreaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        } else {
                            increaseCustomerCredit(businessPartner, payment.getUsedCredit());
                        }
                    }
                }
                List<FIN_PaymentDetail> paymentDetails = payment.getFINPaymentDetailList();
                List<ConversionRateDoc> conversionRates = payment.getCurrencyConversionRateDocList();
                Set<String> invoiceDocNos = new HashSet<String>();
                // Undo Reversed payment relationship
                List<FIN_Payment> revPayments = new ArrayList<FIN_Payment>();
                for (FIN_Payment reversedPayment : payment.getFINPaymentReversedPaymentList()) {
                    reversedPayment.setReversedPayment(null);
                    OBDal.getInstance().save(reversedPayment);
                }
                payment.setFINPaymentReversedPaymentList(revPayments);
                OBDal.getInstance().save(payment);
                for (FIN_PaymentDetail paymentDetail : paymentDetails) {
                    removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
                    for (FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                            .getFINPaymentScheduleDetailList()) {
                        Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
                        if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                            BigDecimal psdWriteoffAmount = paymentScheduleDetail.getWriteoffAmount();
                            BigDecimal psdAmount = paymentScheduleDetail.getAmount();
                            BigDecimal amount = psdAmount.add(psdWriteoffAmount);
                            if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                // Remove invoice description related to the credit payments
                                final Invoice invoice = paymentScheduleDetail.getInvoicePaymentSchedule()
                                        .getInvoice();
                                invoiceDocNos.add(invoice.getDocumentNo());
                                final String invDesc = invoice.getDescription();
                                if (invDesc != null) {
                                    final String creditMsg = OBMessageUtils
                                            .messageBD("APRM_InvoiceDescUsedCredit");
                                    if (creditMsg != null) {
                                        StringBuffer newDesc = new StringBuffer();
                                        for (final String line : invDesc.split("\n")) {
                                            if (!line.startsWith(
                                                    creditMsg.substring(0, creditMsg.lastIndexOf("%s")))) {
                                                newDesc.append(line);
                                                if (!"".equals(line))
                                                    newDesc.append("\n");
                                            }
                                        }
                                        if (newDesc.length() > 255) {
                                            newDesc = newDesc.delete(251, newDesc.length());
                                            newDesc = newDesc.append("...\n");
                                        }
                                        invoice.setDescription(newDesc.toString());

                                    }
                                }
                                if (restorePaidAmounts) {
                                    FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                            paymentScheduleDetail.getInvoicePaymentSchedule(),
                                            psdAmount.negate(), psdWriteoffAmount.negate());
                                    paymentScheduleDetail.setInvoicePaid(false);
                                    OBDal.getInstance().save(paymentScheduleDetail);
                                    // BP SO_CreditUsed
                                    businessPartner = paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getBusinessPartner();
                                    Invoice invoiceForConversion = paymentScheduleDetail
                                            .getInvoicePaymentSchedule() != null
                                                    ? paymentScheduleDetail.getInvoicePaymentSchedule()
                                                            .getInvoice()
                                                    : null;
                                    paidAmount = BigDecimal.ZERO;
                                    if (!(businessPartner == null)) {
                                        final Currency fromCurrency = payment.getCurrency();
                                        if (businessPartner.getCurrency() == null) {
                                            String errorMSG = OBMessageUtils.messageBD("InitBPCurrencyLnk",
                                                    false);
                                            msg = String.format(errorMSG, businessPartner.getId(),
                                                    businessPartner.getName());
                                            throw new OBException(msg);
                                        }
                                        final Currency toCurrency = businessPartner.getCurrency();
                                        if (fromCurrency != null && toCurrency != null
                                                && !fromCurrency.getId().equals(toCurrency.getId())) {
                                            BigDecimal exchangeRate = BigDecimal.ZERO;
                                            // check at invoice document level
                                            List<ConversionRateDoc> conversionRateDocumentForInvoice = getConversionRateDocumentForInvoice(
                                                    invoiceForConversion);
                                            if (conversionRateDocumentForInvoice.size() > 0) {
                                                exchangeRate = conversionRateDocumentForInvoice.get(0)
                                                        .getRate();
                                            } else {
                                                // global
                                                exchangeRate = getConversionRate(
                                                        payment.getOrganization().getId(), fromCurrency.getId(),
                                                        toCurrency.getId(),
                                                        invoiceForConversion != null
                                                                ? invoiceForConversion.getInvoiceDate()
                                                                : payment.getPaymentDate());
                                            }
                                            if (exchangeRate == BigDecimal.ZERO) {
                                                msg = OBMessageUtils.messageBD("NoCurrencyConversion");
                                                throw new OBException(msg);
                                            }
                                            paidAmount = amount.multiply(exchangeRate);
                                        } else {
                                            paidAmount = amount;
                                        }
                                        if (isReceipt) {
                                            increaseCustomerCredit(businessPartner, paidAmount);
                                        } else {
                                            decreaseCustomerCredit(businessPartner, paidAmount);
                                        }
                                    }
                                }
                            }
                            if (paymentScheduleDetail.getOrderPaymentSchedule() != null && restorePaidAmounts) {
                                FIN_AddPayment.updatePaymentScheduleAmounts(paymentDetail,
                                        paymentScheduleDetail.getOrderPaymentSchedule(), psdAmount.negate(),
                                        psdWriteoffAmount.negate());
                            }
                            if (restorePaidAmounts) {
                                // when generating credit for a BP SO_CreditUsed is also updated
                                if (paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                        && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                        && paymentScheduleDetail.getPaymentDetails().getGLItem() == null
                                        && restorePaidAmounts && !paymentDetail.isRefund()) {
                                    // BP SO_CreditUsed
                                    if (isReceipt) {
                                        increaseCustomerCredit(businessPartner, amount);
                                    } else {
                                        decreaseCustomerCredit(businessPartner, amount);
                                    }
                                }
                            }
                        }

                        if (strAction.equals("R") || (strAction.equals("RE")
                                && paymentScheduleDetail.getInvoicePaymentSchedule() == null
                                && paymentScheduleDetail.getOrderPaymentSchedule() == null
                                && paymentScheduleDetail.getPaymentDetails().getGLItem() == null)) {
                            FIN_AddPayment.mergePaymentScheduleDetails(paymentScheduleDetail);
                            removedPDS.add(paymentScheduleDetail);
                        }

                    }
                    paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
                    if (strAction.equals("R")) {
                        OBDal.getInstance().getSession().refresh(paymentDetail);
                    }
                    // If there is any schedule detail with amount zero, those are deleted
                    // Besides it removes the payment proposal lines linked to the PSD when
                    // a) we are removing the PSD and
                    // b) if we are reactivating a payment (deleting lines only) and we don't come from
                    // payment proposal reactivation process
                    for (FIN_PaymentScheduleDetail psd : removedPDS) {
                        int proposalLinesRemoved = 0;
                        if (BigDecimal.ZERO.compareTo(psd.getAmount()) == 0
                                && BigDecimal.ZERO.compareTo(psd.getWriteoffAmount()) == 0) {
                            paymentDetail.getFINPaymentScheduleDetailList().remove(psd);
                            OBDal.getInstance().getSession().refresh(paymentDetail);
                            if (psd.getInvoicePaymentSchedule() != null) {
                                psd.getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList().remove(psd);
                            }
                            if (psd.getOrderPaymentSchedule() != null) {
                                psd.getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList().remove(psd);
                            }

                            // Before deleting the PSD, we must delete any payment proposal line linked to it
                            proposalLinesRemoved = removePaymentProposalLines(psd);

                            OBDal.getInstance().remove(psd);
                        }

                        // Delete any payment proposal line linked to the PSD if we are reactivating a payment
                        // (deleting lines only), we haven't removed it in a previous step and we don't come
                        // from payment proposal reactivation process
                        if (strAction.equals("R") && proposalLinesRemoved == 0
                                && !StringUtils.equals(comingFrom,
                                        FIN_PaymentProposalProcess.COMINGFROM_PAYMENTPROPOSALPROCESS)) {
                            removePaymentProposalLines(psd);
                        }
                    }
                    if (paymentDetail.getFINPaymentScheduleDetailList().size() == 0) {
                        removedPD.add(paymentDetail);
                        removedPDIds.add(paymentDetail.getId());
                    }
                    OBDal.getInstance().save(paymentDetail);
                }
                for (String pdToRm : removedPDIds) {
                    OBDal.getInstance().remove(OBDal.getInstance().get(FIN_PaymentDetail.class, pdToRm));
                }
                payment.getFINPaymentDetailList().removeAll(removedPD);
                if (strAction.equals("R")) {
                    payment.getCurrencyConversionRateDocList().removeAll(conversionRates);
                    payment.setFinancialTransactionConvertRate(BigDecimal.ZERO);
                }
                OBDal.getInstance().save(payment);

                if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                        && payment.getUsedCredit().compareTo(BigDecimal.ZERO) != 0) {
                    undoUsedCredit(payment, invoiceDocNos);
                }

                List<FIN_Payment> creditPayments = new ArrayList<FIN_Payment>();
                for (final FIN_Payment_Credit pc : payment.getFINPaymentCreditList()) {
                    creditPayments.add(pc.getCreditPaymentUsed());
                }
                for (final FIN_Payment creditPayment : creditPayments) {
                    // Update Description
                    final String payDesc = creditPayment.getDescription();
                    if (payDesc != null) {
                        final String invoiceDocNoMsg = OBMessageUtils.messageBD("APRM_CreditUsedinInvoice");
                        if (invoiceDocNoMsg != null) {
                            final StringBuffer newDesc = new StringBuffer();
                            for (final String line : payDesc.split("\n")) {
                                boolean include = true;
                                if (line.startsWith(
                                        invoiceDocNoMsg.substring(0, invoiceDocNoMsg.lastIndexOf("%s")))) {
                                    for (final String docNo : invoiceDocNos) {
                                        if (line.indexOf(docNo) > 0) {
                                            include = false;
                                            break;
                                        }
                                    }
                                }
                                if (include) {
                                    newDesc.append(line);
                                    if (!"".equals(line))
                                        newDesc.append("\n");
                                }
                            }
                            // Truncate Description to keep length as 255
                            creditPayment.setDescription(
                                    newDesc.toString().length() > 255 ? newDesc.toString().substring(0, 255)
                                            : newDesc.toString());
                        }
                    }
                }

                payment.getFINPaymentCreditList().clear();
                if (payment.isReceipt() || strAction.equals("R")) {
                    payment.setGeneratedCredit(BigDecimal.ZERO);
                }
                if (strAction.equals("R")) {
                    payment.setUsedCredit(BigDecimal.ZERO);
                }
            } finally {
                OBDal.getInstance().flush();
                OBContext.restorePreviousMode();
            }

        } else if (strAction.equals("V")) {
            // Void
            OBContext.setAdminMode();
            try {
                if (payment.isProcessed()) {
                    // Already Posted Document
                    if ("Y".equals(payment.getPosted())) {
                        msg = OBMessageUtils.messageBD("PostedDocument: " + payment.getDocumentNo());
                        throw new OBException(msg);
                    }
                    // Transaction exists
                    if (hasTransaction(payment)) {
                        msg = OBMessageUtils.messageBD("APRM_TransactionExists");
                        throw new OBException(msg);
                    }
                    // Payment with generated credit already used on other payments.
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 1
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                        msg = OBMessageUtils.messageBD("APRM_PaymentGeneratedCreditIsUsed");
                        throw new OBException(msg);
                    }
                    // Payment not in Awaiting Execution
                    boolean restorePaidAmounts = (FIN_Utility
                            .seqnumberpaymentstatus(payment.getStatus())) < (FIN_Utility
                                    .seqnumberpaymentstatus(FIN_Utility.invoicePaymentStatus(payment)));
                    if (!restorePaidAmounts) {
                        msg = OBMessageUtils.messageBD("APRM_PaymentNotRPAE_NotVoid");
                        throw new OBException(msg);
                    }

                    /*
                     * Void the payment
                     */
                    payment.setStatus("RPVOID");

                    /*
                     * Cancel all payment schedule details related to the payment
                     */
                    final List<FIN_PaymentScheduleDetail> removedPDS = new ArrayList<FIN_PaymentScheduleDetail>();
                    Set<String> invoiceDocNos = new HashSet<String>();
                    for (final FIN_PaymentDetail paymentDetail : payment.getFINPaymentDetailList()) {
                        for (final FIN_PaymentScheduleDetail paymentScheduleDetail : paymentDetail
                                .getFINPaymentScheduleDetailList()) {
                            Boolean invoicePaidold = paymentScheduleDetail.isInvoicePaid();
                            if (invoicePaidold | paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                                paymentScheduleDetail.setInvoicePaid(false);
                            }
                            BigDecimal outStandingAmt = BigDecimal.ZERO;

                            if (paymentScheduleDetail.getInvoicePaymentSchedule() != null) {
                                // Related to invoices
                                for (final FIN_PaymentScheduleDetail invScheDetail : paymentScheduleDetail
                                        .getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList()) {
                                    if (invScheDetail.isCanceled()) {
                                        continue;
                                    }
                                    if (invScheDetail.getPaymentDetails() == null) {
                                        outStandingAmt = outStandingAmt.add(invScheDetail.getAmount())
                                                .add(invScheDetail.getWriteoffAmount());
                                        removedPDS.add(invScheDetail);
                                    } else if (invScheDetail.equals(paymentScheduleDetail)) {
                                        outStandingAmt = outStandingAmt.add(invScheDetail.getAmount())
                                                .add(invScheDetail.getWriteoffAmount());
                                        paymentScheduleDetail.setCanceled(true);
                                    }
                                    invoiceDocNos.add(paymentScheduleDetail.getInvoicePaymentSchedule()
                                            .getInvoice().getDocumentNo());
                                }
                                // Create merged Payment Schedule Detail with the pending to be paid amount
                                if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) {
                                    final FIN_PaymentScheduleDetail mergedScheduleDetail = dao
                                            .getNewPaymentScheduleDetail(payment.getOrganization(),
                                                    outStandingAmt);
                                    mergedScheduleDetail.setInvoicePaymentSchedule(
                                            paymentScheduleDetail.getInvoicePaymentSchedule());
                                    mergedScheduleDetail.setOrderPaymentSchedule(
                                            paymentScheduleDetail.getOrderPaymentSchedule());
                                    OBDal.getInstance().save(mergedScheduleDetail);
                                }
                            } else if (paymentScheduleDetail.getOrderPaymentSchedule() != null) {
                                // Related to orders
                                for (final FIN_PaymentScheduleDetail ordScheDetail : paymentScheduleDetail
                                        .getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList()) {
                                    if (ordScheDetail.isCanceled()) {
                                        continue;
                                    }
                                    if (ordScheDetail.getPaymentDetails() == null) {
                                        outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount())
                                                .add(ordScheDetail.getWriteoffAmount());
                                        removedPDS.add(ordScheDetail);
                                    } else if (ordScheDetail.equals(paymentScheduleDetail)) {
                                        outStandingAmt = outStandingAmt.add(ordScheDetail.getAmount())
                                                .add(ordScheDetail.getWriteoffAmount());
                                        paymentScheduleDetail.setCanceled(true);
                                    }
                                }
                                // Create merged Payment Schedule Detail with the pending to be paid amount
                                if (outStandingAmt.compareTo(BigDecimal.ZERO) != 0) {
                                    final FIN_PaymentScheduleDetail mergedScheduleDetail = dao
                                            .getNewPaymentScheduleDetail(payment.getOrganization(),
                                                    outStandingAmt);
                                    mergedScheduleDetail.setOrderPaymentSchedule(
                                            paymentScheduleDetail.getOrderPaymentSchedule());
                                    OBDal.getInstance().save(mergedScheduleDetail);
                                }
                            } else if (paymentDetail.getGLItem() != null) {
                                paymentScheduleDetail.setCanceled(true);
                            } else if (paymentScheduleDetail.getOrderPaymentSchedule() == null
                                    && paymentScheduleDetail.getInvoicePaymentSchedule() == null) {
                                // Credit payment
                                payment.setGeneratedCredit(payment.getGeneratedCredit()
                                        .subtract(paymentScheduleDetail.getAmount()));
                                removedPDS.add(paymentScheduleDetail);
                            }

                            OBDal.getInstance().save(payment);
                            OBDal.getInstance().flush();
                        }
                        paymentDetail.getFINPaymentScheduleDetailList().removeAll(removedPDS);
                        for (FIN_PaymentScheduleDetail removedPD : removedPDS) {
                            if (removedPD.getOrderPaymentSchedule() != null) {
                                removedPD.getOrderPaymentSchedule()
                                        .getFINPaymentScheduleDetailOrderPaymentScheduleList()
                                        .remove(removedPD);
                                OBDal.getInstance().save(removedPD.getOrderPaymentSchedule());
                            }
                            if (removedPD.getInvoicePaymentSchedule() != null) {
                                removedPD.getInvoicePaymentSchedule()
                                        .getFINPaymentScheduleDetailInvoicePaymentScheduleList()
                                        .remove(removedPD);
                                OBDal.getInstance().save(removedPD.getInvoicePaymentSchedule());
                            }
                            OBDal.getInstance().remove(removedPD);
                        }
                        OBDal.getInstance().flush();
                        removedPDS.clear();

                    }
                    if (payment.getGeneratedCredit().compareTo(BigDecimal.ZERO) == 0
                            && payment.getUsedCredit().compareTo(BigDecimal.ZERO) == 1) {
                        undoUsedCredit(payment, invoiceDocNos);
                    }
                    payment.getFINPaymentCreditList().clear();
                    payment.setUsedCredit(BigDecimal.ZERO);
                }
                OBDal.getInstance().flush();
            } finally {
                OBContext.restorePreviousMode();
            }
        }
    } catch (final Exception e) {
        log4j.error(e.getMessage());
        msg = OBMessageUtils.translateError(FIN_Utility.getExceptionMessage(e)).getMessage();
        throw new OBException(msg);
    }
}

From source file:com.glaf.base.modules.sys.springmvc.SysTreeController.java

/**
 * ?/*  w w w .  j a v  a 2 s . co m*/
 * 
 * @param request
 * @param modelMap
 * @return
 */
@RequestMapping(params = "method=showPerms")
public ModelAndView showPerms(HttpServletRequest request, ModelMap modelMap) {
    RequestUtils.setRequestParameterToAttribute(request);
    long nodeId = ParamUtil.getIntParameter(request, "nodeId", 0);
    SysTree bean = sysTreeService.findById(nodeId);
    if (bean != null && bean.getParentId() > 0) {
        SysTree parent = sysTreeService.findById(bean.getParentId());
        bean.setParent(parent);
    }
    request.setAttribute("bean", bean);
    List<SysTree> list = new java.util.ArrayList<SysTree>();
    sysTreeService.loadSysTrees(list, 0, 0);
    request.setAttribute("parent", list);

    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);

    String rowId = ParamUtils.getString(paramMap, "id");
    String moduleId = ParamUtils.getString(paramMap, "moduleId");
    String entityId = ParamUtils.getString(paramMap, "entityId");
    String entryKey = ParamUtils.getString(paramMap, "entryKey");
    String dataCode = ParamUtils.getString(paramMap, "dataCode");
    StringBuffer rolesBuffer = new StringBuffer();
    StringBuffer rolesNameBuffer = new StringBuffer();
    StringBuffer deptsBuffer = new StringBuffer();
    StringBuffer deptsNameBuffer = new StringBuffer();
    StringBuffer usersBuffer = new StringBuffer();
    StringBuffer usersNameBuffer = new StringBuffer();

    Map<Long, Role> roleMap = IdentityFactory.getRoleMap();
    Map<String, User> userMap = IdentityFactory.getUserMap();
    Map<Long, TreeModel> deptMap = IdentityFactory.getDepartmentMap();

    if (entryKey == null) {
        entryKey = "r";
    }

    EntityEntry entityEntry = null;

    if (StringUtils.isNotEmpty(moduleId) && StringUtils.isNotEmpty(entityId)
            && StringUtils.isNotEmpty(entryKey)) {
        entityEntry = entryService.getEntityEntry(moduleId, entityId, entryKey);
    } else if (nodeId > 0) {
        entityEntry = entryService.getEntityEntry(nodeId, entryKey);
    } else if (StringUtils.isNotEmpty(rowId)) {
        entityEntry = entryService.getEntityEntry(rowId);
    }

    if (entityEntry != null && entityEntry.getEntryPoints() != null) {
        Iterator<EntryPoint> iter = entityEntry.getEntryPoints().iterator();
        while (iter.hasNext()) {
            EntryPoint entryPoint = iter.next();
            String value = entryPoint.getValue();
            if ("ROLE".equals(entryPoint.getName())) {
                Role role = roleMap.get(Long.parseLong(value));
                if (role != null) {
                    rolesBuffer.append(role.getRoleId()).append(',');
                    rolesNameBuffer.append(role.getName()).append(',');
                }
            } else if ("DEPT".equals(entryPoint.getName())) {
                TreeModel treeModel = deptMap.get(Long.parseLong(value));
                if (treeModel != null) {
                    deptsBuffer.append(treeModel.getId()).append(',');
                    deptsNameBuffer.append(treeModel.getName()).append(',');
                }
            } else if ("USER".equals(entryPoint.getName())) {
                User user = userMap.get(value);
                if (user != null) {
                    usersBuffer.append(user.getActorId()).append(',');
                    usersNameBuffer.append(user.getName()).append(',');
                }
            }
        }
    }

    if (rolesBuffer.length() > 0) {
        rolesBuffer.delete(rolesBuffer.length() - 1, rolesBuffer.length());
    }

    if (rolesNameBuffer.length() > 0) {
        rolesNameBuffer.delete(rolesNameBuffer.length() - 1, rolesNameBuffer.length());
    }

    if (deptsBuffer.length() > 0) {
        deptsBuffer.delete(deptsBuffer.length() - 1, deptsBuffer.length());
    }

    if (deptsNameBuffer.length() > 0) {
        deptsNameBuffer.delete(deptsNameBuffer.length() - 1, deptsNameBuffer.length());
    }

    if (usersBuffer.length() > 0) {
        usersBuffer.delete(usersBuffer.length() - 1, usersBuffer.length());
    }

    if (usersNameBuffer.length() > 0) {
        usersNameBuffer.delete(usersNameBuffer.length() - 1, usersNameBuffer.length());
    }

    if (StringUtils.isEmpty(dataCode)) {
        dataCode = "entityEntryCode";
    }

    modelMap.put("entityEntry", entityEntry);
    modelMap.put("roleMap", roleMap);
    modelMap.put("x_roles", rolesBuffer.toString());
    modelMap.put("x_roles_name", rolesNameBuffer.toString());
    modelMap.put("x_users", usersBuffer.toString());
    modelMap.put("x_users_name", usersNameBuffer.toString());
    modelMap.put("x_departments", deptsBuffer.toString());
    modelMap.put("x_departments_name", deptsNameBuffer.toString());

    String x_view = ViewProperties.getString("tree.showPerms");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view, modelMap);
    }

    return new ModelAndView("/modules/sys/tree/showPerms", modelMap);
}

From source file:marytts.tools.dbselection.WikipediaMarkupCleaner.java

/****
 * This is also special because the line might contain sections with [[ ...  ]] so the ]] after a [[
 * is not the endTag of [[image:  ... ]]
 * @param s/*from   w  w w  .j av a  2 s.  c  om*/
 * @param lineIn
 * @param iniTag
 * @param endTag
 * @param debug
 * @return
 */
private StringBuffer removeSectionImage(Scanner s, StringBuffer lineIn, String iniTag, String endTag) {
    String next;
    int index1 = 0, index2 = -1, index3 = -1, endTagLength = 0, numRef = 0, lastEndTag1 = 0, lastIniTag = 0;
    boolean closeRef = true;
    StringBuffer line = new StringBuffer(lineIn);
    StringBuffer nextLine;
    StringBuffer aux;

    if (debug)
        System.out.println("Removing tag: " + iniTag + "  LINE (BEFORE): " + line);

    while ((index1 = line.indexOf(iniTag)) >= 0) { // in one line can be more than one iniTag

        numRef++;
        index3 = endTagLength = index1;

        while (s.hasNext() && numRef > 0) {

            while ((index2 = line.indexOf("]]", endTagLength)) >= 0 && numRef > 0) {
                aux = new StringBuffer(line.subSequence(index1 + 2, index2 + 2));
                if (debug)
                    System.out.println("    aux=" + aux);
                if ((index3 = aux.indexOf("[[")) == -1) {
                    endTagLength = endTag.length() + index2;
                    numRef--;
                } else { // The previous was a [[ ]] inside of a [[Image: so it has to be deleted
                    index1 = index2;
                    endTagLength = index2 + 2;
                    index2 = -1;
                }
            }
            // so far it has not found the endTag, so get another line
            if (numRef > 0)
                line.append(s.nextLine());
        }

        if (numRef == 0) {
            index1 = line.indexOf(iniTag); // get again this because the position might change
            if (endTagLength > index1) {
                if (debug) {
                    System.out.println("    FINAL LINE: " + line);
                    System.out.print("iniTag: " + iniTag + "  index1=" + index1);
                    System.out.print("  endTagLength=" + endTagLength);
                    System.out.println("  line.length=" + line.length() + "  line: " + line);
                    System.out.println("  line.length=" + line.length());
                }
                line.delete(index1, endTagLength);
            } else {
                if (debug) {
                    System.out.println("removeSection: WARNING endTagLength > length of line: ");
                    System.out.print("iniTag: " + iniTag + "  index1=" + index1);
                    System.out.print("  endTagLength=" + endTagLength);
                    System.out.println("  line.length=" + line.length() + "  line: " + line);
                    System.out.println("removeSection: WARNING endTagLength > length of line: " + line);
                }
                line = new StringBuffer("");
            }

        } else {
            if (debug)
                System.out.println("removeSection: WARNING no " + endTag);
            line = new StringBuffer("");
        }

    } // while this line contains iniTag-s

    if (debug)
        System.out.println("    LINE (AFTER): " + line);
    return line;
}

From source file:org.openbravo.userinterface.selector.CustomQuerySelectorDatasource.java

/**
 * Generates the HQL Sort By Clause to append to the query being executed. If no sort options is
 * set on the sortBy parameter the result is ordered by the first shown grid's column.
 * //from   w  w  w .  ja v a 2 s  .  co  m
 * @param sortBy
 *          String of grid's field names concatenated by JsonConstants.IN_PARAMETER_SEPARATOR.
 * @param sel
 *          the selector that it is being displayed.
 * @return a String with the HQL Sort By clause.
 */
private String getSortClause(String sortBy, Selector sel) {
    StringBuffer sortByClause = new StringBuffer();
    boolean sortByDesc = false;
    if (sortBy != null && sortBy.startsWith("-")) {
        sortByDesc = true;
    }
    // If grid is manually filtered sortBy is not empty
    if (StringUtils.isNotEmpty(sortBy)) {
        if (sortBy.contains(JsonConstants.IN_PARAMETER_SEPARATOR)) {
            final String[] fieldNames = sortBy.split(JsonConstants.IN_PARAMETER_SEPARATOR);
            for (String fieldName : fieldNames) {
                if (sortByDesc) {
                    fieldName = fieldName.substring(1, fieldName.length());
                }
                int fieldSortIndex = getFieldSortIndex(fieldName, sel);
                if (fieldSortIndex > 0) {
                    if (sortByClause.length() > 0) {
                        sortByClause.append(", ");
                    }
                    if (sortByDesc) {
                        sortByClause.append(fieldSortIndex + " desc");
                    } else {
                        sortByClause.append(fieldSortIndex);
                    }
                }
            }
        } else {
            String fieldName = null;
            if (sortByDesc) {
                fieldName = sortBy.substring(1, sortBy.length());
            } else {
                fieldName = sortBy;
            }
            int fieldSortIndex = getFieldSortIndex(fieldName, sel);
            if (fieldSortIndex > 0) {
                if (sortByDesc) {
                    sortByClause.append(fieldSortIndex + " desc");
                } else {
                    sortByClause.append(fieldSortIndex);
                }
            }
        }
    }

    // If sortByClause is empty set default sort options.
    if (sortByClause.length() == 0) {
        OBCriteria<SelectorField> selFieldsCrit = OBDao.getFilteredCriteria(SelectorField.class,
                Restrictions.eq(SelectorField.PROPERTY_OBUISELSELECTOR, sel),
                Restrictions.eq(SelectorField.PROPERTY_SHOWINGRID, true));
        selFieldsCrit.addOrderBy(SelectorField.PROPERTY_SORTNO, true);
        for (SelectorField selField : selFieldsCrit.list()) {
            int fieldSortIndex = getFieldSortIndex(selField.getDisplayColumnAlias(), sel);
            if (fieldSortIndex > 0) {
                sortByClause.append(fieldSortIndex + ", ");
            }
        }
        // Delete last 2 characters: ", "
        if (sortByClause.length() > 0) {
            sortByClause.delete(sortByClause.length() - 2, sortByClause.length() - 1);
        }
    }
    String result = "";
    if (sortByClause.length() > 0) {
        result = "\n ORDER BY " + sortByClause.toString();
    }

    return result;
}

From source file:lcmc.gui.ClusterBrowser.java

/** Process output from cluster. */
void processClusterOutput(final String output, final StringBuffer clusterStatusOutput, final Host host,
        final CountDownLatch firstTime, final boolean testOnly) {
    final ClusterStatus clStatus = clusterStatus;
    clStatusLock();/*from w  ww  . jav a 2s .  co m*/
    if (clStatusCanceled || clStatus == null) {
        clStatusUnlock();
        firstTime.countDown();
        return;
    }
    if (output == null || "".equals(output)) {
        clStatus.setOnlineNode(host.getName(), "no");
        setClStatus(host, false);
        firstTime.countDown();
    } else {
        // TODO: if we get ERROR:... show it somewhere
        clusterStatusOutput.append(output);
        /* removes the string from the output. */
        int s = clusterStatusOutput.indexOf(RESET_STRING);
        while (s >= 0) {
            clusterStatusOutput.delete(s, s + RESET_STRING_LEN);
            s = clusterStatusOutput.indexOf(RESET_STRING);
        }
        if (clusterStatusOutput.length() > 12) {
            final String e = clusterStatusOutput.substring(clusterStatusOutput.length() - 12);
            if (e.trim().equals("---done---")) {
                final int i = clusterStatusOutput.lastIndexOf("---start---");
                if (i >= 0) {
                    if (clusterStatusOutput.indexOf("is stopped") >= 0) {
                        /* TODO: heartbeat's not running. */
                    } else {
                        final String status = clusterStatusOutput.substring(i);
                        clusterStatusOutput.delete(0, clusterStatusOutput.length());
                        if (CLUSTER_STATUS_ERROR.equals(status)) {
                            final boolean oldStatus = host.isClStatus();
                            clStatus.setOnlineNode(host.getName(), "no");
                            setClStatus(host, false);
                            if (oldStatus) {
                                crmGraph.repaint();
                            }
                        } else {
                            if (clStatus.parseStatus(status)) {
                                Tools.debug(this, "update cluster status: " + host.getName(), 1);
                                final ServicesInfo ssi = servicesInfo;
                                rscDefaultsInfo.setParameters(clStatus.getRscDefaultsValuePairs());
                                ssi.setGlobalConfig(clStatus);
                                ssi.setAllResources(clStatus, testOnly);
                                if (firstTime.getCount() == 1) {
                                    /* one more time so that id-refs work.*/
                                    ssi.setAllResources(clStatus, testOnly);
                                }
                                repaintTree();
                                clusterHostsInfo.updateTable(ClusterHostsInfo.MAIN_TABLE);
                            }
                            final String online = clStatus.isOnlineNode(host.getName());
                            if ("yes".equals(online)) {
                                setClStatus(host, true);
                                setClStatus();
                            } else {
                                setClStatus(host, false);
                            }
                        }
                    }
                    firstTime.countDown();
                }
            }
        }
        Tools.chomp(clusterStatusOutput);
    }
    clStatusUnlock();
}

From source file:dao.CarryonDaoDb.java

/**
  * updates only caption for the blob in carryon.
  * @param entryid - the entry id/*from  w  w w  .  j  a  v a2  s .c om*/
  * @param memberId - the member id
  * @param category - the category
  * @param member - the member
  * @param caption - caption
  * @throws BaseDaoException If we have a problem interpreting the data or the data is missing or incorrect
  */
public void updateOnlyCaption(String entryid, String memberId, String category, String member, String caption)
        throws BaseDaoException {

    if (RegexStrUtil.isNull(memberId) || RegexStrUtil.isNull(caption) || RegexStrUtil.isNull(entryid)
            || RegexStrUtil.isNull(member)) {
        throw new BaseDaoException("null parameters passed");
    }

    /**
     * Set the source based on scalability
     */
    String sourceName = scalabilityManager.getWriteBlobScalability(memberId);
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds is null for sourceName = " + sourceName);
    }

    Connection conn = null;
    try {
        conn = ds.getConnection();
        if (conn != null) {
            updateCaptionQuery.run(conn, entryid, memberId, caption);
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("conn.close() error in updateCaptionQuery() carryon", e1);
        }
        throw new BaseDaoException("error occured in updateCaptionQuery() carryon", e);
    }

    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e4) {
        throw new BaseDaoException("connection close exception in updateCaptionQuery", e4);
    }

    /**
     * update only caption for tags
     */
    sourceName = scalabilityManager.getWriteZeroScalability();
    ds = scalabilityManager.getSource(sourceName);
    if (ds == null) {
        throw new BaseDaoException("ds is null for sourceName = " + sourceName);
    }

    conn = null;
    try {
        conn = ds.getConnection();
        if (conn != null) {
            carryonTagCaptionUpdateQuery.run(conn, caption, entryid, memberId);
        }
    } catch (Exception e) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e1) {
            throw new BaseDaoException("connection close exception for carryonTagCaptionUpdateQuery()", e1);
        }
        StringBuffer sb = new StringBuffer("error occured while executing in updateOnlyCaption()  caption = ");
        sb.append(caption);
        sb.append(" entryid = ");
        sb.append(entryid);
        sb.append(" memberId = ");
        sb.append(memberId);
        throw new BaseDaoException(sb.toString(), e);
    }

    // close the connection
    try {
        if (conn != null) {
            conn.close();
        }
    } catch (Exception e1) {
        throw new BaseDaoException("connection close exception", e1);
    }

    /**
     * remove from userstreamblob based on the key (memberId+entryid)
     */
    StringBuffer sb = new StringBuffer(memberId);
    sb.append("-");
    sb.append(entryid);
    String key = sb.toString();
    Fqn fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOB_ENTRY);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }
    fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOB_DATA);
    if (treeCache.exists(fqn, key)) {
        treeCache.remove(fqn, key);
    }

    /**
     * uses memberid-category key
     */
    sb.delete(0, sb.length());
    sb.append(memberId);
    sb.append("-");
    sb.append(category);
    fqn = cacheUtil.fqn(DbConstants.USER_STREAM_BLOBS_CAT);
    if (treeCache.exists(fqn, sb.toString())) {
        treeCache.remove(fqn, sb.toString());
    }

    /**
     * remove all entries for this user, key based on memberId 
     */
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }

    fqn = cacheUtil.fqn(DbConstants.USER_PAGE);
    if (treeCache.exists(fqn, member)) {
        treeCache.remove(fqn, member);
    }

    fqn = cacheUtil.fqn(DbConstants.DEFAULT_PHOTO);
    if (treeCache.exists(fqn, memberId)) {
        treeCache.remove(fqn, memberId);
    }
}

From source file:cn.jsprun.struts.action.BasicSettingsAction.java

@SuppressWarnings("unchecked")
public ActionForward functions(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {//from  w ww.ja  va  2  s. com
    try {
        if (submitCheck(request, "settingsubmit")) {
            String variables[] = { "forumjump", "jsmenustatus", "pluginjsmenu", "editoroptions", "bbinsert",
                    "smileyinsert", "smthumb", "smcols", "smrows", "statstatus", "statscachelife",
                    "pvfrequence", "oltimespan", "modworkstatus", "maxmodworksmonths", "myrecorddays",
                    "losslessdel", "modreasons", "bannedmessages", "tagstatus", "hottags", "viewthreadtags",
                    "rssstatus", "rssttl", "allowcsscache", "bdaystatus", "debug", "activitytype" };
            Map<String, String> oldSettings = ForumInit.settings;
            Map<String, String> settings = new HashMap<String, String>();
            for (String variable : variables) {
                String value = request.getParameter(variable);
                if ("jsmenustatus".equals(variable)) {
                    int sum = 0;
                    for (int j = 0; j < 4; j++) {
                        String par = request.getParameter(variable + j);
                        if (par != null)
                            sum = sum + Integer.valueOf(par);
                    }
                    value = String.valueOf(sum);
                    oldSettings.put("jsmenu_1", String.valueOf(sum & 1));
                    oldSettings.put("jsmenu_2", String.valueOf(sum & 2));
                    oldSettings.put("jsmenu_3", String.valueOf(sum & 4));
                    oldSettings.put("jsmenu_4", String.valueOf(sum & 8));
                } else if ("editoroptions".equals(variable) || "editoroptions_changer".equals(variable)) {
                    int editoroptions_editer = Integer.valueOf(request.getParameter("editoroptions_editer"));
                    int editoroptions_changer = Integer.valueOf(request.getParameter("editoroptions_changer"));
                    value = String.valueOf(editoroptions_editer + editoroptions_changer);
                } else if (Common.matches(variable,
                        "^(smcols|statscachelife|pvfrequence|oltimespan|maxmodworksmonths|losslessdel|rssttl)$")) {
                    value = Double.valueOf(FormDataCheck.getDoubleString(value)).toString();
                    if (value.endsWith(".0")) {
                        value = value.substring(0, value.length() - 2);
                    }
                } else if ("smthumb".equals(variable)) {
                    long smthumb = Common.toDigit(value);
                    value = String.valueOf(smthumb);
                    if (!(smthumb >= 20 && smthumb <= 40)) {
                        value = "20";
                    }
                } else if ("myrecorddays".equals(variable)) {
                    long myrecorddays = Common.toDigit(value);
                    value = String.valueOf(myrecorddays);
                    if (myrecorddays < 1) {
                        value = "30";
                    }
                }
                this.putValue(variable, value, oldSettings, settings);
            }
            String honorset = request.getParameter("honorset");
            this.putValue("honorset", honorset, oldSettings, settings);
            String[] medalIdArray = request.getParameterValues("au_medalid");
            List<Map<String, String>> medalMapList = dataBaseService
                    .executeQuery("SELECT medalid FROM " + tablePrefix + "medals WHERE available");
            Map<String, Map<String, String>> honorvalueTDP = new HashMap<String, Map<String, String>>();
            boolean checked_b = false;
            for (Map<String, String> medalMap : medalMapList) {
                checked_b = false;
                String medalid = medalMap.get("medalid");
                Map<String, String> honorvalueIMP = new HashMap<String, String>();
                honorvalueTDP.put(medalid, honorvalueIMP);
                if (medalIdArray != null) {
                    for (String medalIdFR : medalIdArray) {
                        if (medalid.equals(medalIdFR)) {
                            checked_b = true;
                            break;
                        }
                    }
                }
                honorvalueIMP.put("checked", checked_b ? "1" : "0");
                String qualification = request.getParameter("mqualification_" + medalid);
                if (checked_b && (qualification == null || qualification.trim().equals("")
                        || !validateQualification(qualification))) {
                    request.setAttribute("message", getMessage(request, "a_setting_creditsformula_invalid"));
                    request.setAttribute("return", true);
                    return mapping.findForward("message");
                }
                honorvalueIMP.put("qualification", qualification);
                honorvalueIMP.put("reason", request.getParameter("mreason_" + medalid));
            }
            String honorvalue = dataParse.combinationChar(honorvalueTDP);
            this.putValue("honorvalue", honorvalue, oldSettings, settings);
            this.updateSettings(settings, oldSettings);
            if ("2".equals(honorset) && medalIdArray != null) {
                Members currentMember = (Members) request.getSession().getAttribute("members");
                int timestamp = (Integer) (request.getAttribute("timestamp"));
                StringBuffer uids = new StringBuffer();
                StringBuffer logBuffer = new StringBuffer();
                for (String medalId : medalIdArray) {
                    uids.delete(0, uids.length());
                    uids.append("0");
                    Map<String, String> honorvalueIMP = honorvalueTDP.get(medalId);
                    String qualification = honorvalueIMP.get("qualification");
                    String reason = honorvalueIMP.get("reason");
                    qualification = qualification.replace("extcredits", "m.extcredits")
                            .replace("oltime", "m.oltime").replace("pageviews", "m.pageviews")
                            .replaceAll("posts", "temp").replace("digesttemp", "m.digestposts")
                            .replace("temp", "m.posts");
                    List<Map<String, String>> memberslist = dataBaseService
                            .executeQuery("select m.uid,m.username,mm.medals from " + tablePrefix
                                    + "members as m left join " + tablePrefix
                                    + "memberfields as mm on m.uid=mm.uid where " + qualification);
                    boolean exist = false;
                    if (memberslist != null) {
                        String onlineip = Common.get_onlineip(request);
                        for (Map<String, String> memberIfMap : memberslist) {
                            String mmMedals = memberIfMap.get("medals");
                            exist = false;
                            if (mmMedals != null && !mmMedals.equals("")) {
                                String[] mmMedalsArray = mmMedals.split("\t");
                                for (String mmMedal : mmMedalsArray) {
                                    if (mmMedal.equals(medalId)) {
                                        exist = true;
                                        break;
                                    }
                                }
                            }
                            if (!exist) {
                                uids.append(",").append(memberIfMap.get("uid"));
                                int lbl = logBuffer.length();
                                if (lbl > 1024000) {
                                    Log.writelog("medalslog", timestamp, logBuffer.toString(), true);
                                    logBuffer.delete(0, lbl);
                                }
                                logBuffer.append("<?JSP exit;?>\t");
                                logBuffer.append(timestamp);
                                logBuffer.append("\t");
                                logBuffer.append(currentMember.getUsername().replaceAll("\n", " "));
                                logBuffer.append("\t");
                                logBuffer.append(onlineip);
                                logBuffer.append("\t");
                                logBuffer.append(memberIfMap.get("username"));
                                logBuffer.append("\t");
                                logBuffer.append(medalId);
                                logBuffer.append("\tgrant\t");
                                logBuffer.append(reason.replaceAll("\n", " "));
                                logBuffer.append("\n");
                            }
                        }
                    }
                    String uidInfo = uids.toString();
                    if (!uidInfo.equals("0")) {
                        dataBaseService
                                .execute("UPDATE " + tablePrefix + "memberfields SET medals=concat(medals,'"
                                        + medalId + "\t') where uid IN(" + uidInfo + ")");
                    }
                }
                if (logBuffer.length() > 0) {
                    Log.writelog("medalslog", timestamp, logBuffer.toString(), true);
                }
            }
            return this.getForward(mapping, request);
        }
    } catch (Exception e) {
        request.setAttribute("message", e.getMessage());
        return mapping.findForward("message");
    }
    Map<String, String> settings = ForumInit.settings;
    int jsmenustatus = Integer.valueOf(settings.get("jsmenustatus"));
    Common.setChecked(request, "jsmenustatus", 4, jsmenustatus);
    List<Map<String, String>> medalMapList = dataBaseService
            .executeQuery("SELECT medalid,name,image FROM " + tablePrefix + "medals WHERE available='1'");
    String honorvalue = settings.get("honorvalue");
    Map<String, Map<String, String>> honorvalueDP = (Map<String, Map<String, String>>) dataParse
            .characterParse(honorvalue, false);
    String tempString = null;
    for (Map<String, String> medalMap : medalMapList) {
        medalMap.put("name", medalMap.get("name").replace("\"", "&quot;"));
        medalMap.put("image", medalMap.get("image").replace("\"", "&quot;"));
        Map<String, String> tempMap = honorvalueDP.get(medalMap.get("medalid"));
        if (tempMap != null) {
            tempString = tempMap.get("qualification");
            tempString = tempString != null ? tempString.replace("\"", "&quot;") : null;
            medalMap.put("qualification", tempString);
            tempString = tempMap.get("reason");
            tempString = tempString != null ? tempString.replace("\"", "&quot;") : null;
            medalMap.put("reason", tempString);
            medalMap.put("checked", tempMap.get("checked"));
        } else {
            medalMap.put("qualification", "");
            medalMap.put("reason", getMessage(request, "a_setting_auto_send"));
            medalMap.put("checked", "0");
        }
    }
    Map extcredits = dataParse.characterParse(settings.get("extcredits_bak"), true);
    request.setAttribute("medalMapList", medalMapList);
    request.setAttribute("extcredits", extcredits);
    return mapping.findForward("setting_functions");
}

From source file:com.codegarden.nativenavigation.JuceActivity.java

public static final HTTPStream createHTTPStream(String address, boolean isPost, byte[] postData, String headers,
        int timeOutMs, int[] statusCode, StringBuffer responseHeaders, int numRedirectsToFollow,
        String httpRequestCmd) {/*from   w  ww .j a va  2s. c o  m*/
    // timeout parameter of zero for HttpUrlConnection is a blocking connect (negative value for juce::URL)
    if (timeOutMs < 0)
        timeOutMs = 0;
    else if (timeOutMs == 0)
        timeOutMs = 30000;

    // headers - if not empty, this string is appended onto the headers that are used for the request. It must therefore be a valid set of HTML header directives, separated by newlines.
    // So convert headers string to an array, with an element for each line
    String headerLines[] = headers.split("\\n");

    for (;;) {
        try {
            HttpURLConnection connection = (HttpURLConnection) (new URL(address).openConnection());

            if (connection != null) {
                try {
                    connection.setInstanceFollowRedirects(false);
                    connection.setConnectTimeout(timeOutMs);
                    connection.setReadTimeout(timeOutMs);

                    // Set request headers
                    for (int i = 0; i < headerLines.length; ++i) {
                        int pos = headerLines[i].indexOf(":");

                        if (pos > 0 && pos < headerLines[i].length()) {
                            String field = headerLines[i].substring(0, pos);
                            String value = headerLines[i].substring(pos + 1);

                            if (value.length() > 0)
                                connection.setRequestProperty(field, value);
                        }
                    }

                    connection.setRequestMethod(httpRequestCmd);
                    if (isPost) {
                        connection.setDoOutput(true);

                        if (postData != null) {
                            OutputStream out = connection.getOutputStream();
                            out.write(postData);
                            out.flush();
                        }
                    }

                    HTTPStream httpStream = new HTTPStream(connection, statusCode, responseHeaders);

                    // Process redirect & continue as necessary
                    int status = statusCode[0];

                    if (--numRedirectsToFollow >= 0
                            && (status == 301 || status == 302 || status == 303 || status == 307)) {
                        // Assumes only one occurrence of "Location"
                        int pos1 = responseHeaders.indexOf("Location:") + 10;
                        int pos2 = responseHeaders.indexOf("\n", pos1);

                        if (pos2 > pos1) {
                            String newLocation = responseHeaders.substring(pos1, pos2);
                            // Handle newLocation whether it's absolute or relative
                            URL baseUrl = new URL(address);
                            URL newUrl = new URL(baseUrl, newLocation);
                            String transformedNewLocation = newUrl.toString();

                            if (transformedNewLocation != address) {
                                address = transformedNewLocation;
                                // Clear responseHeaders before next iteration
                                responseHeaders.delete(0, responseHeaders.length());
                                continue;
                            }
                        }
                    }

                    return httpStream;
                } catch (Throwable e) {
                    connection.disconnect();
                }
            }
        } catch (Throwable e) {
        }

        return null;
    }
}