Example usage for java.util Set toString

List of usage examples for java.util Set toString

Introduction

In this page you can find the example usage for java.util Set toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:info.schnatterer.songbirdDbTools.commands.playlist.ExportPlaylistsCommand.java

/**
 * Exports all songbird playlists in a specific format to a specified destination folder.
 * /*from   ww w  .j  av a 2 s . co  m*/
 * @param destinationFolder
 *            the folder to write the playlist to
 * @param playlistFormat
 *            desired format for the playlist (e.g. "m3u" or "pls") if
 * @param playlistNames
 *            the names of the playlists to be exported. If <code>null</code> or empty, all playlists are exported.
 * @param useRelativePaths
 *            <code>true</code> tries to create relative paths from the playlist members to the playlist file
 * @param skipDynamicLists
 *            <code>true</code> skips dynamic playlists
 */
public void exportPlaylists(final String destinationFolder, final String playlistFormat,
        final List<String> playlistNames, final boolean useRelativePaths, final boolean skipDynamicLists) {

    // Check if playlist can be written to destination folder.
    try {
        checkDirectory(destinationFolder);
    } catch (Exception e) {
        logger.warn("Error writing playlist: " + e.getMessage(), e);
        return;
    }

    Set<String> playlistNamesSet = null;
    if (playlistNames != null && !playlistNames.isEmpty()) {
        playlistNamesSet = new HashSet<String>();
        playlistNamesSet.addAll(playlistNames);
    }

    Set<String> exportedLists = new HashSet<String>();

    try {
        List<SimpleMediaList> playlists = songbirdDb.getPlayLists(true, skipDynamicLists);
        for (SimpleMediaList simpleMediaList : playlists) {

            // String playlistName = simpleMediaList.getList().getProperty(
            // Property.PROP_MEDIA_LIST_NAME);

            // if (logger.isDebugEnabled()) {
            // // Print playlist info
            // logger.debug("Playlist: ID: "
            // + simpleMediaList.getList().getId()
            // + ": \""
            // + simpleMediaList.getList().getProperty(
            // Property.PROP_MEDIA_LIST_NAME)
            // + "\"; Type: "
            // + simpleMediaList.getList().getListType());
            // }

            // Export Playlist
            // try {
            String playlistName = simpleMediaList.getList().getProperty(Property.PROP_MEDIA_LIST_NAME);
            if (playlistName == null) {
                logger.warn("Found playlist with no name. Skipping list. " + simpleMediaList);
                continue;
            }
            if (playlistName.startsWith("&smart.defaultlist.")) {
                playlistName = playlistName.substring("&smart.defaultlist.".length());
            }
            if (playlistNamesSet != null && !playlistNamesSet.contains(playlistName)) {
                // Don't export playlist
                logger.debug("Skipping playlist \"" + playlistName + "\"");
                continue;
            }
            exportedLists.add(playlistName);
            try {
                List<String> omittedFiles = playlistExporter.export(playlistNameToFileName(playlistName),
                        getMemberPaths(simpleMediaList), destinationFolder, playlistFormat, useRelativePaths,
                        skipDynamicLists);
                String output = "Finished writing playlist " + playlistName;
                if (omittedFiles != null && omittedFiles.size() > 0) {
                    output += ". The following files were omitted because they did not exist: " + EOL;
                    output += StringUtils.join(omittedFiles, EOL);
                }
                logger.info(output);
            } catch (PlaylistExporterException e) {
                logger.warn("Error creating playlist: " + e.getMessage(), e);
            }
            // } catch (IOException e) {
            // logger.error("Unable to write playlist file", e);
            // } catch (Exception e) {
            // logger.error("Error while trying to write playlist file", e);
            // } finally {
            // try {
            // out.close();
            // } catch (IOException e) {
            // logger.error("Unable to close playlist file", e);
            // }
            // }
            // } catch (FileNotFoundException e) {
            // logger.error("Unable to open playlist file for writing",
            // e);
            // }
        }
        if (playlistNamesSet != null && !playlistNamesSet.isEmpty()) {
            playlistNamesSet.removeAll(exportedLists);
            if (!playlistNamesSet.isEmpty()) {
                logger.warn("The following playlist were not found in songbird database: "
                        + playlistNamesSet.toString());
            }
        }
    } catch (SQLException e) {
        /*
         * if the error message is "out of memory", it probably means no database file is found
         */
        logger.error("Error reading songbird database", e);
    }
}

From source file:org.egov.ptis.actions.edit.AddDemandAction.java

