FileDocCategorySizeDatePackage
ReportHandler.javaAPI DocExample33198Tue Jun 08 11:26:42 BST 2004com.mycompany.expense

ReportHandler

public class ReportHandler extends Object
This class contains properties and methods for the JSF components in the report area of the sample expense report application.
author
Hans Bergsten, Gefion Software
version
1.0

Fields Summary
private static final int
SORT_BY_TITLE
private static final int
SORT_BY_OWNER
private static final int
SORT_BY_DATE
private static final int
SORT_BY_TOTAL
private static final int
SORT_BY_STATUS
private ReportRegistry
registry
private Rules
rules
private Report
currentReport
private String
currentUser
private boolean
isManager
private javax.faces.model.DataModel
reportsModel
private javax.faces.model.DataModel
entriesModel
private Date
from
private Date
to
private int[]
status
private boolean
ascending
private int
sortBy
private int
noOfRows
private int
firstRowIndex
private int
noOfPageLinks
private static final Comparator
ASC_TITLE_COMPARATOR
private static final Comparator
DESC_TITLE_COMPARATOR
private static final Comparator
ASC_OWNER_COMPARATOR
private static final Comparator
DESC_OWNER_COMPARATOR
private static final Comparator
ASC_DATE_COMPARATOR
private static final Comparator
DESC_DATE_COMPARATOR
private static final Comparator
ASC_TOTAL_COMPARATOR
private static final Comparator
DESC_TOTAL_COMPARATOR
private static final Comparator
ASC_STATUS_COMPARATOR
private static final Comparator
DESC_STATUS_COMPARATOR
Constructors Summary
public ReportHandler()
Creates a new instance, initialized with a new Report and information about the current user.


                        
      
        rules = new Rules();
        currentReport = getCurrentReport();
        currentUser = getCurrentUser();
        isManager = isManager();
    
Methods Summary
public java.lang.Stringaccept()
Accepts the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canAccept(currentUser, isManager, currentReport)) {
            addMessage("report_no_accept_access", null);
            return "error";
        }

        String outcome = "success";
        int currentStatus = currentReport.getStatus();
        currentReport.setStatus(Report.STATUS_ACCEPTED);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            currentReport.setStatus(currentStatus);
            outcome = "error";
        }
        return outcome;
    
public java.lang.StringaddEntry(ReportEntry entry)
Adds an entry to the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }
        
        if (!rules.canEdit(currentUser, isManager, currentReport)) {
            addMessage("report_no_edit_access", null);
            return "error";
        }

        String outcome = "success";
        currentReport.addEntry(entry);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            currentReport.removeEntry(entry.getId());
            addMessage("registry_error", e.getMessage());
            outcome = "error";
        }
        return outcome;
    
private voidaddMessage(java.lang.String messageKey, java.lang.Object param)
Adds the message matching the key in the application's resource bundle, formatted with the parameters (if any), the the JSF message queue as a global message.

        FacesContext context = FacesContext.getCurrentInstance();
        Application application = context.getApplication();
        String messageBundleName = application.getMessageBundle();
        Locale locale = context.getViewRoot().getLocale();
        ResourceBundle rb = 
            ResourceBundle.getBundle(messageBundleName, locale);
        String msgPattern = rb.getString(messageKey);
        String msg = msgPattern;
        if (param != null) {
            Object[] params = {param};
            msg = MessageFormat.format(msgPattern, params);
        }
        FacesMessage facesMsg = 
            new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, msg);
        context.addMessage(null, facesMsg);
    
public java.lang.Stringcreate()
Creates a new Report and makes it the current report.

        currentReport = createNewReport();
        return "success";
    
private ReportcreateNewReport()
Creates a new Report instance initialized with the current user as the owner, and resets the cached entries DataModel.

        Report report = new Report();
        report.setOwner(getCurrentUser());
	entriesModel = null;
        return report;
    
public java.lang.Stringdelete()
Deletes the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canDelete(currentUser, isManager, currentReport)) {
            addMessage("report_no_delete_access", null);
            return "error";
        }

        String outcome = "success";
        try {
            registry.removeReport(currentReport);
            currentReport = createNewReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            outcome = "error";
        }
        return outcome;
    
