Example usage for java.lang StringBuffer substring

List of usage examples for java.lang StringBuffer substring

Introduction

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

Prototype

@Override
public synchronized String substring(int start, int end) 

Source Link

Usage

From source file:org.etudes.component.app.melete.ModuleDB.java

private String getDelSectionIds(Session session, int moduleId) {
    StringBuffer delIds = null;
    String a = null;/*  w  w  w .ja v a  2  s.  c  om*/
    String selectDelsecStr = "select sec.sectionId from Section sec where sec.deleteFlag=1 and sec.moduleId=:moduleId";
    List<String> deletedSections = session.createQuery(selectDelsecStr).setInteger("moduleId", moduleId).list();
    if (deletedSections != null) {
        delIds = new StringBuffer("(");
        for (Iterator i = deletedSections.iterator(); i.hasNext();) {
            Object obj = i.next();
            delIds.append(obj + ",");
        }
    }
    if (delIds != null && delIds.lastIndexOf(",") != -1)
        a = delIds.substring(0, delIds.lastIndexOf(",")) + " )";

    return a;
}

From source file:azkaban.webapp.servlet.ProjectManagerServlet.java

private void ajaxHandleUpload(HttpServletRequest req, Map<String, String> ret, Map<String, Object> multipart,
        Session session) throws ServletException, IOException {
    User user = session.getUser();/*  w w w .  j av  a2s.c om*/
    String projectName = (String) multipart.get("project");
    Project project = projectManager.getProject(projectName);
    String autoFix = (String) multipart.get("fix");
    Props props = new Props();
    if (autoFix != null && autoFix.equals("off")) {
        props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "false");
    } else {
        props.put(ValidatorConfigs.CUSTOM_AUTO_FIX_FLAG_PARAM, "true");
    }

    if (projectName == null || projectName.isEmpty()) {
        ret.put("error", "No project name found.");
    } else if (project == null) {
        ret.put("error", "Installation Failed. Project '" + projectName + "' doesn't exist.");
    } else if (!hasPermission(project, user, Type.WRITE)) {
        ret.put("error", "Installation Failed. User '" + user.getUserId() + "' does not have write access.");
    } else {
        ret.put("projectId", String.valueOf(project.getId()));

        FileItem item = (FileItem) multipart.get("file");
        String name = item.getName();
        String type = null;

        final String contentType = item.getContentType();
        if (contentType != null && (contentType.startsWith(APPLICATION_ZIP_MIME_TYPE)
                || contentType.startsWith("application/x-zip-compressed")
                || contentType.startsWith("application/octet-stream"))) {
            type = "zip";
        } else {
            item.delete();
            ret.put("error", "File type " + contentType + " unrecognized.");

            return;
        }

        File tempDir = Utils.createTempDir();
        OutputStream out = null;
        try {
            logger.info("Uploading file " + name);
            File archiveFile = new File(tempDir, name);
            out = new BufferedOutputStream(new FileOutputStream(archiveFile));
            IOUtils.copy(item.getInputStream(), out);
            out.close();

            Map<String, ValidationReport> reports = projectManager.uploadProject(project, archiveFile, type,
                    user, props);
            StringBuffer errorMsgs = new StringBuffer();
            StringBuffer warnMsgs = new StringBuffer();
            for (Entry<String, ValidationReport> reportEntry : reports.entrySet()) {
                ValidationReport report = reportEntry.getValue();
                if (!report.getInfoMsgs().isEmpty()) {
                    for (String msg : report.getInfoMsgs()) {
                        switch (ValidationReport.getInfoMsgLevel(msg)) {
                        case ERROR:
                            errorMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>");
                            break;
                        case WARN:
                            warnMsgs.append(ValidationReport.getInfoMsg(msg) + "<br/>");
                            break;
                        default:
                            break;
                        }
                    }
                }
                if (!report.getErrorMsgs().isEmpty()) {
                    errorMsgs.append("Validator " + reportEntry.getKey() + " reports errors:<ul>");
                    for (String msg : report.getErrorMsgs()) {
                        errorMsgs.append("<li>" + msg + "</li>");
                    }
                    errorMsgs.append("</ul>");
                }
                if (!report.getWarningMsgs().isEmpty()) {
                    warnMsgs.append("Validator " + reportEntry.getKey() + " reports warnings:<ul>");
                    for (String msg : report.getWarningMsgs()) {
                        warnMsgs.append("<li>" + msg + "</li>");
                    }
                    warnMsgs.append("</ul>");
                }
            }
            if (errorMsgs.length() > 0) {
                // If putting more than 4000 characters in the cookie, the entire
                // message
                // will somehow get discarded.
                ret.put("error",
                        errorMsgs.length() > 4000 ? errorMsgs.substring(0, 4000) : errorMsgs.toString());
            }
            if (warnMsgs.length() > 0) {
                ret.put("warn", warnMsgs.length() > 4000 ? warnMsgs.substring(0, 4000) : warnMsgs.toString());
            }
        } catch (Exception e) {
            logger.info("Installation Failed.", e);
            String error = e.getMessage();
            if (error.length() > 512) {
                error = error.substring(0, 512) + "<br>Too many errors to display.<br>";
            }
            ret.put("error", "Installation Failed.<br>" + error);
        } finally {
            if (tempDir.exists()) {
                FileUtils.deleteDirectory(tempDir);
            }
            if (out != null) {
                out.close();
            }
        }

        ret.put("version", String.valueOf(project.getVersion()));
    }
}

From source file:org.zkoss.poi.ss.format.CellNumberFormatter.java

private void writeInteger(StringBuffer result, StringBuffer output, List<Special> numSpecials,
        Set<StringMod> mods, boolean showCommas, boolean fraction) {//20100924, henrichen@zkoss.org: fraction has special treatment about zero
    //20100914, henrichen@zkoss.org: repect the current locale
    final char comma = Formatters.getGroupingSeparator(locale);
    final String commaStr = "" + comma;
    final String dot = "" + Formatters.getDecimalSeparator(locale);
    int pos = result.indexOf(dot) - 1;
    if (pos < 0) {
        if (exponent != null && numSpecials == integerSpecials)
            pos = result.indexOf("E") - 1;
        else/*from w  w w . j  a v a2 s. c  o  m*/
            pos = result.length() - 1;
    }

    int strip;
    for (strip = 0; strip < pos; strip++) {
        char resultCh = result.charAt(strip);
        if (resultCh != '0' && resultCh != comma)
            break;
    }
    //20100924, henrichen@zkoss.org: handle all zero case
    final char posCh = !fraction && strip == pos && pos >= 0 ? result.charAt(pos) : '\000';
    final boolean allZeros = posCh == '0' || posCh == comma;

    ListIterator<Special> it = numSpecials.listIterator(numSpecials.size());
    boolean followWithComma = false;
    Special lastOutputIntegerDigit = null;
    int digit = 0;
    while (it.hasPrevious()) {
        char resultCh;
        if (pos >= 0)
            resultCh = result.charAt(pos);
        else {
            // If result is shorter than field, pretend there are leading zeros
            resultCh = '0';
        }
        Special s = it.previous();
        followWithComma = showCommas && digit > 0 && digit % 3 == 0;
        boolean zeroStrip = false;
        if (resultCh != '0' || s.ch == '0' || s.ch == '?' || pos >= strip) {
            zeroStrip = s.ch == '?' && (pos < strip || allZeros); //20100924, henrichen@zkoss.org: handle all zero case
            output.setCharAt(s.pos, (zeroStrip ? ' ' : resultCh));
            lastOutputIntegerDigit = s;
        }
        if (followWithComma) {
            //20100914, henrichen@zkoss.org: repect the current locale
            //mods.add(insertMod(s, zeroStrip ? " " : ",", StringMod.AFTER));
            mods.add(insertMod(s, zeroStrip ? " " : commaStr, StringMod.AFTER));
            followWithComma = false;
        }
        digit++;
        --pos;
    }
    StringBuffer extraLeadingDigits = new StringBuffer();
    if (pos >= 0) {
        // We ran out of places to put digits before we ran out of digits; put this aside so we can add it later
        ++pos; // pos was decremented at the end of the loop above when the iterator was at its end
        extraLeadingDigits = new StringBuffer(result.substring(0, pos));
        if (showCommas) {
            while (pos > 0) {
                if (digit > 0 && digit % 3 == 0)
                    //20100914, henrichen@zkoss.org: repect the current locale
                    //extraLeadingDigits.insert(pos, ',');
                    extraLeadingDigits.insert(pos, comma);
                digit++;
                --pos;
            }
        }
        mods.add(insertMod(lastOutputIntegerDigit, extraLeadingDigits, StringMod.BEFORE));
    }
}

From source file:org.etudes.mneme.impl.AttachmentServiceImpl.java

/**
 * Creates a comma delimited string of answers
 * @param answers Array of answers//from  w w w.j av a 2s  .com
 * @return Comma delimited string of answers
 */
private String getCommaAnswers(String[] answers) {
    if (answers.length == 0)
        return null;
    StringBuffer commaAnswers = new StringBuffer();
    for (int i = 0; i < answers.length; i++) {
        if (answers[i] != null && answers[i].trim().length() > 0) {
            commaAnswers.append(answers[i].trim());
            commaAnswers.append(", ");
        }
    }
    if (commaAnswers.length() >= 3)
        return commaAnswers.substring(0, commaAnswers.length() - 2);
    return null;
}

From source file:org.egov.egf.web.actions.voucher.CommonAction.java

private String getCommaSeperatedListForDesignationNameAndFunctionaryName(final String designationName,
        final String functionaryName) {
    final String qrySQL = "select pos_id from eg_eis_employeeinfo empinfo, eg_designation desg, functionary func   "
            + " where empinfo.functionary_id=func.id and empinfo.DESIGNATIONID=desg.DESIGNATIONID "
            + " and empinfo.isactive=true   " + " and desg.DESIGNATION_NAME like '" + designationName
            + "' and func.NAME like '" + functionaryName + "' ";
    final Query query = persistenceService.getSession().createSQLQuery(qrySQL);
    final List<BigDecimal> result = query.list();
    if (result == null || result.isEmpty())
        throw new ValidationException("",
                "No employee with functionary -" + functionaryName + " and designation - " + designationName);
    final StringBuffer returnListSB = new StringBuffer();
    String commaSeperatedList = "";
    for (final BigDecimal posId : result)
        returnListSB.append(posId.toString() + ",");
    commaSeperatedList = returnListSB.substring(0, returnListSB.length() - 1);
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Commo seperated  list - " + commaSeperatedList);
    return commaSeperatedList;
}

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   ww  w .  java2 s. c  om
        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.stratelia.webactiv.kmelia.servlets.KmeliaRequestRouter.java

/**
 * This method has to be implemented by the component request rooter it has to compute a
 * destination page//  w  w w  .  j  a v a  2s.  co  m
 *
 *
 * @param function The entering request function ( : "Main.jsp")
 * @param kmelia The component Session Control, build and initialised.
 * @param request The entering request. The request rooter need it to get parameters
 * @return The complete destination URL for a forward (ex :
 * "/almanach/jsp/almanach.jsp?flag=user")
 */