@Override
public void validate() {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into validate");
    final Set<Installment> newInstallments = new TreeSet<>();
    final Set<String> installmentsChqPenalty = new TreeSet<>();
    final Set<String> instDmdRsnMaster = new HashSet<>();
    List<String> instString;
    final Set<String> actAmtInstallments = new TreeSet<>();
    List<String> errorParams = null;

    for (final DemandDetail dd : demandDetailBeanList)
        if (dd.getIsNew() != null && dd.getIsNew()) {
            instString = new ArrayList<>();
            instString.add(dd.getReasonMaster());
            if ((PropertyTaxConstants.NON_VACANT_TAX_DEMAND_REASONS.contains(dd.getReasonMaster())
                    || dd.getReasonMaster().equalsIgnoreCase(DEMANDRSN_STR_VACANT_TAX))
                    && (dd.getInstallment().getId() == null || dd.getInstallment().getId().equals(-1)))
                addActionError(getText("error.editDemand.selectInstallment"));

            if (null != dd.getInstallment().getId() && !dd.getInstallment().getId().equals(-1)) {
                if (null == dd.getActualAmount())
                    addActionError(getText("error.editDemand.actualAmount", instString));
                if (null != dd.getActualAmount() && null != dd.getActualCollection()
                        && dd.getActualAmount().intValue() < dd.getActualCollection().intValue())
                    addActionError(getText("error.collection.greaterThan.actualAmount"));
            }/*  w  w  w .j  a  v a  2 s.c o  m*/

            if (dd.getActualAmount() == null) {
                if (dd.getActualCollection() != null)
                    actAmtInstallments.add(dd.getInstallment().getDescription());
            } else if (PropertyTaxConstants.NON_VACANT_TAX_DEMAND_REASONS.contains(dd.getReasonMaster())
                    || dd.getReasonMaster().equalsIgnoreCase(DEMANDRSN_STR_VACANT_TAX))
                if (dd.getInstallment().getId() == null || dd.getInstallment().getId().equals(-1))
                    addActionError(getText("error.editDemand.selectInstallment"));
                else {
                    newInstallments.add(dd.getInstallment());
                    final String instRsn = dd.getInstallment().toString().concat(ADD_TYPE_POSTFIX)
                            .concat(dd.getReasonMaster());
                    if (!instDmdRsnMaster.add(instRsn)) {
                        instString.add(dd.getInstallment().toString());
                        addActionError(getText("error.editDemand.duplicateInstallment", instString));
                    }
                }
        } else {
            newInstallments.add(dd.getInstallment());

            if (null != dd.getRevisedAmount() && dd.getRevisedAmount().compareTo(BigDecimal.ZERO) == 0
                    && dd.getActualCollection().compareTo(BigDecimal.ZERO) > 0
                    && dd.getRevisedCollection() == null) {
                errorParams = new ArrayList<>();
                errorParams.add(dd.getReasonMaster());
                errorParams.add(dd.getInstallment().getDescription());
                addActionError(getText("error.editDemand.collectionForUpdatedDemand", errorParams));
            }
            if (null != dd.getRevisedAmount() && null != dd.getActualCollection()
                    && dd.getRevisedAmount().intValue() < dd.getActualCollection().intValue())
                addActionError(getText("error.collection.greaterThan.revisedAmount"));
            if (null != dd.getRevisedAmount() && null != dd.getRevisedCollection()
                    && dd.getRevisedAmount().intValue() < dd.getRevisedCollection().intValue())
                addActionError(getText("error.revisedCollecion.greaterThan.revisedAmount"));
        }

    if (!actAmtInstallments.isEmpty()) {
        final String inst = actAmtInstallments.toString().replace('[', ' ').replace(']', ' ');
        final List<String> instStrings = new ArrayList<>();
        instStrings.add(inst);
        addActionError(getText("error.editDemand.actualAmount", instStrings));
    }

    List<Installment> installmentsInOrder = null;
    if (!newInstallments.isEmpty()) {
        installmentsInOrder = propertyTaxUtil.getInstallmentListByStartDateToCurrFinYearDesc(
                new ArrayList<Installment>(newInstallments).get(0).getFromDate());

        if (newInstallments.size() != installmentsInOrder.size())
            addActionError(getText("error.editDemand.badInstallmentSelection"));

        final Date currDate = new Date();
        final Map<String, Installment> currYearInstMap = propertyTaxUtil.getInstallmentsForCurrYear(currDate);
        if (!DateUtils.compareDates(currDate, currYearInstMap.get(CURRENTYEAR_SECOND_HALF).getFromDate())) {
            if (newInstallments.contains(currYearInstMap.get(CURRENTYEAR_FIRST_HALF))
                    && !newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF))
                    || !newInstallments.contains(currYearInstMap.get(CURRENTYEAR_FIRST_HALF))
                            && newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF)))
                addActionError(getText("error.currentyearinstallments"));
        } else if (!newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF)))
            addActionError(getText("error.currentInst"));

    }

    if (!installmentsChqPenalty.isEmpty()) {
        final String inst = installmentsChqPenalty.toString().replace('[', ' ').replace(']', ' ');
        final List<String> instStrings = new ArrayList<>();
        instStrings.add(inst);
        addActionError(getText("error.editDemand.chqBouncePenaltyIsZero", instStrings));
    }

    if (StringUtils.isBlank(remarks))
        addActionError(getText("mandatory.editDmdCollRemarks"));
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exiting from validate");
}

From source file:org.egov.ptis.actions.edit.EditDemandAction.java