public intgetCurrentPage()
Returns the index for the page matching the currently rendered set of reports in the reports list.

	return (firstRowIndex / noOfRows) + 1;
    
public ReportgetCurrentReport()
Returns the current Report instance, or a new instance if there's no current instance.

        if (currentReport == null) {
            currentReport = createNewReport();
        }
        return currentReport; 
    
public java.util.ListgetCurrentReportEntries()
Returns a List with the ReportEntry instances for the current Report, sorted on the entry dates.

        List currentList = currentReport.getEntries();
        Collections.sort(currentList, new Comparator() {
                public int compare(Object o1, Object o2) {
                    Date d1 = ((ReportEntry) o1).getDate();
                    Date d2 = ((ReportEntry) o2).getDate();
                    return d1.compareTo(d2);
                }
            });
        return currentList;
    
private java.lang.StringgetCurrentUser()
Returns the username of the current, authenticated user.

        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ec = context.getExternalContext();
        return ec.getRemoteUser();
    
public intgetFirstPageIndex()
Returns the index for the first page link to render.

        int noOfPages = getPages().size();
	if (noOfPages <= noOfPageLinks) {
	    return 0;
	}
	
	int firstPageIndex = (firstRowIndex / noOfRows) - 1;
	if (firstPageIndex < 0) {
	    firstPageIndex = 0;
	}
	else if (noOfPages - firstPageIndex < noOfPageLinks) {
	    firstPageIndex = noOfPages - noOfPageLinks;
	}
	return firstPageIndex;
    
public intgetFirstRowIndex()
Returns the index for the first row in the reports table.

        return firstRowIndex;
    
public java.util.DategetFrom()
Returns the from date, or a Date representing the previous month if no from date is set.

        if (from == null) {
            from = getPreviousMonth(new Date());
        }
        return from;
    
public intgetNoOfPageLinks()
Returns the number of links to render in the navigation bar.

	return noOfPageLinks;
    
public intgetNoOfRows()
Returns the number of rows to show in the reports table.


    /*
     * Methods related to the display of the reports table.
     */

                    
       
        return noOfRows;
    
public java.util.ListgetPages()
Returns a List with Page instances for each page of reports.

	int totalNoOfRows = getSortedReportsModel().getRowCount();
        int noOfPages =  totalNoOfRows / noOfRows;
	if (totalNoOfRows % noOfRows > 0) {
	    noOfPages += 1;
	}
	
        List pages = new ArrayList(noOfPages);
        for (int i = 0; i < noOfPages; i++) {
	    pages.add(new Page(i + 1, this));
        }
	return pages;
    
private java.util.DategetPreviousMonth(java.util.Date current)
Returns a Date one month prior to the provided Date.

        GregorianCalendar c = new GregorianCalendar();
        c.setTime(current);
        c.add(Calendar.MONTH, -1);
        return c.getTime();
    
public javax.faces.model.DataModelgetReportEntriesModel()
Returns a DataModel with the ReportEntry instances for the current Report, sorted on the entry dates.

        if (entriesModel == null) {
            entriesModel = new ListDataModel();
	    entriesModel.setWrappedData(getCurrentReportEntries());
        }
        return entriesModel;
    
public java.util.ListgetReports()
Returns a List with Report instances matching the filtering criteria.

        String user = null;
        if (!isManager) {
            user = getCurrentUser();
        }
        List l = null;
        try {
            l = registry.getReports(user, from, to, status);
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
        }
        return l;
    
public javax.faces.model.DataModelgetReportsModel()
Returns a DataModel with Report instances matching the filtering criteria.

        if (reportsModel == null) {
            reportsModel = new ListDataModel();
        }
        reportsModel.setWrappedData(getReports());
        return reportsModel;
    
public javax.faces.model.DataModelgetSortedReportsModel()
Returns a DataModel with Report instances matching the filtering criteria, sorted according to the current sort column and order.

        if (reportsModel == null) {
            reportsModel = new ListDataModel();
        }
        List reports = getReports();
        sortReports(reports);
        reportsModel.setWrappedData(reports);
        return reportsModel;
    