@Override
public String getDestination(String function, KmeliaSessionController kmelia, HttpRequest request) {
    SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
            "function = " + function);
    String destination = "";
    String rootDestination = "/kmelia/jsp/";
    boolean profileError = false;
    boolean kmaxMode = false;
    boolean toolboxMode;
    try {
        SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                "getComponentRootName() = " + kmelia.getComponentRootName());
        if ("kmax".equals(kmelia.getComponentRootName())) {
            kmaxMode = true;
            kmelia.isKmaxMode = true;
        }
        request.setAttribute("KmaxMode", kmaxMode);

        toolboxMode = KmeliaHelper.isToolbox(kmelia.getComponentId());

        // Set language choosen by the user
        setLanguage(request, kmelia);

        if (function.startsWith("Main")) {
            resetWizard(kmelia);
            if (kmaxMode) {
                destination = getDestination("KmaxMain", kmelia, request);
                kmelia.setSessionTopic(null);
                kmelia.setSessionPath("");
            } else {
                destination = getDestination("GoToTopic", kmelia, request);
            }
        } else if (function.startsWith("validateClassification")) {
            String[] publicationIds = request.getParameterValues("pubid");
            Collection<KmeliaPublication> publications = kmelia
                    .getPublications(asPks(kmelia.getComponentId(), publicationIds));
            request.setAttribute("Context", URLManager.getApplicationURL());
            request.setAttribute("PublicationsDetails", publications);
            destination = rootDestination + "validateImportedFilesClassification.jsp";
        } else if (function.startsWith("portlet")) {
            kmelia.setSessionPublication(null);
            String flag = kmelia.getUserRoleLevel();
            if (kmaxMode) {
                destination = rootDestination + "kmax_portlet.jsp?Profile=" + flag;
            } else {
                destination = rootDestination + "portlet.jsp?Profile=user";
            }
        } else if (function.equals("FlushTrashCan")) {
            kmelia.flushTrashCan();
            if (kmaxMode) {
                destination = getDestination("KmaxMain", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("GoToDirectory")) {
            String topicId = request.getParameter("Id");

            String path;
            if (StringUtil.isDefined(topicId)) {
                NodeDetail topic = kmelia.getNodeHeader(topicId);
                path = topic.getPath();
            } else {
                path = request.getParameter("Path");
            }

            FileFolder folder = new FileFolder(path);
            request.setAttribute("Directory", folder);
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());

            destination = rootDestination + "repository.jsp";
        } else if ("GoToTopic".equals(function)) {
            String topicId = (String) request.getAttribute("Id");
            if (!StringUtil.isDefined(topicId)) {
                topicId = request.getParameter("Id");
                if (!StringUtil.isDefined(topicId)) {
                    topicId = NodePK.ROOT_NODE_ID;
                }
            }
            kmelia.setCurrentFolderId(topicId, true);
            resetWizard(kmelia);
            request.setAttribute("CurrentFolderId", topicId);
            request.setAttribute("DisplayNBPublis", kmelia.displayNbPublis());
            request.setAttribute("DisplaySearch", kmelia.isSearchOnTopicsEnabled());

            // rechercher si le theme a un descripteur
            request.setAttribute("HaveDescriptor", kmelia.isTopicHaveUpdateChainDescriptor());

            request.setAttribute("Profile", kmelia.getUserTopicProfile(topicId));
            request.setAttribute("IsGuest", kmelia.getUserDetail().isAccessGuest());
            request.setAttribute("RightsOnTopicsEnabled", kmelia.isRightsOnTopicsEnabled());
            request.setAttribute("WysiwygDescription", kmelia.getWysiwygOnTopic());
            request.setAttribute("PageIndex", kmelia.getIndexOfFirstPubToDisplay());

            if (kmelia.isTreeviewUsed()) {
                destination = rootDestination + "treeview.jsp";
            } else if (kmelia.isTreeStructure()) {
                destination = rootDestination + "oneLevel.jsp";
            } else {
                destination = rootDestination + "simpleListOfPublications.jsp";
            }
        } else if ("GoToCurrentTopic".equals(function)) {
            if (!NodePK.ROOT_NODE_ID.equals(kmelia.getCurrentFolderId())) {
                request.setAttribute("Id", kmelia.getCurrentFolderId());
                destination = getDestination("GoToTopic", kmelia, request);
            } else {
                destination = getDestination("Main", kmelia, request);
            }
        } else if (function.equals("GoToBasket")) {
            destination = rootDestination + "basket.jsp";
        } else if (function.equals("ViewPublicationsToValidate")) {
            destination = rootDestination + "publicationsToValidate.jsp";
        } else if ("GoBackToResults".equals(function)) {
            request.setAttribute("SearchContext", kmelia.getSearchContext());
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.startsWith("searchResult")) {
            resetWizard(kmelia);
            String id = request.getParameter("Id");
            String type = request.getParameter("Type");
            String fileAlreadyOpened = request.getParameter("FileOpened");
            String from = request.getParameter("From");
            if ("Search".equals(from)) {
                // identify clearly access from global search
                // because same URL is used from portlet, permalink...
                request.setAttribute("SearchScope", SearchContext.GLOBAL);
            }

            if (type != null && ("Publication".equals(type)
                    || "com.stratelia.webactiv.calendar.backbone.TodoDetail".equals(type)
                    || "Attachment".equals(type) || "Document".equals(type) || type.startsWith("Comment"))) {
                KmeliaSecurity security = new KmeliaSecurity(kmelia.getOrganisationController());
                try {
                    boolean accessAuthorized = security.isAccessAuthorized(kmelia.getComponentId(),
                            kmelia.getUserId(), id, "Publication");
                    if (accessAuthorized) {
                        processPath(kmelia, id);
                        if ("Attachment".equals(type)) {
                            String attachmentId = request.getParameter("AttachmentId");
                            request.setAttribute("AttachmentId", attachmentId);
                            destination = getDestination("ViewPublication", kmelia, request);
                        } else if ("Document".equals(type)) {
                            String documentId = request.getParameter("DocumentId");
                            request.setAttribute("DocumentId", documentId);
                            destination = getDestination("ViewPublication", kmelia, request);
                        } else {
                            if (kmaxMode) {
                                request.setAttribute("FileAlreadyOpened", fileAlreadyOpened);
                                destination = getDestination("ViewPublication", kmelia, request);
                            } else if (toolboxMode) {
                                // we have to find which page contains the right publication
                                List<KmeliaPublication> publications = kmelia.getSessionPublicationsList();
                                int pubIndex = -1;
                                for (int p = 0; p < publications.size() && pubIndex == -1; p++) {
                                    KmeliaPublication publication = publications.get(p);
                                    if (id.equals(publication.getDetail().getPK().getId())) {
                                        pubIndex = p;
                                    }
                                }
                                int nbPubliPerPage = kmelia.getNbPublicationsPerPage();
                                if (nbPubliPerPage == 0) {
                                    nbPubliPerPage = pubIndex;
                                }
                                int ipage = pubIndex / nbPubliPerPage;
                                kmelia.setIndexOfFirstPubToDisplay(Integer.toString(ipage * nbPubliPerPage));
                                request.setAttribute("PubIdToHighlight", id);
                                request.setAttribute("Id", kmelia.getCurrentFolderId());
                                destination = getDestination("GoToTopic", kmelia, request);
                            } else {
                                request.setAttribute("FileAlreadyOpened", fileAlreadyOpened);
                                destination = getDestination("ViewPublication", kmelia, request);
                            }
                        }
                    } else {
                        destination = "/admin/jsp/accessForbidden.jsp";
                    }
                } catch (Exception e) {
                    SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()",
                            "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e);
                    destination = getDocumentNotFoundDestination(kmelia, request);
                }
            } else if ("Node".equals(type)) {
                if (kmaxMode) {
                    // Simuler l'action d'un utilisateur ayant slectionn la valeur id d'un axe
                    // SearchCombination est un chemin /0/4/i
                    NodeDetail node = kmelia.getNodeHeader(id);
                    String path = node.getPath() + id;
                    request.setAttribute("SearchCombination", path);
                    destination = getDestination("KmaxSearch", kmelia, request);
                } else {
                    try {
                        request.setAttribute("Id", id);
                        destination = getDestination("GoToTopic", kmelia, request);
                    } catch (Exception e) {
                        SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()",
                                "root.MSG_GEN_PARAM_VALUE", "Document Not Found = " + e.getMessage(), e);
                        destination = getDocumentNotFoundDestination(kmelia, request);
                    }
                }
            } else if ("Wysiwyg".equals(type)) {
                if (id.startsWith("Node")) {
                    id = id.substring("Node_".length(), id.length());
                    request.setAttribute("Id", id);
                    destination = getDestination("GoToTopic", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            } else {
                request.setAttribute("Id", NodePK.ROOT_NODE_ID);
                destination = getDestination("GoToTopic", kmelia, request);
            }
        } else if (function.startsWith("GoToFilesTab")) {
            String id = request.getParameter("Id");
            try {
                processPath(kmelia, id);
                if (toolboxMode) {
                    KmeliaPublication kmeliaPublication = kmelia.getPublication(id);
                    kmelia.setSessionPublication(kmeliaPublication);
                    kmelia.setSessionOwner(true);
                    destination = getDestination("ViewAttachments", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            } catch (Exception e) {
                SilverTrace.error("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                        "Document Not Found = " + e.getMessage(), e);
                destination = getDocumentNotFoundDestination(kmelia, request);
            }
        } else if ("ToUpdatePublicationHeader".equals(function)) {
            request.setAttribute("Action", "UpdateView");
            destination = getDestination("publicationManager.jsp", kmelia, request);
        } else if ("publicationManager.jsp".equals(function)) {
            String action = (String) request.getAttribute("Action");
            if ("UpdateView".equals(action)) {
                request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
                request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());
                request.setAttribute("Publication", kmelia.getSessionPubliOrClone());
            } else if ("New".equals(action)) {
                request.setAttribute("TaxonomyOK", true);
                request.setAttribute("ValidatorsOK", true);
            }

            request.setAttribute("Wizard", kmelia.getWizard());
            request.setAttribute("Path", kmelia.getTopicPath(kmelia.getCurrentFolderId()));
            request.setAttribute("Profile", kmelia.getProfile());

            destination = rootDestination + "publicationManager.jsp";
            // thumbnail error for front explication
            if (request.getParameter("errorThumbnail") != null) {
                destination = destination + "&resultThumbnail=" + request.getParameter("errorThumbnail");
            }
        } else if (function.equals("ToAddTopic")) {
            String topicId = request.getParameter("Id");
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(topicId))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                String isLink = request.getParameter("IsLink");
                if (StringUtil.isDefined(isLink)) {
                    request.setAttribute("IsLink", Boolean.TRUE);
                }

                List<NodeDetail> path = kmelia.getTopicPath(topicId);
                request.setAttribute("Path", kmelia.displayPath(path, false, 3));
                request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3));
                request.setAttribute("Translation", kmelia.getCurrentLanguage());
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());
                request.setAttribute("Parent", kmelia.getNodeHeader(topicId));

                if (kmelia.isRightsOnTopicsEnabled()) {
                    request.setAttribute("Profiles", kmelia.getTopicProfiles());

                    // Rights of the component
                    request.setAttribute("RightsDependsOn", "ThisComponent");
                }

                destination = rootDestination + "addTopic.jsp";
            }
        } else if ("ToUpdateTopic".equals(function)) {
            String id = request.getParameter("Id");
            NodeDetail node = kmelia.getSubTopicDetail(id);
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))
                    && !SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(node.getFatherPK().getId()))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                request.setAttribute("NodeDetail", node);

                List<NodeDetail> path = kmelia.getTopicPath(id);
                request.setAttribute("Path", kmelia.displayPath(path, false, 3));
                request.setAttribute("PathLinked", kmelia.displayPath(path, true, 3));
                request.setAttribute("Translation", kmelia.getCurrentLanguage());
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

                if (kmelia.isRightsOnTopicsEnabled()) {
                    request.setAttribute("Profiles", kmelia.getTopicProfiles(id));

                    if (node.haveInheritedRights()) {
                        request.setAttribute("RightsDependsOn", "AnotherTopic");
                    } else if (node.haveLocalRights()) {
                        request.setAttribute("RightsDependsOn", "ThisTopic");
                    } else {
                        // Rights of the component
                        request.setAttribute("RightsDependsOn", "ThisComponent");
                    }
                }

                destination = rootDestination + "updateTopicNew.jsp";
            }
        } else if (function.equals("AddTopic")) {
            String name = request.getParameter("Name");
            String description = request.getParameter("Description");
            String alertType = request.getParameter("AlertType");
            if (!StringUtil.isDefined(alertType)) {
                alertType = "None";
            }
            String rightsUsed = request.getParameter("RightsUsed");
            String path = request.getParameter("Path");
            String parentId = request.getParameter("ParentId");

            NodeDetail topic = new NodeDetail("-1", name, description, null, null, null, "0", "X");
            I18NHelper.setI18NInfo(topic, request);

            if (StringUtil.isDefined(path)) {
                topic.setType(NodeDetail.FILE_LINK_TYPE);
                topic.setPath(path);
            }

            int rightsDependsOn = -1;
            if (StringUtil.isDefined(rightsUsed)) {
                if ("father".equalsIgnoreCase(rightsUsed)) {
                    NodeDetail father = kmelia.getCurrentFolder();
                    rightsDependsOn = father.getRightsDependsOn();
                } else {
                    rightsDependsOn = 0;
                }
                topic.setRightsDependsOn(rightsDependsOn);
            }
            NodePK nodePK = kmelia.addSubTopic(topic, alertType, parentId);
            if (kmelia.isRightsOnTopicsEnabled()) {
                if (rightsDependsOn == 0) {
                    request.setAttribute("NodeId", nodePK.getId());
                    destination = getDestination("ViewTopicProfiles", kmelia, request);
                } else {
                    destination = getDestination("GoToCurrentTopic", kmelia, request);
                }
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if ("UpdateTopic".equals(function)) {
            String name = request.getParameter("Name");
            String description = request.getParameter("Description");
            String alertType = request.getParameter("AlertType");
            if (!StringUtil.isDefined(alertType)) {
                alertType = "None";
            }
            String id = request.getParameter("ChildId");
            String path = request.getParameter("Path");
            NodeDetail topic = new NodeDetail(id, name, description, null, null, null, "0", "X");
            I18NHelper.setI18NInfo(topic, request);
            if (StringUtil.isDefined(path)) {
                topic.setType(NodeDetail.FILE_LINK_TYPE);
                topic.setPath(path);
            }
            boolean goToProfilesDefinition = false;
            if (kmelia.isRightsOnTopicsEnabled()) {
                int rightsUsed = Integer.parseInt(request.getParameter("RightsUsed"));
                topic.setRightsDependsOn(rightsUsed);

                // process destination
                NodeDetail oldTopic = kmelia.getNodeHeader(id);
                if (oldTopic.getRightsDependsOn() != rightsUsed) {
                    // rights dependency have changed
                    if (rightsUsed != -1) {
                        // folder uses its own rights
                        goToProfilesDefinition = true;
                    }
                }
            }
            kmelia.updateTopicHeader(topic, alertType);

            if (goToProfilesDefinition) {
                request.setAttribute("NodeId", id);
                destination = getDestination("ViewTopicProfiles", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("DeleteTopic")) {
            String id = request.getParameter("Id");
            kmelia.deleteTopic(id);
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ViewClone")) {
            PublicationDetail pubDetail = kmelia.getSessionPublication().getDetail();

            // Reload clone and put it into session
            String cloneId = pubDetail.getCloneId();
            KmeliaPublication kmeliaPublication = kmelia.getPublication(cloneId);
            kmelia.setSessionClone(kmeliaPublication);

            request.setAttribute("Publication", kmeliaPublication);
            request.setAttribute("Profile", kmelia.getProfile());
            request.setAttribute("VisiblePublicationId", pubDetail.getPK().getId());
            request.setAttribute("UserCanValidate", kmelia.isUserCanValidatePublication());
            request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
            request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());

            putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request);

            // Attachments area must be displayed or not ?
            request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled());

            destination = rootDestination + "clone.jsp";
        } else if ("ViewPublication".equals(function)) {
            String id = request.getParameter("PubId");
            if (!StringUtil.isDefined(id)) {
                id = request.getParameter("Id");
                if (!StringUtil.isDefined(id)) {
                    id = (String) request.getAttribute("PubId");
                }
            }

            if (!kmaxMode) {
                boolean checkPath = StringUtil.getBooleanValue(request.getParameter("CheckPath"));
                if (checkPath || KmeliaHelper.isToValidateFolder(kmelia.getCurrentFolderId())) {
                    processPath(kmelia, id);
                } else {
                    processPath(kmelia, null);
                }
            }

            // view publication from global search ?
            Integer searchScope = (Integer) request.getAttribute("SearchScope");
            if (searchScope == null) {
                if (kmelia.getSearchContext() != null) {
                    request.setAttribute("SearchScope", SearchContext.LOCAL);
                } else {
                    request.setAttribute("SearchScope", SearchContext.NONE);
                }
            }

            KmeliaPublication kmeliaPublication;
            if (StringUtil.isDefined(id)) {
                kmeliaPublication = kmelia.getPublication(id, true);
                kmelia.setSessionPublication(kmeliaPublication);

                PublicationDetail pubDetail = kmeliaPublication.getDetail();
                if (pubDetail.haveGotClone()) {
                    KmeliaPublication clone = kmelia.getPublication(pubDetail.getCloneId());
                    kmelia.setSessionClone(clone);
                }
            } else {
                kmeliaPublication = kmelia.getSessionPublication();
                id = kmeliaPublication.getDetail().getPK().getId();
            }
            if (toolboxMode) {
                destination = getDestination("ToUpdatePublicationHeader", kmelia, request);
            } else {
                List<String> publicationLanguages = kmelia.getPublicationLanguages(); // languages of
                // publication
                // header and attachments
                if (publicationLanguages.contains(kmelia.getCurrentLanguage())) {
                    request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage());
                } else {
                    request.setAttribute("ContentLanguage",
                            checkLanguage(kmelia, kmeliaPublication.getDetail()));
                }
                request.setAttribute("Languages", publicationLanguages);

                // see also management
                Collection<ForeignPK> links = kmeliaPublication.getCompleteDetail().getLinkList();
                HashSet<String> linkedList = new HashSet<String>(links.size());
                for (ForeignPK link : links) {
                    linkedList.add(link.getId() + "-" + link.getInstanceId());
                }
                // put into session the current list of selected publications (see also)
                request.getSession().setAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY, linkedList);

                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("PubId", id);
                request.setAttribute("UserCanValidate",
                        kmelia.isUserCanValidatePublication() && kmelia.getSessionClone() == null);
                request.setAttribute("ValidationStep", kmelia.getValidationStep());
                request.setAttribute("ValidationType", kmelia.getValidationType());

                // check if user is writer with approval right (versioning case)
                request.setAttribute("WriterApproval", kmelia.isWriterApproval(id));
                request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

                // check is requested publication is an alias
                checkAlias(kmelia, kmeliaPublication);

                if (kmeliaPublication.isAlias()) {
                    request.setAttribute("Profile", "user");
                    request.setAttribute("TaxonomyOK", false);
                    request.setAttribute("ValidatorsOK", false);
                    request.setAttribute("IsAlias", "1");
                } else {
                    request.setAttribute("Profile", kmelia.getProfile());
                    request.setAttribute("TaxonomyOK", kmelia.isPublicationTaxonomyOK());
                    request.setAttribute("ValidatorsOK", kmelia.isPublicationValidatorsOK());
                }

                request.setAttribute("Wizard", kmelia.getWizard());

                request.setAttribute("Rang", kmelia.getRang());
                if (kmelia.getSessionPublicationsList() != null) {
                    request.setAttribute("NbPublis", kmelia.getSessionPublicationsList().size());
                } else {
                    request.setAttribute("NbPublis", 1);
                }
                putXMLDisplayerIntoRequest(kmeliaPublication.getDetail(), kmelia, request);
                String fileAlreadyOpened = (String) request.getAttribute("FileAlreadyOpened");
                boolean alreadyOpened = "1".equals(fileAlreadyOpened);
                String attachmentId = (String) request.getAttribute("AttachmentId");
                String documentId = (String) request.getAttribute("DocumentId");
                if (!alreadyOpened && kmelia.openSingleAttachmentAutomatically()
                        && !kmelia.isCurrentPublicationHaveContent()) {
                    request.setAttribute("SingleAttachmentURL",
                            kmelia.getFirstAttachmentURLOfCurrentPublication());
                } else if (!alreadyOpened && attachmentId != null) {
                    request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(attachmentId));
                } else if (!alreadyOpened && documentId != null) {
                    request.setAttribute("SingleAttachmentURL", kmelia.getAttachmentURL(documentId));
                }

                // Attachments area must be displayed or not ?
                request.setAttribute("AttachmentsEnabled", kmelia.isAttachmentsEnabled());

                // option Actualits dcentralises
                request.setAttribute("NewsManage", kmelia.isNewsManage());
                if (kmelia.isNewsManage()) {
                    request.setAttribute("DelegatedNews", kmelia.getDelegatedNews(id));
                    request.setAttribute("IsBasket", NodePK.BIN_NODE_ID.equals(kmelia.getCurrentFolderId()));
                }

                request.setAttribute("LastAccess", kmelia.getLastAccess(kmeliaPublication.getPk()));
                request.setAttribute("PublicationRatingsAllowed", kmelia.isPublicationRatingAllowed());

                destination = rootDestination + "publication.jsp";
            }
        } else if (function.equals("PreviousPublication")) {
            // rcupration de la publication prcdente
            String pubId = kmelia.getPrevious();
            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("NextPublication")) {
            // rcupration de la publication suivante
            String pubId = kmelia.getNext();
            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.startsWith("copy")) {
            String objectType = request.getParameter("Object");
            String objectId = request.getParameter("Id");
            if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) {
                kmelia.copyTopic(objectId);
            } else {
                kmelia.copyPublication(objectId);
            }

            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null)
                    + "Idle.jsp?message=REFRESHCLIPBOARD";
        } else if (function.startsWith("cut")) {
            String objectType = request.getParameter("Object");
            String objectId = request.getParameter("Id");
            if (StringUtil.isDefined(objectType) && "Node".equalsIgnoreCase(objectType)) {
                kmelia.cutTopic(objectId);
            } else {
                kmelia.cutPublication(objectId);
            }

            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null)
                    + "Idle.jsp?message=REFRESHCLIPBOARD";
        } else if (function.startsWith("paste")) {
            kmelia.paste();
            destination = URLManager.getURL(URLManager.CMP_CLIPBOARD, null, null) + "Idle.jsp";
        } else if (function.startsWith("ToAlertUserAttachment")) { // utilisation de alertUser et
            // alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserAttachment: function = " + function + " spaceId=" + kmelia.getSpaceId()
                            + " componentId=" + kmelia.getComponentId());
            try {
                String attachmentId = request.getParameter("AttachmentOrDocumentId");
                destination = kmelia.initAlertUserAttachment(attachmentId);
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserAttachment: function = " + function + "=> destination=" + destination);
        } else if (function.startsWith("ToAlertUserDocument")) { // utilisation de alertUser et
            // alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserDocument: function = " + function + " spaceId=" + kmelia.getSpaceId()
                            + " componentId=" + kmelia.getComponentId());
            try {
                String documentId = request.getParameter("AttachmentOrDocumentId");
                destination = kmelia.initAlertUserAttachment(documentId);
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUserDocument: function = " + function + "=> destination=" + destination);
        } else if (function.startsWith("ToAlertUser")) { // utilisation de alertUser et alertUserPeas
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUser: function = " + function + " spaceId=" + kmelia.getSpaceId() + " componentId="
                            + kmelia.getComponentId());
            try {
                destination = kmelia.initAlertUser();
            } catch (Exception e) {
                SilverTrace.warn("kmelia", "KmeliaRequestRooter.getDestination()", "root.EX_USERPANEL_FAILED",
                        "function = " + function, e);
            }
            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "ToAlertUser: function = " + function + "=> destination=" + destination);
        } else if (function.equals("ReadingControl")) {
            PublicationDetail publication = kmelia.getSessionPublication().getDetail();
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("Publication", publication);
            request.setAttribute("UserIds", kmelia.getUserIdsOfTopic());

            // paramtre du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            destination = rootDestination + "readingControlManager.jsp";
        } else if (function.startsWith("ViewAttachments")) {
            String flag = kmelia.getProfile();

            // Versioning is out of "Always visible publication" mode
            if (kmelia.isCloneNeeded() && !kmelia.isVersionControlled()) {
                kmelia.clonePublication();
            }

            // put current publication
            if (!kmelia.isVersionControlled()) {
                request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail());
            } else {
                request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail());
            }
            // Paramtres du wizard
            setWizardParams(request, kmelia);

            // Paramtres de i18n
            List<String> attachmentLanguages = kmelia.getAttachmentLanguages();
            if (attachmentLanguages.contains(kmelia.getCurrentLanguage())) {
                request.setAttribute("Language", kmelia.getCurrentLanguage());
            } else {
                request.setAttribute("Language", checkLanguage(kmelia));
            }
            request.setAttribute("Languages", attachmentLanguages);

            request.setAttribute("XmlFormForFiles", kmelia.getXmlFormForFiles());

            destination = rootDestination + "attachmentManager.jsp?profile=" + flag;
        } else if (function.equals("DeletePublication")) {
            String pubId = request.getParameter("PubId");
            kmelia.deletePublication(pubId);

            if (kmaxMode) {
                destination = getDestination("Main", kmelia, request);
            } else {
                destination = getDestination("GoToCurrentTopic", kmelia, request);
            }
        } else if (function.equals("DeleteClone")) {
            kmelia.deleteClone();

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ViewValidationSteps")) {
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("Publication", kmelia.getSessionPubliOrClone().getDetail());
            request.setAttribute("ValidationSteps", kmelia.getValidationSteps());

            request.setAttribute("Role", kmelia.getProfile());

            destination = rootDestination + "validationSteps.jsp";
        } else if ("ValidatePublication".equals(function)) {
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();

            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "function = " + function + " pubId=" + pubId);

            boolean validationComplete = kmelia.validatePublication(pubId);
            if (validationComplete) {
                request.setAttribute("Action", "ValidationComplete");
                destination = getDestination("ViewPublication", kmelia, request);
            } else {
                request.setAttribute("Action", "ValidationInProgress");
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("ForceValidatePublication")) {
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();
            kmelia.forcePublicationValidation(pubId);
            request.setAttribute("Action", "ValidationComplete");

            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } else if ("Unvalidate".equals(function)) {
            String motive = request.getParameter("Motive");
            String pubId = kmelia.getSessionPublication().getDetail().getPK().getId();

            SilverTrace.debug("kmelia", "KmeliaRequestRooter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "function = " + function + " pubId=" + pubId);

            kmelia.unvalidatePublication(pubId, motive);

            request.setAttribute("Action", "Unvalidate");

            if (kmelia.getSessionClone() != null) {
                destination = getDestination("ViewClone", kmelia, request);
            } else {
                destination = getDestination("ViewPublication", kmelia, request);
            }
        } else if (function.equals("WantToSuspendPubli")) {
            String pubId = request.getParameter("PubId");

            PublicationDetail pubDetail = kmelia.getPublicationDetail(pubId);

            request.setAttribute("PublicationToSuspend", pubDetail);

            destination = rootDestination + "defermentMotive.jsp";
        } else if (function.equals("SuspendPublication")) {
            String motive = request.getParameter("Motive");
            String pubId = request.getParameter("PubId");

            kmelia.suspendPublication(pubId, motive);

            request.setAttribute("Action", "Suspend");

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("DraftIn")) {
            kmelia.draftInPublication();
            if (kmelia.getSessionClone() != null) {
                // draft have generate a clone
                destination = getDestination("ViewClone", kmelia, request);
            } else {
                String from = request.getParameter("From");
                if (StringUtil.isDefined(from)) {
                    destination = getDestination(from, kmelia, request);
                } else {
                    destination = getDestination("ToUpdatePublicationHeader", kmelia, request);
                }
            }
        } else if (function.equals("DraftOut")) {
            kmelia.draftOutPublication();

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ToTopicWysiwyg")) {
            String topicId = request.getParameter("Id");
            String subTopicId = request.getParameter("ChildId");
            String flag = kmelia.getProfile();

            NodeDetail topic = kmelia.getSubTopicDetail(subTopicId);

            request.setAttribute("SpaceId", kmelia.getSpaceId());
            request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8));
            request.setAttribute("ComponentId", kmelia.getComponentId());
            request.setAttribute("ComponentName",
                    URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8));
            String browseInfo = kmelia.getSessionPathString();
            if (browseInfo != null && !browseInfo.contains(topic.getName())) {
                browseInfo += topic.getName();
            }
            if (!StringUtil.isDefined(browseInfo)) {
                browseInfo = kmelia.getString("TopicWysiwyg");
            } else {
                browseInfo += " > " + kmelia.getString("TopicWysiwyg");
            }
            request.setAttribute("BrowseInfo", browseInfo);
            request.setAttribute("ObjectId", "Node_" + subTopicId);
            request.setAttribute("Language", kmelia.getLanguage());
            request.setAttribute("ContentLanguage", kmelia.getCurrentLanguage());
            request.setAttribute("ReturnUrl",
                    URLManager.getApplicationURL()
                            + URLManager.getURL(kmelia.getSpaceId(), kmelia.getComponentId())
                            + "FromTopicWysiwyg?Action=Search&Id=" + topicId + "&ChildId=" + subTopicId
                            + "&Profile=" + flag);
            destination = "/wysiwyg/jsp/htmlEditor.jsp";
        } else if (function.equals("FromTopicWysiwyg")) {
            String subTopicId = request.getParameter("ChildId");

            kmelia.processTopicWysiwyg(subTopicId);

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ChangeTopicStatus")) {
            String subTopicId = request.getParameter("ChildId");
            String newStatus = request.getParameter("Status");
            String recursive = request.getParameter("Recursive");

            if (recursive != null && recursive.equals("1")) {
                kmelia.changeTopicStatus(newStatus, subTopicId, true);
            } else {
                kmelia.changeTopicStatus(newStatus, subTopicId, false);
            }

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ViewOnly")) {
            String id = request.getParameter("Id");
            destination = rootDestination + "publicationViewOnly.jsp?Id=" + id;
        } else if (function.equals("SeeAlso")) {
            String action = request.getParameter("Action");
            if (!StringUtil.isDefined(action)) {
                action = "LinkAuthorView";
            }

            request.setAttribute("Action", action);

            // check if requested publication is an alias
            String pubId = request.getParameter("PubId");
            KmeliaPublication kmeliaPublication = kmelia.getSessionPublication();
            if (StringUtil.isDefined(pubId)) {
                kmeliaPublication = kmelia.getPublication(pubId);
                kmelia.setSessionPublication(kmeliaPublication);
            }
            checkAlias(kmelia, kmeliaPublication);

            if (kmeliaPublication.isAlias()) {
                request.setAttribute("Profile", "user");
                request.setAttribute("IsAlias", "1");
            } else {
                request.setAttribute("Profile", kmelia.getProfile());
            }

            // paramtres du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            destination = rootDestination + "seeAlso.jsp";
        } else if (function.equals("DeleteSeeAlso")) {
            String[] pubIds = request.getParameterValues("PubIds");

            if (pubIds != null) {
                List<ForeignPK> infoLinks = new ArrayList<ForeignPK>();
                for (String pubId : pubIds) {
                    StringTokenizer tokens = new StringTokenizer(pubId, "-");
                    infoLinks.add(new ForeignPK(tokens.nextToken(), tokens.nextToken()));

                    // removing deleted pks from session
                    Set<String> list = (Set<String>) request.getSession()
                            .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY);
                    if (list != null) {
                        list.remove(pubId);
                    }
                }

                if (!infoLinks.isEmpty()) {
                    kmelia.deleteInfoLinks(kmelia.getSessionPublication().getId(), infoLinks);
                }
            }

            destination = getDestination("SeeAlso", kmelia, request);
        } else if (function.equals("ImportFileUpload")) {
            destination = processFormUpload(kmelia, request, rootDestination, false);
        } else if (function.equals("ImportFilesUpload")) {
            destination = processFormUpload(kmelia, request, rootDestination, true);
        } else if (function.equals("ExportAttachementsToPDF")) {
            String topicId = request.getParameter("TopicId");
            // build an exploitable list by importExportPeas
            SilverTrace.info("kmelia", "KmeliaSessionController.getAllVisiblePublicationsByTopic()",
                    "root.MSG_PARAM_VALUE", "topicId =" + topicId);
            List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId);
            request.setAttribute("selectedResultsWa", publicationsIds);
            request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId()));
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/ExportPDF";
        } else if (function.equals("NewPublication")) {
            request.setAttribute("Action", "New");
            destination = getDestination("publicationManager.jsp", kmelia, request);
        } else if (function.equals("ManageSubscriptions")) {
            destination = kmelia.manageSubscriptions();
        } else if (function.equals("AddPublication")) {
            List<FileItem> parameters = request.getFileItems();

            // create publication
            String positions = FileUploadUtil.getParameter(parameters, "Positions");
            PdcClassificationEntity withClassification = PdcClassificationEntity.undefinedClassification();
            if (StringUtil.isDefined(positions)) {
                withClassification = PdcClassificationEntity.fromJSON(positions);
            }
            PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia);
            String newPubId = kmelia.createPublication(pubDetail, withClassification);
            // create thumbnail if exists
            boolean newThumbnail = ThumbnailController.processThumbnail(
                    new ForeignPK(newPubId, kmelia.getComponentId()), PublicationDetail.getResourceType(),
                    parameters);
            // force indexation to taking into account new thumbnail
            if (newThumbnail && pubDetail.isIndexable()) {
                kmelia.getPublicationBm().createIndex(pubDetail.getPK());
            }
            request.setAttribute("PubId", newPubId);
            processPath(kmelia, newPubId);
            String wizard = kmelia.getWizard();
            if ("progress".equals(wizard)) {
                KmeliaPublication kmeliaPublication = kmelia.getPublication(newPubId);
                kmelia.setSessionPublication(kmeliaPublication);
                String position = FileUploadUtil.getParameter(parameters, "Position");
                setWizardParams(request, kmelia);
                request.setAttribute("Position", position);
                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("Profile", kmelia.getProfile());
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                StringBuffer requestURI = request.getRequestURL();
                destination = requestURI.substring(0, requestURI.indexOf("AddPublication"))
                        + "ViewPublication?PubId=" + newPubId;
            }
        } else if ("UpdatePublication".equals(function)) {
            List<FileItem> parameters = request.getFileItems();

            PublicationDetail pubDetail = getPublicationDetail(parameters, kmelia);
            String id = pubDetail.getPK().getId();
            ThumbnailController.processThumbnail(new ForeignPK(id, kmelia.getComponentId()),
                    PublicationDetail.getResourceType(), parameters);

            kmelia.updatePublication(pubDetail);

            String wizard = kmelia.getWizard();
            if (wizard.equals("progress")) {
                KmeliaPublication kmeliaPublication = kmelia.getPublication(id);
                String position = FileUploadUtil.getParameter(parameters, "Position");
                setWizardParams(request, kmelia);
                request.setAttribute("Position", position);
                request.setAttribute("Publication", kmeliaPublication);
                request.setAttribute("Profile", kmelia.getProfile());
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    request.setAttribute("PubId", id);
                    request.setAttribute("CheckPath", "1");
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("SelectValidator")) {
            destination = kmelia.initUPToSelectValidator("");
        } else if (function.equals("PublicationPaths")) {
            // paramtre du wizard
            request.setAttribute("Wizard", kmelia.getWizard());

            PublicationDetail publication = kmelia.getSessionPublication().getDetail();
            String pubId = publication.getPK().getId();
            request.setAttribute("Publication", publication);
            request.setAttribute("LinkedPathString", kmelia.getSessionPath());
            request.setAttribute("PathList", kmelia.getPublicationFathers(pubId));

            if (toolboxMode) {
                request.setAttribute("Topics", kmelia.getAllTopics());
            } else {
                List<Alias> aliases = kmelia.getAliases();
                request.setAttribute("Aliases", aliases);
                request.setAttribute("Components", kmelia.getComponents(aliases));
            }

            destination = rootDestination + "publicationPaths.jsp";
        } else if (function.equals("SetPath")) {
            String[] topics = request.getParameterValues("topicChoice");
            String loadedComponentIds = request.getParameter("LoadedComponentIds");

            Alias alias;
            List<Alias> aliases = new ArrayList<Alias>();
            for (int i = 0; topics != null && i < topics.length; i++) {
                String topicId = topics[i];
                SilverTrace.debug("kmelia", "KmeliaRequestRouter.setPath()", "root.MSG_GEN_PARAM_VALUE",
                        "topicId = " + topicId);
                StringTokenizer tokenizer = new StringTokenizer(topicId, ",");
                String nodeId = tokenizer.nextToken();
                String instanceId = tokenizer.nextToken();

                alias = new Alias(nodeId, instanceId);
                alias.setUserId(kmelia.getUserId());
                aliases.add(alias);
            }

            // Tous les composants ayant un alias n'ont pas forcment t chargs
            List<Alias> oldAliases = kmelia.getAliases();
            for (Alias oldAlias : oldAliases) {
                if (!loadedComponentIds.contains(oldAlias.getInstanceId())) {
                    // le composant de l'alias n'a pas t charg
                    aliases.add(oldAlias);
                }
            }

            kmelia.setAliases(aliases);

            destination = getDestination("ViewPublication", kmelia, request);
        } else if (function.equals("ShowAliasTree")) {
            String componentId = request.getParameter("ComponentId");

            request.setAttribute("Tree", kmelia.getAliasTreeview(componentId));
            request.setAttribute("Aliases", kmelia.getAliases());

            destination = rootDestination + "treeview4PublicationPaths.jsp";
        } else if (function.equals("AddLinksToPublication")) {
            String id = request.getParameter("PubId");
            String topicId = request.getParameter("TopicId");
            //noinspection unchecked
            HashSet<String> list = (HashSet) request.getSession()
                    .getAttribute(KmeliaConstants.PUB_TO_LINK_SESSION_KEY);

            int nb = kmelia.addPublicationsToLink(id, list);

            request.setAttribute("NbLinks", Integer.toString(nb));

            destination = rootDestination + "publicationLinksManager.jsp?Action=Add&Id=" + topicId;
        } else if (function.equals("ExportTopic")) {
            String topicId = request.getParameter("TopicId");
            boolean exportFullApp = !StringUtil.isDefined(topicId) || NodePK.ROOT_NODE_ID.equals(topicId);
            if (kmaxMode) {
                if (exportFullApp) {
                    destination = getDestination("KmaxExportComponent", kmelia, request);
                } else {
                    destination = getDestination("KmaxExportPublications", kmelia, request);
                }
            } else {
                // build an exploitable list by importExportPeas
                SilverTrace.info("kmelia", "KmeliaRequestRouter.ExportTopic", "root.MSG_PARAM_VALUE",
                        "topicId =" + topicId);
                final List<WAAttributeValuePair> publicationsIds;
                if (exportFullApp) {
                    publicationsIds = kmelia.getAllVisiblePublications();
                } else {
                    publicationsIds = kmelia.getAllVisiblePublicationsByTopic(topicId);
                }
                request.setAttribute("selectedResultsWa", publicationsIds);
                request.setAttribute("RootPK", new NodePK(topicId, kmelia.getComponentId()));
                // Go to importExportPeas
                destination = "/RimportExportPeas/jsp/SelectExportMode";
            }
        } else if (function.equals("ExportPublications")) {
            String selectedIds = request.getParameter("SelectedIds");
            String notSelectedIds = request.getParameter("NotSelectedIds");
            List<PublicationPK> pks = kmelia.processSelectedPublicationIds(selectedIds, notSelectedIds);

            List<WAAttributeValuePair> publicationIds = new ArrayList<WAAttributeValuePair>();
            for (PublicationPK pk : pks) {
                publicationIds.add(new WAAttributeValuePair(pk.getId(), pk.getInstanceId()));
            }
            request.setAttribute("selectedResultsWa", publicationIds);
            request.setAttribute("RootPK", new NodePK(kmelia.getCurrentFolderId(), kmelia.getComponentId()));
            kmelia.resetSelectedPublicationPKs();
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/SelectExportMode";
        } else if (function.equals("ToPubliContent")) {
            CompletePublication completePublication = kmelia.getSessionPubliOrClone().getCompleteDetail();
            if (completePublication.getModelDetail() != null) {
                destination = getDestination("ToDBModel", kmelia, request);
            } else if (WysiwygController.haveGotWysiwyg(kmelia.getComponentId(),
                    completePublication.getPublicationDetail().getPK().getId(), kmelia.getCurrentLanguage())) {

                destination = getDestination("ToWysiwyg", kmelia, request);
            } else {
                String infoId = completePublication.getPublicationDetail().getInfoId();
                if (infoId == null || "0".equals(infoId)) {
                    List<String> usedModels = (List<String>) kmelia.getModelUsed();
                    if (usedModels.size() == 1) {
                        String modelId = usedModels.get(0);
                        if ("WYSIWYG".equals(modelId)) {
                            // Wysiwyg content
                            destination = getDestination("ToWysiwyg", kmelia, request);
                        } else if (StringUtil.isInteger(modelId)) {
                            // DB template
                            ModelDetail model = kmelia.getModelDetail(modelId);
                            request.setAttribute("ModelDetail", model);
                            destination = getDestination("ToDBModel", kmelia, request);
                        } else {
                            // XML template
                            request.setAttribute("Name", modelId);
                            destination = getDestination("GoToXMLForm", kmelia, request);
                        }
                    } else {
                        destination = getDestination("ListModels", kmelia, request);
                    }
                } else {
                    destination = getDestination("GoToXMLForm", kmelia, request);
                }
            }
        } else if (function.equals("ListModels")) {
            setTemplatesUsedIntoRequest(kmelia, request);

            // put current publication
            request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPublication().getDetail());

            // Paramtres du wizard
            setWizardParams(request, kmelia);
            destination = rootDestination + "modelsList.jsp";
        } else if (function.equals("ModelUsed")) {
            request.setAttribute("XMLForms", kmelia.getForms());
            // put dbForms
            Collection<ModelDetail> dbForms = kmelia.getAllModels();
            request.setAttribute("DBForms", dbForms);

            Collection<String> modelUsed = kmelia.getModelUsed();
            request.setAttribute("ModelUsed", modelUsed);

            destination = rootDestination + "modelUsedList.jsp";
        } else if (function.equals("SelectModel")) {
            Object o = request.getParameterValues("modelChoice");
            if (o != null) {
                kmelia.addModelUsed((String[]) o);
            }
            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if ("ChangeTemplate".equals(function)) {
            kmelia.removePublicationContent();
            destination = getDestination("ToPubliContent", kmelia, request);
        } else if ("ToWysiwyg".equals(function)) {
            if (kmelia.isCloneNeeded()) {
                kmelia.clonePublication();
            }
            // put current publication
            PublicationDetail publication = kmelia.getSessionPubliOrClone().getDetail();

            // Parametres du Wizard
            setWizardParams(request, kmelia);
            request.setAttribute("SpaceId", kmelia.getSpaceId());
            request.setAttribute("SpaceName", URLEncoder.encode(kmelia.getSpaceLabel(), CharEncoding.UTF_8));
            request.setAttribute("ComponentId", kmelia.getComponentId());
            request.setAttribute("ComponentName",
                    URLEncoder.encode(kmelia.getComponentLabel(), CharEncoding.UTF_8));
            if (kmaxMode) {
                request.setAttribute("BrowseInfo", publication.getName());
            } else {
                request.setAttribute("BrowseInfo",
                        kmelia.getSessionPathString() + " > " + publication.getName());
            }
            request.setAttribute("ObjectId", publication.getId());
            request.setAttribute("Language", kmelia.getLanguage());
            request.setAttribute("ContentLanguage", checkLanguage(kmelia, publication));
            request.setAttribute("ReturnUrl", URLManager.getApplicationURL() + kmelia.getComponentUrl()
                    + "FromWysiwyg?PubId=" + publication.getId());
            request.setAttribute("UserId", kmelia.getUserId());
            request.setAttribute("IndexIt", "false");

            destination = "/wysiwyg/jsp/htmlEditor.jsp";
        } else if ("FromWysiwyg".equals(function)) {
            String id = request.getParameter("PubId");

            // Parametres du Wizard
            String wizard = kmelia.getWizard();
            setWizardParams(request, kmelia);
            if (wizard.equals("progress")) {
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null
                        && id.equals(kmelia.getSessionClone().getDetail().getPK().getId())) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.equals("ToDBModel")) {
            String modelId = request.getParameter("ModelId");
            if (StringUtil.isDefined(modelId)) {
                ModelDetail model = kmelia.getModelDetail(modelId);
                request.setAttribute("ModelDetail", model);
            }

            // put current publication
            request.setAttribute("CompletePublication", kmelia.getSessionPubliOrClone().getCompleteDetail());
            request.setAttribute("NotificationAllowed", kmelia.isNotificationAllowed());

            // Paramtres du wizard
            setWizardParams(request, kmelia);

            destination = rootDestination + "modelManager.jsp";
        } else if (function.equals("UpdateDBModelContent")) {
            ResourceLocator publicationSettings = kmelia.getPublicationSettings();

            List<InfoTextDetail> textDetails = new ArrayList<InfoTextDetail>();
            List<InfoImageDetail> imageDetails = new ArrayList<InfoImageDetail>();
            int imageOrder = 0;
            boolean imageTrouble = false;
            List<FileItem> parameters = request.getFileItems();
            String modelId = FileUploadUtil.getParameter(parameters, "ModelId");
            // Parametres du Wizard
            setWizardParams(request, kmelia);

            for (FileItem item : parameters) {
                if (item.isFormField() && item.getFieldName().startsWith("WATXTVAR")) {
                    String theText = item.getString();
                    int textOrder = Integer
                            .parseInt(item.getFieldName().substring(8, item.getFieldName().length()));
                    textDetails.add(new InfoTextDetail(null, Integer.toString(textOrder), null, theText));
                } else if (!item.isFormField()) {
                    String logicalName = item.getName();
                    if (logicalName != null && logicalName.length() > 0) {
                        if (!FileUtil.isWindows()) {
                            logicalName = logicalName.replace('\\', File.separatorChar);
                            SilverTrace.info("kmelia", "KmeliaRequestRouter.UpdateDBModelContent",
                                    "root.MSG_GEN_PARAM_VALUE", "fileName on Unix = " + logicalName);
                        }
                        logicalName = FilenameUtils.getName(logicalName);
                        String physicalName = Long.toString(System.currentTimeMillis()) + "."
                                + FilenameUtils.getExtension(logicalName);
                        String mimeType = item.getContentType();
                        long size = item.getSize();

                        File dir = new File(FileRepositoryManager.getAbsolutePath(kmelia.getComponentId())
                                + publicationSettings.getString("imagesSubDirectory") + File.separatorChar
                                + physicalName);
                        if (FileUtil.isImage(logicalName)) {
                            item.write(dir);
                            imageOrder++;
                            if (size > 0L) {
                                imageDetails.add(new InfoImageDetail(null, Integer.toString(imageOrder), null,
                                        physicalName, logicalName, "", mimeType, size));
                                imageTrouble = false;
                            } else {
                                imageTrouble = true;
                            }
                        } else {
                            imageTrouble = true;
                        }
                    } else {
                        // the field did not contain a file
                    }
                }
            }

            InfoDetail infos = new InfoDetail(null, textDetails, imageDetails, null, "");
            CompletePublication completePub = kmelia.getSessionPubliOrClone().getCompleteDetail();
            if (completePub.getModelDetail() == null) {
                kmelia.createInfoModelDetail("useless", modelId, infos);
            } else {
                kmelia.updateInfoDetail("useless", infos);
            }
            if (imageTrouble) {
                request.setAttribute("ImageTrouble", Boolean.TRUE);
            }

            String wizard = kmelia.getWizard();
            if (wizard.equals("progress")) {
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                destination = getDestination("ToDBModel", kmelia, request);
            }
        } else if (function.equals("GoToXMLForm")) {
            String xmlFormName = request.getParameter("Name");
            if (!StringUtil.isDefined(xmlFormName)) {
                xmlFormName = (String) request.getAttribute("Name");
            }
            setXMLForm(request, kmelia, xmlFormName);
            // put current publication
            request.setAttribute("CurrentPublicationDetail", kmelia.getSessionPubliOrClone().getDetail());
            // Parametres du Wizard
            setWizardParams(request, kmelia);
            // template can be changed only if current topic is using at least two templates
            setTemplatesUsedIntoRequest(kmelia, request);
            @SuppressWarnings("unchecked")
            Collection<PublicationTemplate> templates = (Collection<PublicationTemplate>) request
                    .getAttribute("XMLForms");
            boolean wysiwygUsable = (Boolean) request.getAttribute("WysiwygValid");
            request.setAttribute("IsChangingTemplateAllowed",
                    templates.size() >= 2 || (!templates.isEmpty() && wysiwygUsable));

            destination = rootDestination + "xmlForm.jsp";
        } else if (function.equals("UpdateXMLForm")) {
            if (kmelia.isCloneNeeded()) {
                kmelia.clonePublication();
            }

            if (!StringUtil.isDefined(request.getCharacterEncoding())) {
                request.setCharacterEncoding("UTF-8");
            }
            String encoding = request.getCharacterEncoding();
            List<FileItem> items = request.getFileItems();

            PublicationDetail pubDetail = kmelia.getSessionPubliOrClone().getDetail();

            String xmlFormShortName;

            // Is it the creation of the content or an update ?
            String infoId = pubDetail.getInfoId();
            if (infoId == null || "0".equals(infoId)) {
                String xmlFormName = FileUploadUtil.getParameter(items, "Name", null, encoding);

                // The publication have no content
                // We have to register xmlForm to publication
                xmlFormShortName = xmlFormName.substring(xmlFormName.indexOf('/') + 1,
                        xmlFormName.indexOf('.'));
                pubDetail.setInfoId(xmlFormShortName);
                kmelia.updatePublication(pubDetail);
            } else {
                xmlFormShortName = pubDetail.getInfoId();
            }
            String pubId = pubDetail.getPK().getId();
            PublicationTemplate pub = getPublicationTemplateManager()
                    .getPublicationTemplate(kmelia.getComponentId() + ":" + xmlFormShortName);
            RecordSet set = pub.getRecordSet();
            Form form = pub.getUpdateForm();
            String language = checkLanguage(kmelia, pubDetail);
            DataRecord data = set.getRecord(pubId, language);
            if (data == null) {
                data = set.getEmptyRecord();
                data.setId(pubId);
                data.setLanguage(language);
            }
            PagesContext context = new PagesContext("myForm", "3", kmelia.getLanguage(), false,
                    kmelia.getComponentId(), kmelia.getUserId());
            context.setEncoding(CharEncoding.UTF_8);
            if (!kmaxMode) {
                context.setNodeId(kmelia.getCurrentFolderId());
            }
            context.setObjectId(pubId);
            context.setContentLanguage(kmelia.getCurrentLanguage());

            form.update(items, data, context);
            set.save(data);

            // update publication to change updateDate and updaterId
            kmelia.updatePublication(pubDetail);

            // Parametres du Wizard
            setWizardParams(request, kmelia);

            if (kmelia.getWizard().equals("progress")) {
                // on est en mode Wizard
                request.setAttribute("Position", "Content");
                destination = getDestination("WizardNext", kmelia, request);
            } else {
                if (kmelia.getSessionClone() != null) {
                    destination = getDestination("ViewClone", kmelia, request);
                } else if (kmaxMode) {
                    destination = getDestination("ViewAttachments", kmelia, request);
                } else {
                    destination = getDestination("ViewPublication", kmelia, request);
                }
            }
        } else if (function.startsWith("ToOrderPublications")) {
            List<KmeliaPublication> publications = kmelia.getSessionPublicationsList();

            request.setAttribute("Publications", publications);
            request.setAttribute("Path", kmelia.getSessionPath());

            destination = rootDestination + "orderPublications.jsp";
        } else if (function.startsWith("OrderPublications")) {
            String sortedIds = request.getParameter("sortedIds");

            StringTokenizer tokenizer = new StringTokenizer(sortedIds, ",");
            List<String> ids = new ArrayList<String>();
            while (tokenizer.hasMoreTokens()) {
                ids.add(tokenizer.nextToken());
            }
            kmelia.orderPublications(ids);

            destination = getDestination("GoToCurrentTopic", kmelia, request);
        } else if (function.equals("ToOrderTopics")) {
            String id = request.getParameter("Id");
            if (!SilverpeasRole.admin.isInRole(kmelia.getUserTopicProfile(id))) {
                destination = "/admin/jsp/accessForbidden.jsp";
            } else {
                TopicDetail topic = kmelia.getTopic(id);
                request.setAttribute("Nodes", topic.getNodeDetail().getChildrenDetails());
                destination = rootDestination + "orderTopics.jsp";
            }
        } else if (function.startsWith("Wizard")) {
            destination = processWizard(function, kmelia, request, rootDestination);
        } else if ("ViewTopicProfiles".equals(function)) {
            String role = request.getParameter("Role");
            if (!StringUtil.isDefined(role)) {
                role = SilverpeasRole.admin.toString();
            }

            String id = request.getParameter("NodeId");
            if (!StringUtil.isDefined(id)) {
                id = (String) request.getAttribute("NodeId");
            }
            request.setAttribute("Profiles", kmelia.getTopicProfiles(id));
            NodeDetail topic = kmelia.getNodeHeader(id);
            ProfileInst profile;
            if (topic.haveInheritedRights()) {
                profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn()));

                request.setAttribute("RightsDependsOn", "AnotherTopic");
            } else if (topic.haveLocalRights()) {
                profile = kmelia.getTopicProfile(role, Integer.toString(topic.getRightsDependsOn()));

                request.setAttribute("RightsDependsOn", "ThisTopic");
            } else {
                profile = kmelia.getProfile(role);
                // Rights of the component
                request.setAttribute("RightsDependsOn", "ThisComponent");
            }

            request.setAttribute("CurrentProfile", profile);
            request.setAttribute("Groups", kmelia.groupIds2Groups(profile.getAllGroups()));
            request.setAttribute("Users", kmelia.userIds2Users(profile.getAllUsers()));
            List<NodeDetail> path = kmelia.getTopicPath(id);
            request.setAttribute("Path", kmelia.displayPath(path, true, 3));
            request.setAttribute("NodeDetail", topic);

            destination = rootDestination + "topicProfiles.jsp";
        } else if (function.equals("TopicProfileSelection")) {
            String role = request.getParameter("Role");
            String nodeId = request.getParameter("NodeId");
            try {
                kmelia.initUserPanelForTopicProfile(role, nodeId);
            } catch (Exception e) {
                SilverTrace.warn("jobStartPagePeas", "JobStartPagePeasRequestRouter.getDestination()",
                        "root.EX_USERPANEL_FAILED", "function = " + function, e);
            }
            destination = Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS);
        } else if (function.equals("TopicProfileSetUsersAndGroups")) {
            String role = request.getParameter("Role");
            String nodeId = request.getParameter("NodeId");

            kmelia.updateTopicRole(role, nodeId);

            request.setAttribute("urlToReload", "ViewTopicProfiles?Role=" + role + "&NodeId=" + nodeId);
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("TopicProfileRemove")) {
            String profileId = request.getParameter("Id");

            kmelia.deleteTopicRole(profileId);

            destination = getDestination("ViewTopicProfiles", kmelia, request);
        } else if (function.equals("CloseWindow")) {
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.startsWith("UpdateChain")) {
            destination = processUpdateChainOperation(rootDestination, function, kmelia, request);
        } else if (function.equals("SuggestDelegatedNews")) {

            String pubId = kmelia.addDelegatedNews();

            request.setAttribute("PubId", pubId);
            destination = getDestination("ViewPublication", kmelia, request);
        } /**
          * *************************
          * Kmax mode ***********************
          */
        else if (function.equals("KmaxMain")) {
            destination = rootDestination + "kmax.jsp?Action=KmaxView&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxAxisManager")) {
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxViewAxis&Profile="
                    + kmelia.getProfile();
        } else if (function.equals("KmaxAddAxis")) {
            String newAxisName = request.getParameter("Name");
            String newAxisDescription = request.getParameter("Description");
            NodeDetail axis = new NodeDetail("-1", newAxisName, newAxisDescription, DateUtil.today2SQLDate(),
                    kmelia.getUserId(), null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(axis, request);
            kmelia.addAxis(axis);

            request.setAttribute("urlToReload", "KmaxAxisManager");
            destination = rootDestination + "closeWindow.jsp";
        } else if (function.equals("KmaxUpdateAxis")) {
            String axisId = request.getParameter("AxisId");
            String newAxisName = request.getParameter("AxisName");
            String newAxisDescription = request.getParameter("AxisDescription");
            NodeDetail axis = new NodeDetail(axisId, newAxisName, newAxisDescription, null, null, null, "0",
                    "X");
            // I18N
            I18NHelper.setI18NInfo(axis, request);
            kmelia.updateAxis(axis);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxDeleteAxis")) {
            String axisId = request.getParameter("AxisId");
            kmelia.deleteAxis(axisId);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxManageAxis")) {
            String axisId = request.getParameter("AxisId");
            String translation = request.getParameter("Translation");
            request.setAttribute("Translation", translation);
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManageAxis&Profile="
                    + kmelia.getProfile() + "&AxisId=" + axisId;
        } else if (function.equals("KmaxManagePosition")) {
            String positionId = request.getParameter("PositionId");
            String translation = request.getParameter("Translation");
            request.setAttribute("Translation", translation);
            destination = rootDestination + "kmax_axisManager.jsp?Action=KmaxManagePosition&Profile="
                    + kmelia.getProfile() + "&PositionId=" + positionId;
        } else if (function.equals("KmaxAddPosition")) {
            String axisId = request.getParameter("AxisId");
            String newPositionName = request.getParameter("Name");
            String newPositionDescription = request.getParameter("Description");
            String translation = request.getParameter("Translation");
            NodeDetail position = new NodeDetail("toDefine", newPositionName, newPositionDescription, null,
                    null, null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(position, request);
            kmelia.addPosition(axisId, position);
            request.setAttribute("AxisId", axisId);
            request.setAttribute("Translation", translation);
            destination = getDestination("KmaxManageAxis", kmelia, request);
        } else if (function.equals("KmaxUpdatePosition")) {
            String positionId = request.getParameter("PositionId");
            String positionName = request.getParameter("PositionName");
            String positionDescription = request.getParameter("PositionDescription");
            NodeDetail position = new NodeDetail(positionId, positionName, positionDescription, null, null,
                    null, "0", "X");
            // I18N
            I18NHelper.setI18NInfo(position, request);
            kmelia.updatePosition(position);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxDeletePosition")) {
            String positionId = request.getParameter("PositionId");
            kmelia.deletePosition(positionId);
            destination = getDestination("KmaxAxisManager", kmelia, request);
        } else if (function.equals("KmaxViewUnbalanced")) {
            List<KmeliaPublication> publications = kmelia.getUnbalancedPublications();
            kmelia.setSessionPublicationsList(publications);
            kmelia.orderPubs();

            destination = rootDestination + "kmax.jsp?Action=KmaxViewUnbalanced&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxViewBasket")) {
            TopicDetail basket = kmelia.getTopic("1");
            List<KmeliaPublication> publications = (List<KmeliaPublication>) basket.getKmeliaPublications();
            kmelia.setSessionPublicationsList(publications);
            kmelia.orderPubs();

            destination = rootDestination + "kmax.jsp?Action=KmaxViewBasket&Profile=" + kmelia.getProfile();

        } else if (function.equals("KmaxViewToValidate")) {
            destination = rootDestination + "kmax.jsp?Action=KmaxViewToValidate&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxSearch")) {
            String axisValuesStr = request.getParameter("SearchCombination");
            if (!StringUtil.isDefined(axisValuesStr)) {
                axisValuesStr = (String) request.getAttribute("SearchCombination");
            }
            String timeCriteria = request.getParameter("TimeCriteria");

            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "axisValuesStr = " + axisValuesStr + " timeCriteria=" + timeCriteria);
            List<String> combination = kmelia.getCombination(axisValuesStr);
            List<KmeliaPublication> publications;
            if (StringUtil.isDefined(timeCriteria) && !"X".equals(timeCriteria)) {
                publications = kmelia.search(combination, Integer.parseInt(timeCriteria));
            } else {
                publications = kmelia.search(combination);
            }
            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "publications = " + publications + " Combination=" + combination + " timeCriteria="
                            + timeCriteria);

            kmelia.setIndexOfFirstPubToDisplay("0");
            kmelia.orderPubs();
            kmelia.setSessionCombination(combination);
            kmelia.setSessionTimeCriteria(timeCriteria);

            destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxSearchResult")) {
            if (kmelia.getSessionCombination() == null) {
                destination = getDestination("KmaxMain", kmelia, request);
            } else {
                destination = rootDestination + "kmax.jsp?Action=KmaxSearchResult&Profile="
                        + kmelia.getProfile();
            }
        } else if (function.equals("KmaxViewCombination")) {
            setWizardParams(request, kmelia);

            request.setAttribute("CurrentCombination", kmelia.getCurrentCombination());
            destination = rootDestination + "kmax_viewCombination.jsp?Profile=" + kmelia.getProfile();
        } else if (function.equals("KmaxAddCoordinate")) {
            String pubId = request.getParameter("PubId");
            String axisValuesStr = request.getParameter("SearchCombination");
            StringTokenizer st = new StringTokenizer(axisValuesStr, ",");
            List<String> combination = new ArrayList<String>();
            String axisValue;
            while (st.hasMoreTokens()) {
                axisValue = st.nextToken();
                // axisValue is xx/xx/xx where xx are nodeId
                axisValue = axisValue.substring(axisValue.lastIndexOf('/') + 1, axisValue.length());
                combination.add(axisValue);
            }
            kmelia.addPublicationToCombination(pubId, combination);
            // Store current combination
            kmelia.setCurrentCombination(kmelia.getCombination(axisValuesStr));
            destination = getDestination("KmaxViewCombination", kmelia, request);
        } else if (function.equals("KmaxDeleteCoordinate")) {
            String coordinateId = request.getParameter("CoordinateId");
            String pubId = request.getParameter("PubId");
            SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                    "coordinateId = " + coordinateId + " PubId=" + pubId);
            kmelia.deletePublicationFromCombination(pubId, coordinateId);
            destination = getDestination("KmaxViewCombination", kmelia, request);
        } else if (function.equals("KmaxExportComponent")) {
            // build an exploitable list by importExportPeas
            List<WAAttributeValuePair> publicationsIds = kmelia.getAllVisiblePublications();
            request.setAttribute("selectedResultsWa", publicationsIds);

            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/KmaxExportComponent";
        } else if (function.equals("KmaxExportPublications")) {
            // build an exploitable list by importExportPeas
            List<WAAttributeValuePair> publicationsIds = kmelia.getCurrentPublicationsList();
            List<String> combination = kmelia.getSessionCombination();
            // get the time axis
            String timeCriteria = null;
            if (kmelia.isTimeAxisUsed() && StringUtil.isDefined(kmelia.getSessionTimeCriteria())) {
                ResourceLocator timeSettings = new ResourceLocator(
                        "org.silverpeas.kmelia.multilang.timeAxisBundle", kmelia.getLanguage());
                if (kmelia.getSessionTimeCriteria().equals("X")) {
                    timeCriteria = null;
                } else {
                    timeCriteria = "<b>" + kmelia.getString("TimeAxis") + "</b> > "
                            + timeSettings.getString(kmelia.getSessionTimeCriteria(), "");
                }
            }
            request.setAttribute("selectedResultsWa", publicationsIds);
            request.setAttribute("Combination", combination);
            request.setAttribute("TimeCriteria", timeCriteria);
            // Go to importExportPeas
            destination = "/RimportExportPeas/jsp/KmaxExportPublications";
        } else if ("statistics".equals(function)) {
            destination = rootDestination + statisticRequestHandler.handleRequest(request, function, kmelia);
        } else if ("statSelectionGroup".equals(function)) {
            destination = statisticRequestHandler.handleRequest(request, function, kmelia);
        } else if ("SetPublicationValidator".equals(function)) {
            String userIds = request.getParameter("ValideurId");
            kmelia.setPublicationValidator(userIds);
            destination = getDestination("ViewPublication", kmelia, request);
        } else {
            destination = rootDestination + function;
        }

        if (profileError) {
            destination = GeneralPropertiesManager.getString("sessionTimeout");
        }
        SilverTrace.info("kmelia", "KmeliaRequestRouter.getDestination()", "root.MSG_GEN_PARAM_VALUE",
                "destination = " + destination);
    } catch (Exception exce_all) {
        request.setAttribute("javax.servlet.jsp.jspException", exce_all);
        return "/admin/jsp/errorpageMain.jsp";
    }
    return destination;
}