@Override
public void validate() {
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Entered into validate");

    final Set<Installment> newInstallments = new TreeSet<>();
    final Set<String> installmentsChqPenalty = new TreeSet<>();
    final Set<String> instDmdRsnMaster = new HashSet<>();
    List<String> instString;
    final Set<String> actAmtInstallments = new TreeSet<>();
    List<String> errorParams = null;

    for (final DemandDetail dd : demandDetailBeanList)
        if (dd.getIsNew() != null && dd.getIsNew()) {
            instString = new ArrayList<>();
            instString.add(dd.getReasonMaster());
            if ((PropertyTaxConstants.NON_VACANT_TAX_DEMAND_CODES.contains(dd.getReasonMaster())
                    || dd.getReasonMaster().equalsIgnoreCase(DEMANDRSN_STR_VACANT_TAX))
                    && (dd.getInstallment().getId() == null || dd.getInstallment().getId().equals(-1)))
                addActionError(getText("error.editDemand.selectInstallment"));

            if (null != dd.getInstallment().getId() && !dd.getInstallment().getId().equals(-1)) {
                if (null == dd.getActualAmount())
                    addActionError(getText("error.editDemand.actualAmount", instString));
                if (null != dd.getActualAmount() && null != dd.getActualCollection()
                        && dd.getActualAmount().intValue() < dd.getActualCollection().intValue())
                    addActionError(getText("error.collection.greaterThan.actualAmount"));
            }/*from w w w.j a  v a 2 s . c om*/

            if (dd.getActualAmount() == null) {
                if (dd.getActualCollection() != null)
                    actAmtInstallments.add(dd.getInstallment().getDescription());
            } else if (PropertyTaxConstants.NON_VACANT_TAX_DEMAND_CODES.contains(dd.getReasonMaster())
                    || dd.getReasonMaster().equalsIgnoreCase(DEMANDRSN_STR_VACANT_TAX))
                if (dd.getInstallment().getId() == null || dd.getInstallment().getId().equals(-1))
                    addActionError(getText("error.editDemand.selectInstallment"));
                else {
                    newInstallments.add(dd.getInstallment());
                    final String instRsn = dd.getInstallment().toString().concat(EDIT_TYPE_POSTFIX)
                            .concat(dd.getReasonMaster());
                    if (!instDmdRsnMaster.add(instRsn)) {
                        instString.add(dd.getInstallment().toString());
                        addActionError(getText("error.editDemand.duplicateInstallment", instString));
                    }
                }
        } else {
            newInstallments.add(dd.getInstallment());

            if (null != dd.getRevisedAmount() && dd.getRevisedAmount().compareTo(BigDecimal.ZERO) == 0
                    && dd.getActualCollection().compareTo(BigDecimal.ZERO) > 0
                    && dd.getRevisedCollection() == null) {
                errorParams = new ArrayList<>();
                errorParams.add(dd.getReasonMaster());
                errorParams.add(dd.getInstallment().getDescription());
                addActionError(getText("error.editDemand.collectionForUpdatedDemand", errorParams));
            }
            if (null != dd.getRevisedAmount() && null != dd.getActualCollection()
                    && dd.getRevisedAmount().intValue() < dd.getActualCollection().intValue())
                addActionError(getText("error.collection.greaterThan.revisedAmount"));
            if (null != dd.getRevisedAmount() && null != dd.getRevisedCollection()
                    && dd.getRevisedAmount().intValue() < dd.getRevisedCollection().intValue())
                addActionError(getText("error.revisedCollecion.greaterThan.revisedAmount"));
        }

    if (!actAmtInstallments.isEmpty()) {
        final String inst = actAmtInstallments.toString().replace('[', ' ').replace(']', ' ');
        List<String> instStrings = new ArrayList<>();
        instStrings.add(inst);
        addActionError(getText("error.editDemand.actualAmount", instStrings));
    }

    List<Installment> installmentsInOrder = null;
    if (!newInstallments.isEmpty()) {
        installmentsInOrder = propertyTaxUtil.getInstallmentListByStartDateToCurrFinYearDesc(
                new ArrayList<Installment>(newInstallments).get(0).getFromDate());

        if (newInstallments.size() != installmentsInOrder.size())
            addActionError(getText("error.editDemand.badInstallmentSelection"));

        final Date currDate = new Date();
        final Map<String, Installment> currYearInstMap = propertyTaxUtil.getInstallmentsForCurrYear(currDate);
        if (!DateUtils.compareDates(currDate, currYearInstMap.get(CURRENTYEAR_SECOND_HALF).getFromDate())) {
            if (newInstallments.contains(currYearInstMap.get(CURRENTYEAR_FIRST_HALF))
                    && !newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF))
                    || !newInstallments.contains(currYearInstMap.get(CURRENTYEAR_FIRST_HALF))
                            && newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF)))
                addActionError(getText("error.currentyearinstallments"));
        } else if (!newInstallments.contains(currYearInstMap.get(CURRENTYEAR_SECOND_HALF)))
            addActionError(getText("error.currentInst"));

    }

    if (!installmentsChqPenalty.isEmpty()) {
        final String inst = installmentsChqPenalty.toString().replace('[', ' ').replace(']', ' ');
        final List<String> instStrings = new ArrayList<>();
        instStrings.add(inst);
        addActionError(getText("error.editDemand.chqBouncePenaltyIsZero", instStrings));
    }

    if (StringUtils.isBlank(remarks))
        addActionError(getText("mandatory.editDmdCollRemarks"));
    if (LOGGER.isDebugEnabled())
        LOGGER.debug("Exiting from validate");
}

From source file:com.dell.asm.asmcore.asmmanager.util.deployment.NetworkingUtil.java

private void reserveIP(String usageGuid, Network network, IIPAddressPoolMgr ipAddressPoolMgr,
        Map<String, Network> processedNetworks, List<Network> reservedNetworks, boolean skipDHCP,
        final Integer[] portsToPing) throws WebApplicationException {
    // Track the ips that are occupied by other machiens and clear them from the db at the end
    Set<String> ipsToBeReleased = new HashSet<>();

    try {//from   w w  w . ja  v  a  2  s.  com
        if (network.isStatic() && network.getStaticNetworkConfiguration() != null
                && StringUtils.isEmpty(network.getStaticNetworkConfiguration().getIpAddress())) {
            Set<String> ips;
            if (processedNetworks.get(network.getName()) == null) {
                ips = ipAddressPoolMgr.assignIPAddresses(network.getId(), usageGuid, 1);
                if (ips == null || ips.size() != 1) {
                    throw new AsmManagerRuntimeException("Failed to assign ip address for network "
                            + network.getId() + " usageGuid = " + usageGuid);
                }
                String ip = ips.toArray(new String[1])[0];
                // Storage networks are not expected to be routable, so we do not attempt to connect to those IPs
                if (!NetworkType.STORAGE_ISCSI_SAN.equals(network.getType())
                        && !NetworkType.STORAGE_FCOE_SAN.equals(network.getType())) {
                    while (pingUtil.isReachable(ip, portsToPing)) {
                        logger.warn("Tried to reserve " + ip + ", but it is occupied by another machine.");
                        logService.logMsg(AsmManagerMessages.ipAddressInUse(ip), LogMessage.LogSeverity.WARNING,
                                LogMessage.LogCategory.DEPLOYMENT);
                        ipsToBeReleased.add(ip);
                        ips = ipAddressPoolMgr.assignIPAddresses(network.getId(), usageGuid, 1);
                        if (ips == null || ips.size() != 1) {
                            throw new AsmManagerRuntimeException("Failed to assign ip address for network "
                                    + network.getId() + " usageGuid = " + usageGuid);
                        }
                        ip = ips.toArray(new String[1])[0];
                    }
                }
                network.getStaticNetworkConfiguration().setIpAddress(ip);
                processedNetworks.put(network.getName(), network);
                reservedNetworks.add(network);
            } else {
                Network reservedNetwork = processedNetworks.get(network.getName());
                network.getStaticNetworkConfiguration()
                        .setIpAddress(reservedNetwork.getStaticNetworkConfiguration().getIpAddress());
            }
        } else if (!skipDHCP) {
            // skip dchp networks for network scale up
            reservedNetworks.add(network);
        }
    } catch (AsmRuntimeException e) {
        logger.error("Exception while reserving IPs.", e);
        if (IdentityPoolMgrMessageCode.IPPOOL_ENOUGH_IPADRESS_NOT_AVAILABLE.getCode()
                .equals(e.getEEMILocalizableMessage().getDisplayMessage().getMessageCode())) {
            throw new LocalizedWebApplicationException(Response.Status.BAD_REQUEST,
                    AsmManagerMessages.notEnoughIPs(network.getName()));
        } else {
            throw new LocalizedWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                    AsmManagerMessages.internalError());
        }

    } catch (Exception e) {
        logger.error("Exception while reserving IPs.", e);
        throw new LocalizedWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR,
                AsmManagerMessages.internalError());
    } finally {
        if (ipsToBeReleased.size() > 0) {
            logger.debug("Releasing the following IP addresses from the db: " + ipsToBeReleased.toString());
            ipAddressPoolMgr.releaseIPAddresses(ipsToBeReleased, network.getId());
        }
    }
}