public java.lang.String[]getStatus()
Returns the status codes for displayed reports, or the code for "Submitted" if no status code is set and the current user is a manager, or all status codes if no status code is set and the current user isn't a manager.

        if (status == null) {
            if (isManager) {
                status = new int[1];
                status[0] = Report.STATUS_SUBMITTED;
            }
            else {
                status = new int[4];
                status[0] = Report.STATUS_OPEN;
                status[1] = Report.STATUS_SUBMITTED;
                status[2] = Report.STATUS_ACCEPTED;
                status[3] = Report.STATUS_REJECTED;
            }
        }

        // Convert the int[] to a String[] to match the SelectItem type
        String[] stringStatus = new String[status.length];
        for (int i = 0; i < status.length; i++) {
            stringStatus[i] = String.valueOf(status[i]);
        }
        return stringStatus;
    
public java.util.DategetTo()
Returns the to date, or a Date representing today if no to date is set.

        if (to == null) {
            to = new Date();
        }
        return to;
    
public booleanisAcceptDisabled()
Returns "true" if the current report is new (no entries yet) or the current user isn't allowed to accept the report.

        return isReportNew() || 
            !rules.canAccept(currentUser, isManager, currentReport);
    
public booleanisAcceptRendered()
Returns "true" if the current user is a manager.

        return isManager;
    
public booleanisDeleteDisabled()
Returns "true" if the current report is new (no entries yet) or the current user isn't allowed to delete the report.

        return isReportNew() || 
            !rules.canDelete(currentUser, isManager, currentReport);
    
public booleanisEditDisabled()
Returns "true" if the current report isn't new (no entries yet) and the current user isn't allowed to edit the report.

        return !isReportNew() &&
            !rules.canEdit(currentUser, isManager, currentReport);
    
public booleanisManager()
Returns "true" if the current user is associated with the "manager" role.

        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ec = context.getExternalContext();
        return ec.isUserInRole("manager");
    
public booleanisNewDisabled()
Returns "true" if the current report is new (no entries yet).

        return isReportNew();
    
public booleanisRejectDisabled()
Returns "true" if the current report is new (no entries yet) or the current user isn't allowed to reject the report.

        return isReportNew() || 
            !rules.canReject(currentUser, isManager, currentReport);
    
public booleanisRejectRendered()
Returns "true" if the current user is a manager.

        return isManager;
    
private booleanisReportNew()
Returns "true" if the current report has status "new".

        return currentReport.getStatus() == Report.STATUS_NEW;
    
public booleanisScrollFirstDisabled()
Returns "true" if the first page of reports is displayed.

        return firstRowIndex == 0;
    
public booleanisScrollLastDisabled()
Returns "true" if the last page of reports is displayed.

        return firstRowIndex >= reportsModel.getRowCount() - noOfRows;
    
public booleanisScrollNextDisabled()
Returns "true" if there aren't enough rows to scroll forward one page.

        return firstRowIndex >= reportsModel.getRowCount() - noOfRows;
    
public booleanisScrollPreviousDisabled()
Returns "true" if the first page is displayed.

        return firstRowIndex == 0;
    
public booleanisSubmitDisabled()
Returns "true" if the current report is new (no entries yet) or the current user isn't allowed to submit the report.

        return isReportNew() || 
            !rules.canSubmit(currentUser, isManager, currentReport);
    
private voidrefreshCache()
If the current report isn't new (i.e., not yet stored), refreshes the current report with a copy from the registry to ensure the local copy is the latest version.

        if (!isReportNew()) {
            setCurrentReport(registry.getReport(currentReport.getId()));
        }
    
public java.lang.Stringreject()
Rejects the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canReject(currentUser, isManager, currentReport)) {
            addMessage("report_no_reject_access", null);
            return "error";
        }

        String outcome = "success";
        int currentStatus = currentReport.getStatus();
        currentReport.setStatus(Report.STATUS_REJECTED);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            currentReport.setStatus(currentStatus);
            outcome = "error";
        }
        return outcome;
    