From source file:com.github.gekoh.yagen.ddl.CreateDDL.java

public String updateCreateConstraint(Dialect dialect, StringBuffer buf, String name, Table table,
        Constraint constraint) {/*from   w w  w  .  ja v  a2s  . co  m*/
    NamingStrategy namingStrategy = getProfile().getNamingStrategy();
    String newName = namingStrategy.constraintName(constraint,
            getEntityClassName(namingStrategy.tableName(table.getName())));

    if (!name.equals(newName)) {
        String sqlCreate = buf.toString();
        Matcher matcher = CONSTRAINT_PATTERN.matcher(sqlCreate);
        if (matcher.find()) {
            buf = new StringBuffer();
            buf.append(sqlCreate.substring(0, matcher.start(1)));
            buf.append(newName);
            buf.append(sqlCreate.substring(matcher.end(1)));
        }
        name = newName;
    }

    String tableNameLC = getProfile().getNamingStrategy().tableName(table.getName()).toLowerCase();

    if (!renderTable(tableNameLC) || externalViews.contains(tableNameLC)) {
        return "-- skipped creation of constraint '" + name + "' for table '" + table.getName()
                + "' as the mapped entity was not chosen to be processed or is a view";
    }

    TableConfig tableConfig = tblNameToConfig.get(tableNameLC);

    String refTblNameLC = null;
    if (constraint instanceof ForeignKey) {
        if (tableConfig.getColumnNamesIsNoFK().contains(constraint.getColumn(0).getName().toLowerCase())) {
            return "-- skipped creation of foreign key constraint '" + name + "' for table '" + table.getName()
                    + "' according to annotation of type " + NoForeignKeyConstraint.class.getSimpleName();
        }
        refTblNameLC = getProfile().getNamingStrategy()
                .tableName(((ForeignKey) constraint).getReferencedTable().getName()).toLowerCase();
    }

    checkObjectName(dialect, name);
    String i18nFK = tableConfig.getI18nBaseEntityFkCol();

    if (i18nFK != null) {
        StringBuilder sql = new StringBuilder();
        tableNameLC = getI18NDetailTableName(tableNameLC);
        Matcher matcher = TBL_ALTER_PATTERN.matcher(buf.toString());
        if (matcher.find()) {
            sql.append(buf.substring(0, matcher.start(1))).append(tableNameLC)
                    .append(buf.substring(matcher.end(1)));
        }
        buf = new StringBuffer(sql.toString());
    }

    if (constraint instanceof ForeignKey) {
        StringBuilder colList = new StringBuilder();
        org.hibernate.mapping.Column singleColumn = null;

        TableConfig refTableConfig = tblNameToConfig.get(refTblNameLC);
        IntervalPartitioning refTblPart = refTableConfig != null
                ? refTableConfig.getTableAnnotationOfType(IntervalPartitioning.class)
                : null;

        for (org.hibernate.mapping.Column column : (Iterable<? extends org.hibernate.mapping.Column>) constraint
                .getColumns()) {
            if (colList.length() > 0) {
                colList.append(", ");
            }
            colList.append(column.getName().toLowerCase());
            singleColumn = singleColumn == null ? column : null;
        }

        if (externalViews.contains(refTblNameLC)) {
            buf = new StringBuffer("-- skipped creation of constraint '" + name + "' on table '" + tableNameLC
                    + "' since a view will be referenced");
        } else if (refTblPart != null && refTblPart.useLocalPK() && supportsPartitioning(dialect)) {
            buf = new StringBuffer();
            buf.append("-- skipped creation of foreign key constraint '").append(name).append("' on table '")
                    .append(tableNameLC).append("' to table '").append(refTblNameLC)
                    .append("' as the partitioned target table has a local PK (see @IntervalPartitioning on ")
                    .append(((ForeignKey) constraint).getReferencedEntityName()).append(")");
        } else {
            if (singleColumn != null) {
                if (tableConfig.getColumnNamesIsCascadeNullable()
                        .contains(singleColumn.getName().toLowerCase())) {
                    buf.append(" on delete set null");
                } else if (tableConfig.getColumnNamesIsCascadeDelete()
                        .contains(singleColumn.getName().toLowerCase()) && buf.indexOf("on delete") < 0) {
                    buf.append(" on delete cascade");
                }
            }

            Map<String, Deferrable> col2Deferrable = tableConfig.getColumnNameToDeferrable();
            Deferrable deferrable;
            if (supportsDeferrable(dialect) && col2Deferrable != null
                    && (deferrable = col2Deferrable.get(colList.toString())) != null) {
                buf.append(" deferrable");
                if (deferrable.initiallyDeferred()) {
                    buf.append(" initially deferred");
                }
            }

            if (getProfile().isDisableFKs()) {
                buf.insert(0,
                        "-- creating FK constraint initially disabled since we do not need it for profile '"
                                + getProfile() + "'\n");
                buf.append(" disable");
            }
        }

        getProfile().duplex(ObjectType.CONSTRAINT, name, buf.toString());

        if (constraint.getColumnSpan() == 1 && hasIndex(table, tableNameLC, singleColumn)) {
            LOG.debug("not creating foreign key index as there is already an index on table " + tableNameLC
                    + " and column " + colList.toString());
        } else {
            String fkIndexName = getProfile().getNamingStrategy().indexName(getEntityClassName(tableNameLC),
                    tableNameLC, DefaultNamingStrategy.concatColumnNames(colList.toString()));
            StringBuilder objDdl = new StringBuilder();
            objDdl.append("create index ").append(fkIndexName).append(" on ").append(tableNameLC).append(" (")
                    .append(colList.toString()).append(")");

            if (constraint.getColumnSpan() == 1) {
                tblColNameHasSingleColIndex.add(tableNameLC + "." + colList.toString());
            }

            buf.append(STATEMENT_SEPARATOR).append(objDdl);

            getProfile().duplex(ObjectType.INDEX, fkIndexName, objDdl.toString());
        }
    }

    return buf.toString();
}