From source file:org.etudes.jforum.view.admin.ImportExportAction.java

/**
 * Generate organization and resuore items
 * /*from w  w  w  .j av a2 s .co m*/
 * @param catgForums
 *            - category list
 * @param packagedir
 *            - packaging directory
 * @return list of organization and resource items
 * @throws Exception
 */
private List<Element> generateOrganizationResourceItems(List<org.etudes.api.app.jforum.Category> catgForums,
        File packagedir) throws Exception {
    try {
        String packagedirpath = packagedir.getAbsolutePath();
        String resourcespath = packagedirpath + File.separator + "resources";
        File resoucesDir = new File(resourcespath);
        if (!resoucesDir.exists())
            resoucesDir.mkdir();

        Element organizations = createOrganizations();
        Element resources = createResources();

        Element organization = addOrganization(organizations);

        organizations.addAttribute("default", organization.attributeValue("identifier"));

        Iterator<org.etudes.api.app.jforum.Category> catgForumsIter = catgForums.iterator();
        org.etudes.api.app.jforum.Category category = null;
        int i = 0, j = 0, k = 0;
        // create item for each category and items under the category item
        // for
        // forums and items for task topics under forum items
        while (catgForumsIter.hasNext()) {
            category = catgForumsIter.next();

            /*if (category.isArchived())
               continue;*/

            // add category element
            Element catMainItem = organization.addElement("item");
            catMainItem.addAttribute("identifier", "MF01_ORG1_JFORUM_CATG" + ++i);

            // add category grade if category is gradable
            StringBuffer categoryParameters = new StringBuffer();

            if (category.isGradable()) {
                categoryParameters.append("&gradetype=");
                categoryParameters.append(Forum.GRADE_BY_CATEGORY);

                //Grade catGrade = DataAccessDriver.getInstance().newGradeDAO().selectByCategoryId(category.getId());
                org.etudes.api.app.jforum.Grade catGrade = category.getGrade();

                categoryParameters.append("&gradepoints=");
                categoryParameters.append(catGrade.getPoints().toString());

                categoryParameters.append("&addtogradebook=");
                categoryParameters.append((catGrade.isAddToGradeBook()) ? "1" : "0");

                if (catGrade.isMinimumPostsRequired()) {
                    categoryParameters.append("&minpostsrequired=1");

                    categoryParameters.append("&minposts=");
                    categoryParameters.append(catGrade.getMinimumPosts());
                } else {
                    categoryParameters.append("&minpostsrequired=0");

                    categoryParameters.append("&minposts=");
                    categoryParameters.append(catGrade.getMinimumPosts());
                }
            }

            // open date
            if (category.getAccessDates().getOpenDate() != null) {
                categoryParameters.append("&startdate=");
                SimpleDateFormat df = new SimpleDateFormat(
                        SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                String startDateStr = df.format(category.getAccessDates().getOpenDate());

                categoryParameters.append(startDateStr);

                categoryParameters.append("&hideuntilopen=");
                categoryParameters.append((category.getAccessDates().isHideUntilOpen() ? 1 : 0));
            }

            // due date
            if (category.getAccessDates().getDueDate() != null) {
                categoryParameters.append("&enddate=");

                SimpleDateFormat df = new SimpleDateFormat(
                        SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                String endDateStr = df.format(category.getAccessDates().getDueDate());

                categoryParameters.append(endDateStr);

                /*categoryParameters.append("&lockenddate=");
                categoryParameters.append((category.getAccessDates().isLocked() ? 1 : 0));*/
            }

            // allow until date
            if (category.getAccessDates().getAllowUntilDate() != null) {
                categoryParameters.append("&allowuntildate=");
                SimpleDateFormat df = new SimpleDateFormat(
                        SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                String allowUntilDateStr = df.format(category.getAccessDates().getAllowUntilDate());

                categoryParameters.append(allowUntilDateStr);
            }

            if (categoryParameters.length() > 0) {
                String catgParams = categoryParameters.toString();
                catMainItem.addAttribute("parameters", catgParams.substring(1));
            }

            Element title = catMainItem.addElement("title");
            if (category.getTitle() != null && category.getTitle().trim().length() > 0) {
                title.setText(category.getTitle());
            }

            Collection<org.etudes.api.app.jforum.Forum> forums = (Collection<org.etudes.api.app.jforum.Forum>) category
                    .getForums();
            if (forums != null && forums.size() > 0) {
                Iterator<org.etudes.api.app.jforum.Forum> forumIter = forums.iterator();
                org.etudes.api.app.jforum.Forum forum = null;
                // create items and resources for forum and it's task topics
                while (forumIter.hasNext()) {
                    forum = forumIter.next();

                    // add forum element
                    Element forumElement = null;
                    forumElement = catMainItem.addElement("item");
                    forumElement.addAttribute("identifier", "FORUMITEM" + ++k);
                    // add attribute "parameters" for forum type and access
                    // type
                    StringBuffer forumParameters = new StringBuffer();

                    forumParameters.append("forumtype=");
                    forumParameters.append(forum.getType());
                    forumParameters.append("&accesstype=");
                    if (forum.getAccessType() == Forum.ACCESS_GROUPS)
                        forumParameters.append("0");
                    else
                        forumParameters.append(forum.getAccessType());

                    if (forum.getGradeType() == Forum.GRADE_BY_FORUM) {
                        //Grade grade = DataAccessDriver.getInstance().newGradeDAO().selectByForumId(forum.getId());
                        org.etudes.api.app.jforum.Grade grade = forum.getGrade();

                        if (grade != null) {
                            forumParameters.append("&gradetype=");
                            forumParameters.append(forum.getGradeType());

                            forumParameters.append("&gradepoints=");
                            forumParameters.append(grade.getPoints().toString());

                            forumParameters.append("&addtogradebook=");
                            forumParameters.append((grade.isAddToGradeBook()) ? "1" : "0");

                            if (grade.isMinimumPostsRequired()) {
                                forumParameters.append("&minpostsrequired=1");

                                forumParameters.append("&minposts=");
                                forumParameters.append(grade.getMinimumPosts());
                            } else {
                                forumParameters.append("&minpostsrequired=0");

                                forumParameters.append("&minposts=");
                                forumParameters.append(grade.getMinimumPosts());
                            }
                        }
                    } else if (forum.getGradeType() == Forum.GRADE_BY_TOPIC) {
                        forumParameters.append("&gradetype=");
                        forumParameters.append(forum.getGradeType());
                    }

                    // start date
                    if (forum.getAccessDates().getOpenDate() != null) {
                        forumParameters.append("&startdate=");
                        SimpleDateFormat df = new SimpleDateFormat(
                                SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                        String startDateStr = df.format(forum.getAccessDates().getOpenDate());

                        forumParameters.append(startDateStr);

                        forumParameters.append("&hideuntilopen=");
                        forumParameters.append((forum.getAccessDates().isHideUntilOpen() ? 1 : 0));
                    }

                    // due date
                    if (forum.getAccessDates().getDueDate() != null) {
                        forumParameters.append("&enddate=");

                        SimpleDateFormat df = new SimpleDateFormat(
                                SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                        String endDateStr = df.format(forum.getAccessDates().getDueDate());

                        forumParameters.append(endDateStr);

                        /*forumParameters.append("&lockenddate=");
                        forumParameters.append((forum.getAccessDates().isLocked() ? 1 : 0));*/
                    }

                    // allow until date
                    if (forum.getAccessDates().getAllowUntilDate() != null) {
                        forumParameters.append("&allowuntildate=");
                        SimpleDateFormat df = new SimpleDateFormat(
                                SakaiSystemGlobals.getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                        String allowUntilDateStr = df.format(forum.getAccessDates().getAllowUntilDate());

                        forumParameters.append(allowUntilDateStr);
                    }

                    forumElement.addAttribute("parameters", forumParameters.toString());
                    Element forumTitleEle = forumElement.addElement("title");
                    forumTitleEle.setText(forum.getName());

                    //TopicDAO tm = DataAccessDriver.getInstance().newTopicDAO();
                    //List topics = tm.selectAllByForum(forum.getId());
                    JForumPostService jforumPostService = (JForumPostService) ComponentManager
                            .get("org.etudes.api.app.jforum.JForumPostService");
                    List<org.etudes.api.app.jforum.Topic> topics = jforumPostService
                            .getForumTopics(forum.getId());

                    /* topics */
                    org.etudes.api.app.jforum.Topic topic = null;
                    if (topics != null && topics.size() > 0) {
                        Iterator<org.etudes.api.app.jforum.Topic> topicIter = topics.iterator();

                        // create items and resources for task topics
                        while (topicIter.hasNext()) {
                            topic = topicIter.next();
                            /*
                             * 10/16/08 Murthy Topic type 1 was task topic.
                             * As task topic is changed to export topic task
                             * topic support code is added add topic element
                             * for exportable topic.
                             */
                            if (topic.isExportTopic() || topic.getType() == 1) {
                                if (forumElement != null) {
                                    Element topicElement = forumElement.addElement("item");
                                    topicElement.addAttribute("identifier", "TOPICITEM" + ++k);

                                    // params
                                    StringBuffer topicParameters = new StringBuffer();
                                    topicParameters.append("topictype=");
                                    /*
                                     * 10/16/08 Murthy Topic type 1 was task
                                     * topic. As task topic is changed to
                                     * export topic task topic support code
                                     * is added
                                     */
                                    if (topic.getType() == 1)
                                        topicParameters.append(0);
                                    else
                                        topicParameters.append(topic.getType());

                                    if (forum.getGradeType() == Forum.GRADE_BY_TOPIC && topic.isGradeTopic()) {
                                        //Grade topicGrade = DataAccessDriver.getInstance().newGradeDAO().selectByForumTopicId(forum.getId(), topic.getId());
                                        org.etudes.api.app.jforum.Grade topicGrade = topic.getGrade();

                                        if (topicGrade != null) {
                                            topicParameters.append("&gradetopic=");
                                            topicParameters.append(Topic.GRADE_YES);

                                            topicParameters.append("&gradepoints=");
                                            topicParameters.append(topicGrade.getPoints().toString());

                                            topicParameters.append("&addtogradebook=");
                                            topicParameters.append((topicGrade.isAddToGradeBook()) ? "1" : "0");

                                            if (topicGrade.isMinimumPostsRequired()) {
                                                topicParameters.append("&minpostsrequired=1");

                                                topicParameters.append("&minposts=");
                                                topicParameters.append(topicGrade.getMinimumPosts());
                                            } else {
                                                topicParameters.append("&minpostsrequired=0");

                                                topicParameters.append("&minposts=");
                                                topicParameters.append(topicGrade.getMinimumPosts());
                                            }
                                        }
                                    }

                                    if (topic.getAccessDates().getOpenDate() != null) {
                                        topicParameters.append("&startdate=");
                                        SimpleDateFormat df = new SimpleDateFormat(SakaiSystemGlobals
                                                .getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                                        String startDateStr = df.format(topic.getAccessDates().getOpenDate());

                                        topicParameters.append(startDateStr);

                                        topicParameters.append("&hideuntilopen=");
                                        topicParameters
                                                .append((topic.getAccessDates().isHideUntilOpen() ? 1 : 0));
                                    }

                                    if (topic.getAccessDates().getDueDate() != null) {
                                        topicParameters.append("&enddate=");

                                        SimpleDateFormat df = new SimpleDateFormat(SakaiSystemGlobals
                                                .getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                                        String endDateStr = df.format(topic.getAccessDates().getDueDate());

                                        topicParameters.append(endDateStr);

                                        /*topicParameters.append("&lockenddate=");
                                        topicParameters.append((topic.getAccessDates().isLocked() ? 1 : 0));*/
                                    }

                                    // allow until date
                                    if (topic.getAccessDates().getAllowUntilDate() != null) {
                                        topicParameters.append("&allowuntildate=");
                                        SimpleDateFormat df = new SimpleDateFormat(SakaiSystemGlobals
                                                .getValue(ConfigKeys.CALENDAR_DATE_TIME_FORMAT));
                                        String allowUntilDateStr = df
                                                .format(topic.getAccessDates().getAllowUntilDate());

                                        topicParameters.append(allowUntilDateStr);
                                    }

                                    topicElement.addAttribute("parameters", topicParameters.toString());

                                    Element topicTitleEle = topicElement.addElement("title");
                                    topicTitleEle.setText(topic.getTitle());

                                    int firstPostId = topic.getFirstPostId();
                                    //PostDAO pm = DataAccessDriver.getInstance().newPostDAO();
                                    //Post p = pm.selectById(firstPostId);
                                    org.etudes.api.app.jforum.Post p = jforumPostService.getPost(firstPostId);

                                    /* add topic resource */
                                    Element topicResource = resources.addElement("resource");
                                    topicResource.addAttribute("identifier", "RESOURCE" + ++j);
                                    topicResource.addAttribute("type ", "webcontent");

                                    topicElement.addAttribute("identifierref",
                                            topicResource.attributeValue("identifier"));

                                    // create the file for first post text
                                    File resfile = new File(resoucesDir + "/post_" + p.getId() + ".html");

                                    // process cross references. harvest post text embedded references
                                    Set<String> refs = XrefHelper.harvestEmbeddedReferences(p.getText(), null);

                                    if (logger.isDebugEnabled())
                                        logger.debug(
                                                "processTopic(): embed references found:" + refs.toString());

                                    String modifiedText = null;

                                    if (p.getText() == null) {
                                        p.setText("");
                                    }

                                    if (refs != null && refs.size() > 0) {
                                        modifiedText = updateEmbeddedReferenceUrls(p.getText(), refs,
                                                resoucesDir);

                                        createFileFromContent(modifiedText, resfile.getAbsolutePath());
                                    } else
                                        createFileFromContent(p.getText(), resfile.getAbsolutePath());

                                    Element file = topicResource.addElement("file");
                                    file.addAttribute("href", "resources/post_" + p.getId() + ".html");
                                    topicResource.addAttribute("href", "resources/post_" + p.getId() + ".html");

                                    // create file for attachments if any
                                    // with first post
                                    if (p.hasAttachments()) {
                                        //List attachments = DataAccessDriver.getInstance().newAttachmentDAO().selectAttachments(p.getId());
                                        List<org.etudes.api.app.jforum.Attachment> attachments = p
                                                .getAttachments();

                                        if (attachments != null && attachments.size() > 0) {
                                            for (Iterator<org.etudes.api.app.jforum.Attachment> iter = attachments
                                                    .iterator(); iter.hasNext();) {
                                                org.etudes.api.app.jforum.Attachment attachment = iter.next();
                                                String realFileName = attachment.getInfo().getRealFilename()
                                                        .replaceAll("\\s+", "_");
                                                File resAttachfile = new File(resoucesDir + "/post_" + p.getId()
                                                        + "_" + realFileName);

                                                // String fileLoc = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/"
                                                String fileLoc = SakaiSystemGlobals
                                                        .getValue(ConfigKeys.ATTACHMENTS_STORE_DIR) + "/"
                                                        + attachment.getInfo().getPhysicalFilename();

                                                if (!new File(fileLoc).exists()) {
                                                    if (logger.isErrorEnabled())
                                                        logger.error(this.getClass().getName()
                                                                + ". generateOrganizationResourceItems() : "
                                                                + fileLoc + " doesn't exist.");
                                                    continue;
                                                }
                                                createFile(fileLoc, resAttachfile.getAbsolutePath());

                                                Element attchFileEle = topicResource.addElement("file");

                                                // file description
                                                String attchmentComment = attachment.getInfo().getComment();
                                                if (attchmentComment != null
                                                        && attchmentComment.trim().length() > 0) {
                                                    Element imsmdlom = createLOMElement("imsmd:lom", "lom");
                                                    Element imsmdgeneral = imsmdlom.addElement("imsmd:general");
                                                    imsmdgeneral.add(
                                                            createMetadataDescription(attchmentComment.trim()));
                                                    attchFileEle.add(imsmdlom);
                                                }

                                                attchFileEle.addAttribute("href",
                                                        "resources/post_" + p.getId() + "_" + realFileName);
                                            }
                                        }
                                    }

                                    /*
                                     * add meta data to topic resource
                                     * element - for topic subject - as
                                     * metadata title - subject is same as
                                     * topic title
                                     */
                                    if (p.getSubject() != null && p.getSubject().trim().length() > 0) {
                                        Element imsmdlom = createLOMElement("imsmd:lom", "lom");
                                        Element imsmdgeneral = imsmdlom.addElement("imsmd:general");
                                        imsmdgeneral.add(createMetadataTitle(p.getSubject()));
                                        topicResource.add(imsmdlom);
                                    }
                                }
                            }
                        }
                    }

                    // metadata to capture forum description
                    if (forum.getDescription() != null && forum.getDescription().trim().length() > 0) {
                        Element imsmdlom = createLOMElement("imsmd:lom", "lom");
                        Element imsmdgeneral = imsmdlom.addElement("imsmd:general");
                        imsmdgeneral.add(createMetadataDescription(forum.getDescription().trim()));
                        forumElement.add(imsmdlom);
                    }
                }

            }
        }
        ArrayList manElements = new ArrayList();
        manElements.add(organizations);
        manElements.add(resources);

        return manElements;

    } catch (Exception e) {
        throw e;
    }
}

From source file:org.ojbc.intermediaries.sn.dao.SubscriptionSearchQueryDAO.java

/**
 * Create a subscription (or update an existing one) given the input parameters
 * @param subscriptionSystemId//from  w  w  w .  j  a va 2  s .  c o  m
 * @param topic
 * @param startDateString
 * @param endDateString
 * @param subjectIds
 * @param emailAddresses
 * @param offenderName
 * @param subscribingSystemId
 * @param subscriptionQualifier
 * @param reasonCategoryCode
 * @param subscriptionOwner
 * @return the ID of the created (or updated) subscription
 */
public Number subscribe(String subscriptionSystemId, String topic, String startDateString, String endDateString,
        Map<String, String> subjectIds, Set<String> emailAddresses, String offenderName,
        String subscribingSystemId, String subscriptionQualifier, String reasonCategoryCode,
        String subscriptionOwner, LocalDate creationDateTime, String agencyCaseNumber) {

    Number ret = null;

    log.debug("Entering subscribe method");

    // Use the current time as the start date
    Date startDate = null;
    Date endDate = null;

    // If start date is not provided in the subscription message, use current date
    if (StringUtils.isNotBlank(startDateString)) {
        // Create SQL date from the end date string
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        try {
            java.util.Date utilStartDate = formatter.parse(startDateString.trim());
            startDate = new Date(utilStartDate.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    } else {
        startDate = new Date(System.currentTimeMillis());
    }

    // Many subscription message will not have end dates so we will need to
    // allow nulls
    if (StringUtils.isNotBlank(endDateString)) {
        // Create SQL date from the end date string
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

        try {
            java.util.Date utilEndDate = formatter.parse(endDateString.trim());
            endDate = new Date(utilEndDate.getTime());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    java.util.Date creationDate = creationDateTime.toDateTimeAtStartOfDay().toDate();

    log.debug("Start Date String: " + startDateString);
    log.debug("End Date String: " + endDateString);
    log.debug("System Name: " + subscribingSystemId);
    log.debug("Subscription System ID: " + subscriptionSystemId);

    log.info("\n\n\n reasonCategoryCode = " + reasonCategoryCode + "\n\n\n");
    if (StringUtils.isEmpty(reasonCategoryCode)) {
        log.warn("\n\n\n reasonCategoryCode empty, so inserting null into db \n\n\n");
        reasonCategoryCode = null;
    }

    String fullyQualifiedTopic = NotificationBrokerUtils.getFullyQualifiedTopic(topic);

    List<Subscription> subscriptions = getSubscriptions(subscriptionSystemId, fullyQualifiedTopic, subjectIds,
            subscribingSystemId, subscriptionOwner);

    // No Record exist, insert a new one
    if (subscriptions.size() == 0) {

        log.debug("No subscriptions exist, inserting new one");

        log.debug("Inserting row into subscription table");

        KeyHolder keyHolder = new GeneratedKeyHolder();
        this.jdbcTemplate.update(buildPreparedInsertStatementCreator(
                "insert into subscription (topic, startDate, endDate, subscribingSystemIdentifier, subscriptionOwner, subjectName, active, subscription_category_code, lastValidationDate, agency_case_number) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                new Object[] { fullyQualifiedTopic.trim(), startDate, endDate, subscribingSystemId.trim(),
                        subscriptionOwner, offenderName.trim(), 1, reasonCategoryCode, creationDate,
                        agencyCaseNumber }),
                keyHolder);

        ret = keyHolder.getKey();
        log.debug("Inserting row into notification_mechanism table");

        for (String emailAddress : emailAddresses) {
            this.jdbcTemplate.update(
                    "insert into notification_mechanism (subscriptionId, notificationMechanismType, notificationAddress) values (?,?,?)",
                    keyHolder.getKey(), NotificationConstants.NOTIFICATION_MECHANISM_EMAIL, emailAddress);
        }

        log.debug("Inserting row(s) into subscription_subject_identifier table");

        for (Map.Entry<String, String> entry : subjectIds.entrySet()) {
            this.jdbcTemplate.update(
                    "insert into subscription_subject_identifier (subscriptionId, identifierName, identifierValue) values (?,?,?)",
                    keyHolder.getKey(), entry.getKey(), entry.getValue());
        }
    }

    // A subscriptions exists, let's update it
    if (subscriptions.size() == 1) {
        log.debug("Ensure that SIDs match before updating subscription");

        log.debug("Updating existing subscription");
        log.debug("Subject Id Map: " + subjectIds);
        log.debug("Email Addresses: " + emailAddresses.toString());

        log.debug("Updating row in subscription table");

        this.jdbcTemplate.update(
                "update subscription set topic=?, startDate=?, endDate=?, subjectName=?, active=1, subscriptionOwner=?, lastValidationDate=? where id=?",
                new Object[] { fullyQualifiedTopic.trim(), startDate, endDate, offenderName.trim(),
                        subscriptionOwner, creationDate, subscriptions.get(0).getId() });

        log.debug("Updating row in notification_mechanism table");

        // We will delete all email addresses associated with the subscription and re-add them
        this.jdbcTemplate.update("delete from notification_mechanism where subscriptionId = ?",
                new Object[] { subscriptions.get(0).getId() });

        for (String emailAddress : emailAddresses) {
            this.jdbcTemplate.update(
                    "insert into notification_mechanism (subscriptionId, notificationMechanismType, notificationAddress) values (?,?,?)",
                    subscriptions.get(0).getId(), NotificationConstants.NOTIFICATION_MECHANISM_EMAIL,
                    emailAddress);
        }

        ret = subscriptions.get(0).getId();

    }

    if (ret != null && CIVIL_SUBSCRIPTION_REASON_CODE.equals(reasonCategoryCode)) {
        subscribeIdentificationTransaction(ret, agencyCaseNumber, endDateString);
    }

    return ret;

}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * Internal method to check if the batch class is viewable to the logged in user.
 * /*from www.  j a va  2s  . c om*/
 * @param batchClassId {@link String}
 * @param loggedInUserRole Set<String>
 * @param isSuperAdmin boolean
 * @return boolean
 */
private boolean isBatchClassViewableToUser(final String batchClassId, Set<String> loggedInUserRole,
        boolean isSuperAdmin) {
    LOGGER.info("Starting \"isBatchClassViewableToUser\" service for batch class id:" + batchClassId);
    List<BatchClass> batchClasses = null;
    if (isSuperAdmin) {
        LOGGER.info("Getting all batch classes.");
        batchClasses = bcService.getAllBatchClasses();
    } else {
        LOGGER.info("Getting batch classes by user roles.");
        batchClasses = bcService.getAllBatchClassesByUserRoles(loggedInUserRole);
    }
    boolean isBatchClassViewableToUser = false;
    for (BatchClass batchClass : batchClasses) {
        if (batchClass.getIdentifier().equalsIgnoreCase(batchClassId)) {
            isBatchClassViewableToUser = true;
            break;
        }
    }
    LOGGER.info("isBatchClassViewableToUser:" + isBatchClassViewableToUser + " Batch Class id:" + batchClassId
            + " logged in user role:" + loggedInUserRole.toString());
    LOGGER.info("isSuperAdmin Flag value:" + isSuperAdmin);
    return isBatchClassViewableToUser;
}

From source file:com.ephesoft.dcma.webservice.EphesoftWebServiceAPI.java

/**
 * To restart Batch Instance.//from w  w  w . j  av a 2s . co m
 * @param identifier {@link String}
 * @param moduleName {@link String}
 * @param resp {@link HttpServletResponse}
 * @param req {@link HttpServletRequest}
 * @return {@link String}
 */
@RequestMapping(value = "/restartBatchInstance/{batchInstanceIdentifier}/{restartAtModuleName}", method = RequestMethod.GET)
@ResponseBody
public String restartBatchInstance(@PathVariable("batchInstanceIdentifier") final String identifier,
        @PathVariable("restartAtModuleName") String moduleName, final HttpServletResponse resp,
        final HttpServletRequest req) {
    LOGGER.info("Start processing web service for restart batch instance");
    boolean isSuccess = false;
    String moduleNameLocal = moduleName;
    Set<String> loggedInUserRole = getUserRoles(req);
    String respStr = WebServiceUtil.EMPTY_STRING;
    if (identifier != null && !identifier.isEmpty()) {
        LOGGER.info("Start processing of restarting batch for batch instance:" + identifier);
        BatchInstance batchInstance = biService.getBatchInstanceByIdentifier(identifier);
        // only batch instance with these status can be restarted
        if (batchInstance != null && (batchInstance.getStatus().equals(BatchInstanceStatus.ERROR)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_REVIEW)
                || batchInstance.getStatus().equals(BatchInstanceStatus.READY_FOR_VALIDATION)
                || batchInstance.getStatus().equals(BatchInstanceStatus.RUNNING))) {
            LOGGER.info("Batch is in the valid state to restart.Restarting batch instance:" + batchInstance);

            Set<String> batchInstanceRoles = biService.getRolesForBatchInstance(batchInstance);
            if (isSuperAdmin(req) || batchInstanceRoles.removeAll(loggedInUserRole)) {
                LOGGER.info("User is authorized to perform operation on the batch instance:" + identifier);
                final String batchClassIdentifier = biService.getBatchClassIdentifier(identifier);
                String executedBatchInstanceModules = batchInstance.getExecutedModules();
                if (executedBatchInstanceModules != null) {
                    String[] executedModulesArray = executedBatchInstanceModules.split(";");
                    if (batchClassIdentifier != null) {
                        LOGGER.info(
                                "Restarting the batch instance for the  batch class:" + batchClassIdentifier);
                        final BatchClassModule batchClassModuleItem = bcModuleService
                                .getBatchClassModuleByWorkflowName(batchClassIdentifier, moduleNameLocal);
                        if (batchClassModuleItem != null) {
                            for (String executedModule : executedModulesArray) {
                                if (executedModule.equalsIgnoreCase(
                                        String.valueOf(batchClassModuleItem.getModule().getId()))) {
                                    isSuccess = true;
                                    break;
                                }
                            }
                        }
                    }
                } else {
                    isSuccess = true;
                    List<BatchClassModule> batchClassModuleList = batchInstance.getBatchClass()
                            .getBatchClassModules();
                    moduleNameLocal = batchClassModuleList.get(0).getWorkflowName();
                    LOGGER.info("Restarting the batch from first module." + moduleNameLocal
                            + " as the executed module list is empty.");
                }
                final boolean isZipSwitchOn = bsService.isZipSwitchOn();
                LOGGER.info("Zipped Batch XML switch is:" + isZipSwitchOn);

                final String activeModule = workflowService.getActiveModule(batchInstance);
                LOGGER.info("The activeModule of batch:" + activeModule);
                if (isSuccess) {
                    LOGGER.info("All parameters for restarting the batch are valid.");
                    respStr = processRestartingBatchInternal(identifier, moduleNameLocal, respStr,
                            batchInstance, batchClassIdentifier, isZipSwitchOn, activeModule);
                } else {
                    isSuccess = false;
                    List<BatchClassModule> batchClassModules = bcModuleService
                            .getAllBatchClassModulesByIdentifier(batchClassIdentifier);
                    String[] executedModulesArray = executedBatchInstanceModules.split(";");
                    Set<String> executedWorkflows = new HashSet<String>();
                    for (String executedModuleId : executedModulesArray) {
                        for (BatchClassModule batchClassModule : batchClassModules) {
                            if (batchClassModule != null && executedModuleId
                                    .equalsIgnoreCase(String.valueOf(batchClassModule.getModule().getId()))) {
                                executedWorkflows.add(batchClassModule.getWorkflowName());
                                break;
                            }
                        }
                    }
                    respStr = "Invalid parameter for restarting batch instance. Batch is being restarted from a module:"
                            + moduleNameLocal
                            + " that may not yet be executed or is non existent. Please select the valid module name for restart from the following :"
                            + executedWorkflows.toString();
                    LOGGER.error(SERVER_ERROR_MSG + respStr);
                }
            } else {
                respStr = "User is not authorized to perform operation on this batch instance." + identifier;
                LOGGER.error(SERVER_ERROR_MSG + respStr);
            }
        } else {
            respStr = "Either Batch instance does not exist with batch instance identifier " + identifier
                    + " or batch exists with incorrect status to be restarted. Batch instance should be of status:-"
                    + "ERROR, READY_FOR_REVIEW, READY_FOR_VALIDATION, RUNNING";
            isSuccess = false;
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
            LOGGER.error(SERVER_ERROR_MSG + respStr);
        } catch (final IOException ioe) {
            LOGGER.debug(ERROR_WHILE_SENDING_ERROR_RESPONSE_TO_CLIENT + ioe, ioe);
        }
    }
    return (isSuccess ? "Batch restarted successfully from module:" + moduleNameLocal
            : "Failure while restarting batch instance.");
}

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

private void processPayment(FIN_Payment payment, String strAction, Boolean isPosOrder, String paymentDate,
        String comingFrom, String selectedCreditLineIds) throws OBException {
    dao = new AdvPaymentMngtDao();
    String msg = "";
    try {//from w ww  .j a  va  2 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);
    }
}