public java.lang.StringremoveEntry()
Removes the entry represented by the current row in the entries DataModel from the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        ReportEntry selectedEntry = 
            (ReportEntry) entriesModel.getRowData();
        int entryId = selectedEntry.getId();
        return removeEntry(entryId);
    
public java.lang.StringremoveEntry(int entryId)
Removes the specified entry from the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canEdit(currentUser, isManager, currentReport)) {
            addMessage("report_no_edit_access", null);
            return "error";
        }

        String outcome = "success";
        ReportEntry currentEntry = currentReport.getEntry(entryId);
        currentReport.removeEntry(entryId);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            currentReport.addEntry(currentEntry);
            outcome = "error";
        }
        return outcome;
    
private voidsaveReport()
If the current report is new, changes its status to "open" and add it to the registry; otherwise, updates the report in the registry. Resets the cached entries DataModel.

        if (isReportNew()) {
            currentReport.setStatus(Report.STATUS_OPEN);
            registry.addReport(currentReport);
        }
        else {
            registry.updateReport(currentReport);
        }
	entriesModel = null;
    
public java.lang.StringscrollFirst()
Sets the index for the first row to display in the reports list to zero.

        firstRowIndex = 0;
        return "success";
    
public java.lang.StringscrollLast()
Sets the index for the first row to display in the reports list to the index of the top row for the last page.

        firstRowIndex = reportsModel.getRowCount() - noOfRows;
        if (firstRowIndex < 0) {
            firstRowIndex = 0;
        }
        return "success";
    
public java.lang.StringscrollNext()
Sets the index for the first row to display in the reports table to the index of the top row for the next page, or to zero if there is no more page.

        firstRowIndex += noOfRows;
        if (firstRowIndex >= reportsModel.getRowCount()) {
            firstRowIndex = reportsModel.getRowCount() - noOfRows;
            if (firstRowIndex < 0) {
                firstRowIndex = 0;
            }
        }
        
        return "success";
    
public java.lang.StringscrollPrevious()
Sets the index for the first row to display in the reports table to the index of the top row for the previou page, or to zero if there is no more page.

        firstRowIndex -= noOfRows;
        if (firstRowIndex < 0) {
            firstRowIndex = 0;
        }
        return "success";
    
public java.lang.Stringselect()
Makes the report at the current row in the reports DataModel the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        Report selectedReport = (Report) reportsModel.getRowData();
        if (!rules.canView(currentUser, isManager, selectedReport)) {
            addMessage("report_no_view_access", null);
            return "error";
        }
        setCurrentReport(selectedReport);
        return "success";
    
private voidsetCurrentPage(int currentPage)
Sets the index for the first row in the reports table to match the specified page number.

	firstRowIndex = (currentPage - 1) * noOfRows;
    
private voidsetCurrentReport(Report report)
Makes the provided Report the current report, and resets the cached entries DataModel.

	currentReport = report;
	entriesModel = null;
    
public voidsetFrom(java.util.Date from)
Sets the from date.

        this.from = from;
    
public voidsetNoOfRows(int noOfRows)
Sets the number of rows to show in the reports table.

        this.noOfRows = noOfRows;
    
public voidsetReportRegistry(ReportRegistry registry)
Sets the ReportRegistry instance used by this application.

        this.registry = registry;
    
public voidsetStatus(java.lang.String[] stringStatus)
Sets the status codes to display.

        // Convert the String[], matching the SelectItem type, to 
        // the int[] used internally
        status = null;
        if (stringStatus != null) {
            status = new int[stringStatus.length];
            for (int i = 0; i < stringStatus.length; i++) {
                status[i] = Integer.valueOf(stringStatus[i]).intValue();
            }
        }
    
public voidsetTo(java.util.Date to)
Sets the to date.

        this.to = to;
    
public java.lang.StringsortByDate()
Sets the sorting column for the reports list to the "date" column, reversing the order if the table is already sorted by this column.

        if (sortBy == SORT_BY_DATE) {
            ascending = !ascending;
        }
        else {
            sortBy = SORT_BY_DATE;
            ascending = false;
        }
        return "success";
    