From source file:com.topsec.tsm.sim.report.web.TopoReportController.java

/**
 *  ? ?/*from w  w w.  j  a v a 2 s .  c o  m*/
 * @param sid
 * @param request
 * @param response
 * @return
 * @throws Exception
 */
public String comprehensiveInformReport(SID sid, HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    JSONObject json = new JSONObject();
    ReportBean bean = new ReportBean();
    bean = ReportUiUtil.tidyFormBean(bean, request);
    String[] talCategory = bean.getTalCategory();
    ReportModel.setBeanPropery(bean);
    RptMasterTbService rptMasterTbImp = (RptMasterTbService) SpringContextServlet.springCtx
            .getBean(ReportUiConfig.MstBean);
    List<Map<String, Object>> comprehensiveSubAndColList = new ArrayList<Map<String, Object>>();
    List<String> hasComprehensiveReport = reportService.findAllTypeList();
    IsEditNodeType isEditNodeType = nodeTypeService.findIsEditByUserName(sid.getUserName());
    if (GlobalUtil.isNullOrEmpty(isEditNodeType)) {
        isEditNodeType = new IsEditNodeType();
        initEditNodeType(isEditNodeType, sid);
        if (!GlobalUtil.isNullOrEmpty(isEditNodeType.getUserName())) {
            nodeTypeService.saveIsEditNodeType(isEditNodeType);
        }
    }
    List<String> dvcTypes = null;
    String scanNodeId = null;
    List<SimDatasource> simDatasources = dataSourceService.getDataSource(DataSourceService.CMD_ALL);
    if (!isEditNodeType.getIsEdit()) {
        if (!GlobalUtil.isNullOrEmpty(simDatasources)) {
            dvcTypes = setDvcTypes(sid, simDatasources, bean, dvcTypes);
            hasComprehensive(dvcTypes, hasComprehensiveReport);
        }
        saveAndUpDateStatus(dvcTypes, sid, isEditNodeType);
    } else {
        List<String> deviceTypeList = ReportModel.getDeviceTypeList(dataSourceService, sid);
        hasComprehensive(deviceTypeList, hasComprehensiveReport);
        if (!GlobalUtil.isNullOrEmpty(deviceTypeList)) {
            List<NodeTypeShow> nodeTypeShowList = nodeTypeService.findTypeShowsByUserName(sid.getUserName());
            removeShowsType(deviceTypeList, nodeTypeShowList);
            saveAndUpDateStatus(deviceTypeList, sid, isEditNodeType);
            if (!GlobalUtil.isNullOrEmpty(nodeTypeShowList)) {
                for (NodeTypeShow nodeTypeShow : nodeTypeShowList) {
                    nodeTypeService.deleteNodeTypeShow(nodeTypeShow);
                }
            }
        }

        List<NodeTypeShow> nodeTypeShows = nodeTypeService.findByUserNameAndIsShow(sid.getUserName(), true);
        dvcTypes = new ArrayList<String>(nodeTypeShows.size());
        if (!GlobalUtil.isNullOrEmpty(nodeTypeShows)) {
            for (NodeTypeShow nodeTypeShow : nodeTypeShows) {
                if (!dvcTypes.contains(nodeTypeShow.getNodeType())) {
                    dvcTypes.add(nodeTypeShow.getNodeType());
                }
            }
        }
    }
    if (!GlobalUtil.isNullOrEmpty(simDatasources)) {
        scanNodeId = simDatasources.get(0).getAuditorNodeId();
    } else {
        scanNodeId = "";
    }
    List<String> mstrptidAndNodeTypeList = new ArrayList<String>();
    setMstIdAndScanNodeType(dvcTypes, mstrptidAndNodeTypeList);
    int evtRptsize = 0;
    if (!GlobalUtil.isNullOrEmpty(mstrptidAndNodeTypeList)) {
        for (String string : mstrptidAndNodeTypeList) {
            List<Map<String, Object>> subResult = rptMasterTbImp.queryTmpList(ReportUiConfig.MstSubSql,
                    new Object[] { StringUtil.toInt((string.split("IDandNODEtype"))[0],
                            StringUtil.toInt(bean.getTalTop(), 5)) });
            Map<Integer, Integer> rowColumns = ReportModel.getRowColumns(subResult);
            if (!GlobalUtil.isNullOrEmpty(subResult)) {
                for (Map map2 : subResult) {
                    map2.put("subject", (string.split("IDandNODEtype"))[1]);
                }
                Map subResultAndRowColsMap = new HashMap<String, Object>();
                subResultAndRowColsMap.put("subResult", subResult);
                subResultAndRowColsMap.put("rowColumns", rowColumns);
                subResultAndRowColsMap.put("scanNodeType", string.split("IDandNODEtype")[1]);
                comprehensiveSubAndColList.add(subResultAndRowColsMap);
            }

        }
    }

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("eTime", bean.getTalEndTime());
    String sUrl = null;
    int screenWidth = StringUtil.toInt(request.getParameter("screenWidth"), 1280) - 25 - 200;

    StringBuffer subUrl = new StringBuffer();
    StringBuffer htmlOut = new StringBuffer();
    Map layoutValue = new HashMap();
    htmlOut.append("<table><tbody>");
    int tdnum = 0;
    boolean repeatRep = false;
    List<Object> subIdList = new ArrayList<Object>();
    int totalSub = 0;
    for (Map<String, Object> map : comprehensiveSubAndColList) {
        List<Map> subResult = (List<Map>) map.get("subResult");
        int len = subResult.size();
        totalSub += len;
        for (int i = 0; i < len; i++) {
            Map subMap = subResult.get(i);
            Object subId = subMap.get("subId");
            if (!subIdList.contains(subId)) {
                subIdList.add(subId);
            }
        }
    }
    if (subIdList.size() < totalSub) {
        repeatRep = true;
    }
    int repeatj = 0;
    for (Map<String, Object> map : comprehensiveSubAndColList) {
        List<Map> subResult = (List<Map>) map.get("subResult");
        Map<Integer, Integer> rowColumns = (Map<Integer, Integer>) map.get("rowColumns");
        String scanNodeType = (String) map.get("scanNodeType");
        StringBuffer layout = new StringBuffer();
        int divPaneltotalwidth = 0;
        divPaneltotalwidth = (int) ((screenWidth - 10) / 2.3);
        for (int i = 0, len = subResult.size(); i < len; i++) {
            params.remove("sTime");
            Map subMap = subResult.get(i);
            if (i == 0) {
                bean.setViewItem(StringUtil.toString(subMap.get("viewItem"), ""));
            }
            Integer row = (Integer) subMap.get("subRow");
            layout.append(row + ":" + subMap.get("subColumn") + ",");
            if (GlobalUtil.isNullOrEmpty(subMap)) {
                continue;
            }
            params.put("sTime", bean.getTalStartTime());
            params.put("dvcType", subMap.get("subject"));
            params.put("onlyTable", "onlyTable");
            String reportType = request.getParameter("reportType");
            if (!GlobalUtil.isNullOrEmpty(reportType)) {
                params.put("reportType", reportType);
            }
            sUrl = getComprehensiveUrl(ReportUiConfig.subEvtUrl, scanNodeId, params, bean.getTalCategory())
                    .toString();
            params.remove("dvcType");
            subUrl.replace(0, subUrl.length(), sUrl);
            subUrl.append("&").append(ReportUiConfig.subrptid).append("=").append(subMap.get("subId"));
            subUrl.substring(0, subUrl.length());
            if (repeatRep) {
                subUrl.append("subREPEAT_").append(repeatj++);
            }
            int column = rowColumns.get(row);
            String width = String.valueOf(((screenWidth - 10 * column) / column) / 2.4);
            String _column = subMap.get("subColumn").toString();
            subMap.put("InformReportOnlyTable", true);
            layoutValue.put(row + _column, ReportUiUtil.createSubTitle(subMap, width, subUrl.toString(),
                    bean.getTalCategory(), StringUtil.toInt(bean.getTalTop(), 5)));
        }
        String htmlLayoutmp = ReportModel.createMstTable(layout.toString(), layoutValue);
        String cnDvcName = ReportUiUtil.getDeviceTypeName(scanNodeType.replace("Comprehensive", ""),
                Locale.getDefault());
        if (tdnum % 2 == 0) {
            htmlOut.append("<tr>");
        }
        tdnum++;
        htmlOut.append("<td style='padding: 14px'><div id='div_tt' title='" + cnDvcName)
                .append("' class='easyui-panel' data-options='headerCls:\"sim-panel-header\",width:"
                        + divPaneltotalwidth + ",closable:true'")
                .append(htmlLayoutmp).append("</div></td>");
        if (tdnum % 2 == 0) {
            htmlOut.append("</tr>");
        }
    }
    if (comprehensiveSubAndColList.size() > 0) {
        request.setAttribute("title", "??");
    }
    String htmlLayout = htmlOut.toString();
    StringBuffer sb = getExportUrl(request, params, talCategory, true);
    request.setAttribute("expUrl", sb.toString());
    request.setAttribute("layout", htmlLayout);
    request.setAttribute("bean", bean);

    return "/page/report/assetStatusEvtReport";
}

From source file:com.viettel.logistic.wms.dao.InventoryResultDAO.java

public List<InventoryResultDTO> getInventoryResultByDisplayField(String inventoryActionId,
        List<String> lstShowField) {
    List<InventoryResultDTO> lstInvenResult = new ArrayList<>();
    StringBuffer sql = new StringBuffer();
    String sqlStr = "";
    ///*from w  ww  .j  a  va  2s  . c om*/
    boolean isShowAll = false;
    //create sql
    //init show file check
    boolean isShowLoaction = false;
    boolean isShowGoodsInfo = false;
    boolean isShowBincode = false;
    boolean isShowAmount = false;
    boolean isShowSerial = false;
    if (lstShowField != null && lstShowField.size() > 0) {
        for (String z : lstShowField) {
            switch (z) {
            case ParamUtils.INVENTORY_EXPORT_SHOW_FIELD.LOCATION:
                isShowLoaction = true;
                break;
            case ParamUtils.INVENTORY_EXPORT_SHOW_FIELD.GOODS_INFO:
                isShowGoodsInfo = true;
                break;
            case ParamUtils.INVENTORY_EXPORT_SHOW_FIELD.BINCODE_BARCODE:
                isShowBincode = true;
                break;
            case ParamUtils.INVENTORY_EXPORT_SHOW_FIELD.AMOUNT:
                isShowAmount = true;
                break;
            case ParamUtils.INVENTORY_EXPORT_SHOW_FIELD.SERIAL:
                isShowSerial = true;
                break;
            }
        }
    } else {
        isShowAll = true;
    }

    if (isShowAll) {
        //CREATE SQL
        sql.append(" SELECT distinct from ");
        sql.append(" a.goods_code goodsCode,");
        sql.append(" a.goods_name goodsName,");
        sql.append(" a.cell_code cellCode,");
        sql.append(" a.barcode barcode,");
        sql.append(" a.from_serial fromSerial,");
        sql.append(" a.to_serial toSerial, ");
        sql.append(" sum (a.amount) as amount ");
        sql.append(" from  inventory_result a ");
        sql.append(
                " where inventory_action_id = ? and a.type = ? group by goods_code,goods_name,cell_code,barcode,from_serial,to_serial ");
        sql.append(" order by  goods_code ");

    } else {
        boolean isHaveCondition = false;
        //
        sql.append(" SELECT distinct ");
        if (isShowGoodsInfo) {
            if (isHaveCondition) {
                sql.append(" ,a.goods_code goodsCode ");
                sql.append(" ,a.goods_name goodsName ");
            } else {
                sql.append(" a.goods_code goodsCode, ");
                sql.append(" a.goods_name goodsName ");
            }
            isHaveCondition = true;
        }
        if (isShowLoaction) {
            if (isHaveCondition) {
                sql.append(" ,a.cell_code cellCode ");
            } else {
                sql.append(" a.cell_code cellCode ");
            }
            isHaveCondition = true;
        }
        if (isShowBincode) {
            if (isHaveCondition) {
                sql.append(" ,a.barcode barcode ");
            } else {
                sql.append(" a.barcode barcode ");
            }
            isHaveCondition = true;
        }
        if (isShowSerial) {
            if (isHaveCondition) {
                sql.append(" ,a.from_serial fromSerial ");
                sql.append(" ,a.to_serial toSerial  ");
            } else {
                sql.append(" a.from_serial fromSerial, ");
                sql.append(" a.to_serial toSerial ");
            }
            isHaveCondition = true;
        }

        if (isShowAmount) {
            if (isHaveCondition) {
                sql.append(" ,sum (a.amount) as amount ");
            } else {
                sql.append(" sum (a.amount) as amount ");
            }
            isHaveCondition = true;
        }

        sql.append(" from  inventory_result a ");
        sql.append(" where inventory_action_id = ? and a.type = ? group by ");

        if (isShowGoodsInfo) {
            sql.append(" goods_code,goods_name,");
        }
        if (isShowLoaction) {
            sql.append(" cell_code,");
        }
        if (isShowBincode) {
            sql.append(" barcode,");
        }
        if (isShowSerial) {
            sql.append(" from_serial,to_serial,");
        }
        if (isShowAmount) {
            sql.append(" amount,");
        }

        sqlStr = sql.substring(0, sql.length() - 1);
        if (isShowGoodsInfo) {
            sqlStr += " order by  goods_code ";
        }
    }

    //SET PARAMETTER
    SQLQuery query = getSession().createSQLQuery(sqlStr);

    query.setResultTransformer(Transformers.aliasToBean(InventoryResultDTO.class));
    if (isShowAll) {
        query.addScalar("goodsCode", new StringType());
        query.addScalar("goodsName", new StringType());
        query.addScalar("cellCode", new StringType());
        query.addScalar("barcode", new StringType());
        query.addScalar("fromSerial", new StringType());
        query.addScalar("toSerial", new StringType());
        query.addScalar("amount", new StringType());
    } else {
        if (isShowGoodsInfo) {
            query.addScalar("goodsCode", new StringType());
            query.addScalar("goodsName", new StringType());
        }
        if (isShowLoaction) {
            query.addScalar("cellCode", new StringType());
        }
        if (isShowBincode) {
            query.addScalar("barcode", new StringType());
        }
        if (isShowSerial) {
            query.addScalar("fromSerial", new StringType());
            query.addScalar("toSerial", new StringType());
        }
        if (isShowAmount) {
            query.addScalar("amount", new StringType());
        }
    }

    int inventoryId = 0;
    try {
        inventoryId = Integer.parseInt(inventoryActionId);
    } catch (Exception e) {
    }
    //SET PARAMETER
    query.setParameter(0, inventoryId);
    query.setParameter(1, "1");
    //
    lstInvenResult = query.list();

    return lstInvenResult;
}