public java.lang.StringsortByOwner()
Sets the sorting column for the reports list to the "owner" column, reversing the order if the table is already sorted by this column.

        if (sortBy == SORT_BY_OWNER) {
            ascending = !ascending;
        }
        else {
            sortBy = SORT_BY_OWNER;
            ascending = true;
        }
        return "success";
    
public java.lang.StringsortByStatus()
Sets the sorting column for the reports list to the "status" column, reversing the order if the table is already sorted by this column.

        if (sortBy == SORT_BY_STATUS) {
            ascending = !ascending;
        }
        else {
            sortBy = SORT_BY_STATUS;
            ascending = true;
        }
        return "success";
    
public java.lang.StringsortByTitle()
Sets the sorting column for the reports list to the "title" column, reversing the order if the table is already sorted by this column.

        if (sortBy == SORT_BY_TITLE) {
            ascending = !ascending;
        }
        else {
            sortBy = SORT_BY_TITLE;
            ascending = true;
        }
        return "success";
    
public java.lang.StringsortByTotal()
Sets the sorting column for the reports list to the "total" column, reversing the order if the table is already sorted by this column.

        if (sortBy == SORT_BY_TOTAL) {
            ascending = !ascending;
        }
        else {
            sortBy = SORT_BY_TOTAL;
            ascending = true;
        }
        return "success";
    
private voidsortReports(java.util.List reports)
Sorts the reports according to the current sort column and order.

        switch (sortBy) {
            case SORT_BY_TITLE:
                Collections.sort(reports, 
                    ascending ? ASC_TITLE_COMPARATOR : DESC_TITLE_COMPARATOR);
                break;
            case SORT_BY_OWNER:
                Collections.sort(reports, 
                    ascending ? ASC_OWNER_COMPARATOR : DESC_OWNER_COMPARATOR);
                break;
            case SORT_BY_DATE:
                Collections.sort(reports, 
                    ascending ? ASC_DATE_COMPARATOR : DESC_DATE_COMPARATOR);
                break;
            case SORT_BY_TOTAL:
                Collections.sort(reports, 
                    ascending ? ASC_TOTAL_COMPARATOR : DESC_TOTAL_COMPARATOR);
                break;
            case SORT_BY_STATUS:
                Collections.sort(reports, 
                    ascending ? ASC_STATUS_COMPARATOR : DESC_STATUS_COMPARATOR);
                break;
        }
    
public java.lang.Stringsubmit()
Submits the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canSubmit(currentUser, isManager, currentReport)) {
            addMessage("report_no_submit_access", null);
            return "error";
        }

        String outcome = "success";
        int currentStatus = currentReport.getStatus();
        currentReport.setStatus(Report.STATUS_SUBMITTED);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            currentReport.setStatus(currentStatus);
            outcome = "error";
        }
        return outcome;
    
public java.lang.StringupdateEntry()
Uses the entry represented by the current row in the entries DataModel to update the corresponding entry in the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        ReportEntry selectedEntry = 
            (ReportEntry) entriesModel.getRowData();
        int entryId = selectedEntry.getId();
        return updateEntry(selectedEntry);
    
public java.lang.StringupdateEntry(ReportEntry entry)
Uses the provided entry to update the corresponding entry in the current report, or queues an error message if the current user isn't allowed to do that or the registry throws an exception.

        try {
            refreshCache();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            return "error";
        }

        if (!rules.canEdit(currentUser, isManager, currentReport)) {
            addMessage("report_no_edit_access", null);
            return "error";
        }

        String outcome = "success";
        ReportEntry currentEntry = currentReport.getEntry(entry.getId());
        currentReport.removeEntry(entry.getId());
        currentReport.addEntry(entry);
        try {
            saveReport();
        }
        catch (RegistryException e) {
            addMessage("registry_error", e.getMessage());
            currentReport.removeEntry(entry.getId());
            currentReport.addEntry(currentEntry);
            outcome = "error";
        }
        return outcome;