Example usage for com.google.gwt.user.client.ui SuggestOracle SuggestOracle

List of usage examples for com.google.gwt.user.client.ui SuggestOracle SuggestOracle

Introduction

In this page you can find the example usage for com.google.gwt.user.client.ui SuggestOracle SuggestOracle.

Prototype

public SuggestOracle() 

Source Link

Document

Constructor for com.google.gwt.user.client.ui.SuggestOracle .

Usage

From source file:org.unitime.timetable.gwt.client.events.EventResourceTimetable.java

License:Apache License

public EventResourceTimetable(PageType type) {
    iHistoryToken = new HistoryToken(type);
    iType = type;//from  w w w  .j a v  a 2  s .  c om

    iFilter = new SimpleForm(2);
    iFilter.removeStyleName("unitime-NotPrintableBottomLine");
    iFilter.getColumnFormatter().setWidth(0, "120px");

    iFilterHeader = new UniTimeHeaderPanel(MESSAGES.sectFilter());
    iLookup = new Lookup();
    iLookup.setOptions("mustHaveExternalId");
    iLookup.addValueChangeHandler(new ValueChangeHandler<PersonInterface>() {
        @Override
        public void onValueChange(ValueChangeEvent<PersonInterface> event) {
            if (event.getValue() != null) {
                iResources.setText(event.getValue().getId());
                resourceTypeChanged(true);
            }
        }
    });
    iFilterHeader.addButton("lookup", MESSAGES.buttonLookup(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            iLookup.center();
        }
    });
    iFilterHeader.setEnabled("lookup", false);
    iFilterHeader.addButton("add", MESSAGES.buttonAddEvent(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            iEventAdd.setEvent(null);
            iEventAdd.show();
        }
    });
    iFilterHeader.setEnabled("add", false);
    iFilter.addHeaderRow(iFilterHeader);
    iFilterHeader.addButton("clear", MESSAGES.buttonClear(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            // Event filter
            iEvents.setValue(iHistoryToken.getDefaultParameter("events", ""), true);

            // Room filter
            iRooms.setValue(iHistoryToken.getDefaultParameter("rooms", ""), true);

            // Resource type
            if (!"true".equals(iHistoryToken.getParameter("fixedType", "false"))) {
                String typeString = iHistoryToken.getDefaultParameter("type", "room");
                if (typeString != null)
                    for (int idx = 0; idx < iResourceTypes.getItemCount(); idx++) {
                        if (iResourceTypes.getValue(idx).equalsIgnoreCase(typeString)) {
                            iResourceTypes.setSelectedIndex(idx);
                        }
                    }
            }

            // Subject, curriculum, department, etc.
            iResources.setValue(iHistoryToken.getDefaultParameter("name", ""));

            // Room selection
            iLocRoom = iHistoryToken.getDefaultParameter("room", "");

            // Week selection
            iLocDate = iHistoryToken.getDefaultParameter("date", "");

            hideResults();
            changeUrl();
            UniTimePageLabel.getInstance().setPageName(getPageName());
            resourceTypeChanged(false);
        }
    });
    iFilterHeader.setEnabled("clear", "true".equals(iHistoryToken.getParameter("showClear", "true")));
    iFilterHeader.addButton("search", MESSAGES.buttonSearch(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            resourceTypeChanged(true);
        }
    });

    iSession = new AcademicSessionSelectionBox(iHistoryToken.getParameter("term"), "Events") {
        @Override
        protected void onInitializationSuccess(List<AcademicSession> sessions) {
            iFilter.setVisible(sessions != null && !sessions.isEmpty());
            UniTimePageHeader.getInstance().getRight().setVisible(false);
            UniTimePageHeader.getInstance().getRight().setPreventDefault(true);
        }

        @Override
        protected void onInitializationFailure(Throwable caught) {
            UniTimeNotifications.error(MESSAGES.failedLoadSessions(caught.getMessage()), caught);
        }
    };
    iSession.setFilter(this);
    iSessionRow = iFilter.addRow(MESSAGES.propAcademicSession(), iSession);

    iEvents = new EventFilterBox(iSession);
    if ("true".equals(iHistoryToken.getParameter("showFilter", "true")))
        iFilter.addRow(MESSAGES.propEventFilter(), iEvents);

    iRooms = new RoomFilterBox(iSession);
    if ("true".equals(iHistoryToken.getParameter("showFilter", "true")))
        iFilter.addRow(MESSAGES.propRoomFilter(), iRooms);

    iResourceTypes = new ListBox();
    for (ResourceType resource : ResourceType.values()) {
        if (resource.isVisible())
            iResourceTypes.addItem(resource.getResourceType(CONSTANTS), resource.name());
    }

    iResourceTypes.addChangeHandler(new ChangeHandler() {
        @Override
        public void onChange(ChangeEvent event) {
            iResources.setText("");
            UniTimePageLabel.getInstance().setPageName(getPageName());
            hideResults();
            if (iProperties != null)
                resourceTypeChanged(isShowingResults());
        }
    });
    int row = iFilter.addRow(MESSAGES.propResourceType(), iResourceTypes);
    if ("true".equals(iHistoryToken.getParameter("fixedType", "false")))
        iFilter.getRowFormatter().setVisible(row, false);

    iResources = new SuggestBox(new SuggestOracle() {
        @Override
        public void requestDefaultSuggestions(Request request, Callback callback) {
            requestSuggestions(request, callback);
        }

        @Override
        public void requestSuggestions(final Request request, final Callback callback) {
            if (iSession.getAcademicSessionId() != null) {
                RPC.execute(
                        ResourceLookupRpcRequest.findResources(iSession.getAcademicSessionId(),
                                ResourceType
                                        .valueOf(iResourceTypes.getValue(iResourceTypes.getSelectedIndex())),
                                request.getQuery(), request.getLimit()),
                        new AsyncCallback<GwtRpcResponseList<ResourceInterface>>() {
                            @Override
                            public void onFailure(final Throwable caught) {
                                ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();
                                suggestions.add(new Suggestion() {
                                    @Override
                                    public String getDisplayString() {
                                        return "<font color='red'>" + caught.getMessage() + "</font>";
                                    }

                                    @Override
                                    public String getReplacementString() {
                                        return "";
                                    }
                                });
                                callback.onSuggestionsReady(request, new Response(suggestions));
                                ToolBox.checkAccess(caught);
                            }

                            @Override
                            public void onSuccess(GwtRpcResponseList<ResourceInterface> result) {
                                ArrayList<Suggestion> suggestions = new ArrayList<Suggestion>();
                                for (ResourceInterface resource : result) {
                                    suggestions.add(new ResourceSuggestion(resource));
                                }
                                callback.onSuggestionsReady(request, new Response(suggestions));
                            }
                        });
            }
        }

        @Override
        public boolean isDisplayStringHTML() {
            return true;
        }
    });
    iResources.getValueBox().addFocusHandler(new FocusHandler() {
        @Override
        public void onFocus(FocusEvent event) {
            iResources.showSuggestionList();
        }
    });
    iResourcesRow = iFilter.addRow(MESSAGES.propResource(), iResources);
    iResources.addSelectionHandler(new SelectionHandler<Suggestion>() {
        public void onSelection(SelectionEvent<Suggestion> event) {
            if (event.getSelectedItem() instanceof ResourceSuggestion) {
                resourceChanged(((ResourceSuggestion) event.getSelectedItem()).getResource());
            }
        }
    });
    iFilter.getRowFormatter().setVisible(iResourcesRow, false);

    iResourceTypes.setSelectedIndex(ResourceType.ROOM.ordinal());

    iPanel = new SimpleForm(2);
    iPanel.removeStyleName("unitime-NotPrintableBottomLine");
    iPanel.addRow(iFilter);
    iHeader = new UniTimeHeaderPanel();
    iPanel.addHeaderRow(iHeader);
    iWeekPanel = new WeekSelector(iSession);
    iWeekPanel.addValueChangeHandler(new ValueChangeHandler<WeekSelector.Interval>() {
        @Override
        public void onValueChange(ValueChangeEvent<WeekSelector.Interval> e) {
            iLocDate = iWeekPanel.getSelection();
            tabOrDataChanged(true);
        }
    });
    iWeekPanel.setFilter(new WeekSelector.Filter<WeekInterface>() {
        @Override
        public boolean filter(WeekInterface week) {
            return !iMatchingWeeks.contains(week.getDayOfYear());
        }

        @Override
        public boolean isEmpty() {
            return iMatchingRooms.isEmpty();
        }
    });
    iRoomPanel = new RoomSelector();
    iRoomPanel.setFilter(new WeekSelector.Filter<ResourceInterface>() {
        @Override
        public boolean filter(ResourceInterface room) {
            return !iMatchingRooms.contains(room.getId());
        }

        @Override
        public boolean isEmpty() {
            return iMatchingRooms.isEmpty();
        }
    });

    iTabBar = new AriaTabBar();
    iTabBar.addTab(MESSAGES.tabGrid(), true);
    iTabBar.addTab(MESSAGES.tabEventTable(), true);
    iTabBar.addTab(MESSAGES.tabMeetingTable(), true);
    iTabBar.addSelectionHandler(new SelectionHandler<Integer>() {
        @Override
        public void onSelection(SelectionEvent<Integer> event) {
            tabOrDataChanged(true);
        }
    });

    iGridOrTablePanel = new SimplePanel();
    iGridOrTablePanel.setStyleName("unitime-TabPanel");

    final Character gridAccessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.tabGrid());
    final Character eventsAccessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.tabEventTable());
    final Character meetingsAccessKey = UniTimeHeaderPanel.guessAccessKey(MESSAGES.tabMeetingTable());
    if (gridAccessKey != null || eventsAccessKey != null || meetingsAccessKey != null) {
        RootPanel.get().addDomHandler(new KeyUpHandler() {
            @Override
            public void onKeyUp(KeyUpEvent event) {
                if (!iRootPanel.getWidget().equals(iPanel))
                    return;
                int tab = -1;
                if (gridAccessKey != null && event.getNativeEvent().getCtrlKey()
                        && (event.getNativeKeyCode() == gridAccessKey
                                || event.getNativeKeyCode() == Character.toUpperCase(gridAccessKey))) {
                    tab = 0;
                }
                if (eventsAccessKey != null && event.getNativeEvent().getCtrlKey()
                        && (event.getNativeKeyCode() == eventsAccessKey
                                || event.getNativeKeyCode() == Character.toUpperCase(eventsAccessKey))) {
                    tab = 1;
                }
                if (meetingsAccessKey != null && event.getNativeEvent().getCtrlKey()
                        && (event.getNativeKeyCode() == meetingsAccessKey
                                || event.getNativeKeyCode() == Character.toUpperCase(meetingsAccessKey))) {
                    tab = 2;
                }
                if (tab >= 0) {
                    iTabBar.selectTab(tab);
                    event.preventDefault();
                }
            }
        }, KeyUpEvent.getType());
    }

    iDockPanel = new DockPanel();
    iDockPanel.setStyleName("unitime-EventResults");
    iDockPanel.setSpacing(0);
    iDockPanel.add(iGridOrTablePanel, DockPanel.SOUTH);
    iDockPanel.add(iRoomPanel, DockPanel.WEST);
    iDockPanel.setCellHorizontalAlignment(iRoomPanel, HasHorizontalAlignment.ALIGN_LEFT);
    iDockPanel.add(iTabBar, DockPanel.CENTER);
    iDockPanel.setCellVerticalAlignment(iTabBar, HasVerticalAlignment.ALIGN_BOTTOM);
    iDockPanel.setCellHorizontalAlignment(iTabBar, HasHorizontalAlignment.ALIGN_CENTER);
    iDockPanel.add(iWeekPanel, DockPanel.EAST);
    iDockPanel.setCellHorizontalAlignment(iWeekPanel, HasHorizontalAlignment.ALIGN_RIGHT);
    Roles.getTabpanelRole().set(iDockPanel.getElement());
    Roles.getTabpanelRole().setAriaOwnsProperty(iDockPanel.getElement(), Id.of(iTabBar.getElement()));

    iPanel.addRow(iDockPanel);

    hideResults();

    iFooter = iHeader.clonePanel();
    iPanel.addRow(iFooter);
    iRootPanel = new SimplePanel(iPanel);
    initWidget(iRootPanel);

    iRoomPanel.addValueChangeHandler(new ValueChangeHandler<IntervalSelector<ResourceInterface>.Interval>() {
        @Override
        public void onValueChange(ValueChangeEvent<IntervalSelector<ResourceInterface>.Interval> e) {
            iLocRoom = iRoomPanel.getSelection();
            tabOrDataChanged(true);
        }
    });

    for (int i = 1; i < iPanel.getRowCount(); i++)
        iPanel.getRowFormatter().setVisible(i, false);

    iHeader.addButton("add", MESSAGES.buttonAddEvent(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            iEventAdd.setEvent(null);
            iEventAdd.show();
        }
    });
    iHeader.setEnabled("add", false);
    iHeader.addButton("print", MESSAGES.buttonPrint(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent clickEvent) {
            final EventMeetingTable table = new EventMeetingTable(
                    getSelectedTab() <= 1 ? EventMeetingTable.Mode.ListOfEvents
                            : EventMeetingTable.Mode.ListOfMeetings,
                    false, EventResourceTimetable.this);
            table.setMeetingFilter(EventResourceTimetable.this);
            table.setShowMainContact(iProperties != null && iProperties.isCanLookupMainContact());
            table.setEvents(iData);
            table.setSortBy(iTable.getSortBy());
            table.getElement().getStyle().setWidth(1040, Unit.PX);

            int firstSlot = 84, lastSlot = 216;
            boolean skipDays = iEvents.hasChip(new FilterBox.Chip("day", null));
            boolean hasDay[] = new boolean[] {
                    !skipDays || iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[0])),
                    !skipDays || iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[1])),
                    !skipDays || iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[2])),
                    !skipDays || iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[3])),
                    !skipDays || iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[4])),
                    iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[5])),
                    iEvents.hasChip(new FilterBox.Chip("day", CONSTANTS.longDays()[6])) };
            for (EventInterface event : iData) {
                if (event.getType() == EventType.Unavailabile
                        && !iEvents.hasChip(new Chip("type", "Not Available")))
                    continue;
                for (MeetingInterface meeting : event.getMeetings()) {
                    if (filterEvent(event, meeting))
                        continue;
                    if (meeting.getApprovalStatus() != ApprovalStatus.Pending
                            && meeting.getApprovalStatus() != ApprovalStatus.Approved)
                        continue;
                    if (firstSlot > meeting.getStartSlot())
                        firstSlot = meeting.getStartSlot();
                    if (lastSlot < meeting.getEndSlot())
                        lastSlot = meeting.getEndSlot();
                    hasDay[meeting.getDayOfWeek()] = true;
                }
            }
            Chip after = iEvents.getChip("after");
            if (after != null) {
                Integer slot = TimeUtils.parseTime(CONSTANTS, after.getValue(), null);
                if (slot != null && firstSlot > slot)
                    firstSlot = slot;
            }
            Chip before = iEvents.getChip("before");
            if (before != null) {
                Integer slot = TimeUtils.parseTime(CONSTANTS, before.getValue(), firstSlot);
                if (slot != null && lastSlot < slot)
                    lastSlot = slot;
            }
            int nrDays = 0;
            for (boolean d : hasDay)
                if (d)
                    nrDays++;
            int days[] = new int[nrDays];
            int d = 0;
            for (int i = 0; i < 7; i++)
                if (hasDay[i])
                    days[d++] = i;
            int firstHour = firstSlot / 12;
            int lastHour = 1 + (lastSlot - 1) / 12;
            if (firstHour <= 7 && firstHour > 0 && ((firstSlot % 12) <= 6))
                firstHour--;
            HashMap<Long, String> colors = new HashMap<Long, String>();

            final TimeGrid tg = new TimeGrid(colors, days, (int) (1000 / nrDays), 55, true, false,
                    (firstHour < 7 ? firstHour : 7), (lastHour > 18 ? lastHour : 18),
                    EventResourceTimetable.this);
            tg.setResourceType(getResourceType());
            tg.setSelectedWeeks(iWeekPanel.getSelected());
            tg.setRoomResources(iRoomPanel.getSelected());
            tg.setMode(gridMode());
            tg.showVerticalSplit();

            for (EventInterface event : sortedEvents()) {
                List<MeetingInterface> meetings = new ArrayList<MeetingInterface>();
                for (MeetingInterface meeting : event.getMeetings()) {
                    if (meeting.getApprovalStatus() != ApprovalStatus.Pending
                            && meeting.getApprovalStatus() != ApprovalStatus.Approved)
                        continue;
                    if (meeting.getMeetingDate() != null && !filterEvent(event, meeting))
                        meetings.add(meeting);
                }
                if (!meetings.isEmpty())
                    tg.addEvent(event, meetings);
            }
            if (iWeekPanel.getValue() != null)
                tg.labelDays(iWeekPanel.getValue().getFirst(), iWeekPanel.getValue().getLast());

            // Move header row to thead
            Element headerRow = table.getRowFormatter().getElement(0);
            Element tableElement = table.getElement();
            Element thead = DOM.createTHead();
            tableElement.insertFirst(thead);
            headerRow.getParentElement().removeChild(headerRow);
            thead.appendChild(headerRow);

            ToolBox.print(new ToolBox.Page() {
                @Override
                public String getName() {
                    return iHeader.getHeaderTitle();
                }

                @Override
                public String getUser() {
                    return iRoomPanel.getValue().toString();
                }

                @Override
                public String getSession() {
                    return iWeekPanel.getValue().toString();
                }

                @Override
                public Element getBody() {
                    return tg.getElement();
                }
            }, new ToolBox.Page() {
                @Override
                public String getName() {
                    return iHeader.getHeaderTitle();
                }

                @Override
                public String getUser() {
                    return iRoomPanel.getValue().toString();
                }

                @Override
                public String getSession() {
                    return iWeekPanel.getValue().toString();
                }

                @Override
                public Element getBody() {
                    return table.getElement();
                }
            });
        }
    });

    iHeader.addButton("export", MESSAGES.buttonExport(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent clickEvent) {
            if (iProperties != null && iProperties.isCanExportCSV()) {
                final PopupPanel popup = new PopupPanel(true);
                MenuBar menu = new MenuBar(true);
                MenuItem exportPdf = new MenuItem(MESSAGES.opExportPDF(), true, new Command() {
                    @Override
                    public void execute() {
                        popup.hide();
                        export("output=" + (getSelectedTab() <= 1 ? "events" : "meetings") + ".pdf&flags="
                                + EventCookie.getInstance().getFlags(), true);
                    }
                });
                exportPdf.getElement().getStyle().setCursor(Cursor.POINTER);
                menu.addItem(exportPdf);
                MenuItem exportCsv = new MenuItem(MESSAGES.opExportCSV(), true, new Command() {
                    @Override
                    public void execute() {
                        popup.hide();
                        export("output=" + (getSelectedTab() <= 1 ? "events" : "meetings") + ".csv&flags="
                                + EventCookie.getInstance().getFlags(), true);
                    }
                });
                exportCsv.getElement().getStyle().setCursor(Cursor.POINTER);
                menu.addItem(exportCsv);
                MenuItem exportIcs = new MenuItem(MESSAGES.opExportICalendar(), true, new Command() {
                    @Override
                    public void execute() {
                        popup.hide();
                        copyToClipboard(
                                "output=events.ics"
                                        + (iType == PageType.Personal ? "&e:flag=All+Sessions" : ""),
                                iType == PageType.Personal);
                    }
                });
                exportIcs.getElement().getStyle().setCursor(Cursor.POINTER);
                menu.addItem(exportIcs);
                popup.add(menu);
                popup.showRelativeTo((UIObject) clickEvent.getSource());
                menu.focus();
            } else {
                export("output=events.ics", false);
            }
        }
    });
    iHeader.addButton("operations", MESSAGES.buttonMoreOperations(), 75, new ClickHandler() {
        @Override
        public void onClick(ClickEvent event) {
            final PopupPanel popup = new PopupPanel(true);
            iTable.getHeader(0).setMenu(popup);
            popup.showRelativeTo((UIObject) event.getSource());
            ((MenuBar) popup.getWidget()).focus();
        }
    });
    iHeader.setEnabled("print", false);
    iHeader.setEnabled("export", false);
    iHeader.setEnabled("operations", false);

    iSession.addAcademicSessionChangeHandler(new AcademicSessionChangeHandler() {
        @Override
        public void onAcademicSessionChange(AcademicSessionChangeEvent event) {
            loadProperties(new AsyncCallback<EventPropertiesRpcResponse>() {
                @Override
                public void onFailure(Throwable caught) {
                }

                @Override
                public void onSuccess(EventPropertiesRpcResponse result) {
                    if (!iInitialized)
                        setup(true);
                    else
                        resourceTypeChanged(isShowingResults());
                }
            });
        }
    });

    iEventDetail = new EventDetail(this) {
        @Override
        protected void onHide() {
            iRootPanel.setWidget(iPanel);
            UniTimePageLabel.getInstance().setPageName(getPageName());
            if (!isShowingResults())
                resourceTypeChanged(true);
            changeUrl();
        }

        @Override
        protected void onShow() {
            iBack.clear();
            if (iTable != null)
                iTable.clearHover();
            iRootPanel.setWidget(iEventDetail);
            changeUrl();
        }

        @Override
        protected void edit() {
            super.hide();
            iEventAdd.setEvent(getEvent());
            iEventAdd.show();
        }

        @Override
        protected EventInterface getPrevious(Long eventId) {
            return iTable.previous(eventId);
        }

        @Override
        protected EventInterface getNext(Long eventId) {
            return iTable.next(eventId);
        }

        @Override
        protected void previous(final EventInterface event) {
            iBack.add(getEvent());
            LoadingWidget.execute(
                    EventDetailRpcRequest.requestEventDetails(iSession.getAcademicSessionId(), event.getId()),
                    new AsyncCallback<EventInterface>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            UniTimeNotifications
                                    .error(MESSAGES.failedLoad(event.getName(), caught.getMessage()), caught);
                        }

                        @Override
                        public void onSuccess(EventInterface result) {
                            LoadingWidget.getInstance().hide();
                            setEvent(result);
                            changeUrl();
                        }
                    }, MESSAGES.waitLoading(event.getName()));
        }

        @Override
        protected void next(final EventInterface event) {
            previous(event);
        }

        @Override
        public void hide() {
            if (!iBack.isEmpty()) {
                EventInterface last = iBack.remove(iBack.size() - 1);
                setEvent(last);
            } else {
                super.hide();
            }
        }

        @Override
        protected void onApprovalOrReject(Long eventId, EventInterface event) {
            if (iData != null)
                populate(tinker(new GwtRpcResponseList<EventInterface>(iData), eventId, event));
        }
    };

    iEventAdd = new EventAdd(iSession, this) {
        @Override
        protected void onHide() {
            iSession.setFilter(EventResourceTimetable.this);
            iFilter.setWidget(iSessionRow, 1, iSession);
            final EventInterface modified = iEventAdd.getEvent(), detail = iEventDetail.getEvent(),
                    saved = iEventAdd.getSavedEvent();
            if (saved != null) {
                if (iData != null)
                    populate(tinker(new GwtRpcResponseList<EventInterface>(iData),
                            (saved.getId() == null ? modified.getId() : saved.getId()), saved));
                if (saved.getId() != null) {
                    iEventDetail.setEvent(saved);
                    iEventDetail.show();
                } else {
                    iRootPanel.setWidget(iPanel);
                    UniTimePageLabel.getInstance().setPageName(getPageName());
                }
            } else if (modified != null && detail != null && detail.getId().equals(modified.getId())) {
                LoadingWidget.execute(EventDetailRpcRequest.requestEventDetails(iSession.getAcademicSessionId(),
                        modified.getId()), new AsyncCallback<EventInterface>() {
                            @Override
                            public void onFailure(Throwable caught) {
                                UniTimeNotifications.error(
                                        MESSAGES.failedLoad(detail.getName(), caught.getMessage()), caught);
                            }

                            @Override
                            public void onSuccess(EventInterface result) {
                                LoadingWidget.getInstance().hide();
                                if (result == null) {
                                    iRootPanel.setWidget(iPanel);
                                    UniTimePageLabel.getInstance().setPageName(getPageName());
                                } else {
                                    iEventDetail.setEvent(result);
                                    iEventDetail.show();
                                }
                            }
                        }, MESSAGES.waitLoading(detail.getName()));
            } else {
                iRootPanel.setWidget(iPanel);
                UniTimePageLabel.getInstance().setPageName(getPageName());
            }
            changeUrl();
        }

        @Override
        protected void onShow() {
            if (iTable != null)
                iTable.clearHover();
            iRootPanel.setWidget(iEventAdd);
            changeUrl();
        }
    };

    iMeetingClickHandler = new MeetingClickHandler() {
        @Override
        public void onMeetingClick(final MeetingClickEvent event) {
            if (!event.getEvent().isCanView())
                return;
            LoadingWidget.execute(EventDetailRpcRequest.requestEventDetails(iSession.getAcademicSessionId(),
                    event.getEvent().getId()), new AsyncCallback<EventInterface>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            UniTimeNotifications.error(
                                    MESSAGES.failedLoad(event.getEvent().getName(), caught.getMessage()),
                                    caught);
                        }

                        @Override
                        public void onSuccess(EventInterface result) {
                            LoadingWidget.getInstance().hide();
                            iEventDetail.setEvent(result);
                            iEventDetail.show();
                        }
                    }, MESSAGES.waitLoading(event.getEvent().getName()));
        }
    };

    iTable = new EventMeetingTable(EventMeetingTable.Mode.ListOfEvents, true, this) {
        @Override
        protected void onSortByChanded(EventComparator.EventMeetingSortBy sortBy, boolean asc) {
            changeUrl();
        }

        @Override
        protected void onColumnShownOrHid(int eventCookieFlags) {
            changeUrl();
        }
    };
    iTable.setMeetingFilter(this);
    iTable.addMouseClickListener(new MouseClickListener<EventMeetingRow>() {
        @Override
        public void onMouseClick(final TableEvent<EventMeetingRow> event) {
            if (event.getData() == null)
                return;
            final EventInterface e = event.getData().getEvent();
            if (e == null || !e.isCanView())
                return;
            LoadingWidget.execute(
                    EventDetailRpcRequest.requestEventDetails(iSession.getAcademicSessionId(), e.getId()),
                    new AsyncCallback<EventInterface>() {
                        @Override
                        public void onFailure(Throwable caught) {
                            UniTimeNotifications.error(MESSAGES.failedLoad(e.getName(), caught.getMessage()),
                                    caught);
                        }

                        @Override
                        public void onSuccess(EventInterface result) {
                            LoadingWidget.getInstance().hide();
                            iEventDetail.setEvent(result);
                            iEventDetail.show();
                        }
                    }, MESSAGES.waitLoading(e.getName()));
        }
    });

    iApproveDialog = new ApproveDialog(this) {
        @Override
        protected void onSubmit(ApproveEventRpcRequest.Operation operation, List<EventMeetingRow> data,
                String message, boolean emailConfirmation) {
            Map<EventInterface, List<MeetingInterface>> event2meetings = new HashMap<EventInterface, List<MeetingInterface>>();
            List<EventInterface> events = new ArrayList<EventInterface>();
            for (EventMeetingRow row : data) {
                if (row.getMeeting() != null) {
                    List<MeetingInterface> meetings = event2meetings.get(row.getEvent());
                    if (meetings == null) {
                        meetings = new ArrayList<EventInterface.MeetingInterface>();
                        event2meetings.put(row.getEvent(), meetings);
                        events.add(row.getEvent());
                    }
                    meetings.add(row.getMeeting());
                } else {
                    events.add(row.getEvent());
                }
            }
            onSubmit(operation, events.iterator(), event2meetings, message, emailConfirmation,
                    new GwtRpcResponseList<EventInterface>(iData));
        }

        protected void onSubmit(final ApproveEventRpcRequest.Operation operation,
                final Iterator<EventInterface> events,
                final Map<EventInterface, List<MeetingInterface>> event2meetings, final String message,
                final boolean emailConfirmation, final GwtRpcResponseList<EventInterface> data) {
            if (events.hasNext()) {
                final EventInterface event = events.next();
                List<MeetingInterface> meetings = event2meetings.get(event);
                if (meetings == null) {
                    meetings = new ArrayList<MeetingInterface>();
                    for (MeetingInterface meeting : event.getMeetings()) {
                        switch (operation) {
                        case APPROVE:
                        case REJECT:
                            if (meeting.isCanApprove() && !filter(event, meeting))
                                meetings.add(meeting);
                            break;
                        case CANCEL:
                            if (meeting.isCanCancel() && !filter(event, meeting))
                                meetings.add(meeting);
                            break;
                        case INQUIRE:
                            if (meeting.isCanInquire() && !filter(event, meeting))
                                meetings.add(meeting);
                            break;
                        }
                    }
                }
                if (meetings.isEmpty()) {
                    onSubmit(operation, events, event2meetings, message, emailConfirmation, data);
                } else {
                    switch (operation) {
                    case APPROVE:
                        LoadingWidget.getInstance().show(MESSAGES.waitForApproval(event.getName()));
                        break;
                    case INQUIRE:
                        LoadingWidget.getInstance().show(MESSAGES.waitForInquiry(event.getName()));
                        break;
                    case REJECT:
                        LoadingWidget.getInstance().show(MESSAGES.waitForRejection(event.getName()));
                        break;
                    case CANCEL:
                        LoadingWidget.getInstance().show(MESSAGES.waitForCancellation(event.getName()));
                        break;
                    }
                    RPC.execute(
                            ApproveEventRpcRequest.createRequest(operation, iSession.getAcademicSessionId(),
                                    event, meetings, message, emailConfirmation),
                            new AsyncCallback<SaveOrApproveEventRpcResponse>() {
                                @Override
                                public void onFailure(Throwable caught) {
                                    LoadingWidget.getInstance().hide();
                                    UniTimeNotifications.error(caught);
                                    onSubmit(operation, events, event2meetings, message, emailConfirmation,
                                            data);
                                }

                                @Override
                                public void onSuccess(SaveOrApproveEventRpcResponse result) {
                                    LoadingWidget.getInstance().hide();
                                    if (result.hasMessages())
                                        for (MessageInterface m : result.getMessages()) {
                                            if (m.isError())
                                                UniTimeNotifications.warn(m.getMessage());
                                            else if (m.isWarning())
                                                UniTimeNotifications.error(m.getMessage());
                                            else
                                                UniTimeNotifications.info(m.getMessage());
                                        }
                                    switch (operation) {
                                    case APPROVE:
                                    case REJECT:
                                    case CANCEL:
                                        tinker(data, event.getId(), result.getEvent());
                                    }
                                    onSubmit(operation, events, event2meetings, message, emailConfirmation,
                                            data);
                                }
                            });
                }
            } else {
                LoadingWidget.getInstance().hide();
                populate(data);
            }
        }
    };
    iTable.setOperation(EventMeetingTable.OperationType.Approve, iApproveDialog);
    iTable.setOperation(EventMeetingTable.OperationType.Reject, iApproveDialog);
    iTable.setOperation(EventMeetingTable.OperationType.Inquire, iApproveDialog);
    iTable.setOperation(EventMeetingTable.OperationType.Cancel, iApproveDialog);

    History.addValueChangeHandler(new ValueChangeHandler<String>() {
        @Override
        public void onValueChange(ValueChangeEvent<String> event) {
            if (iInitialized) {
                if ("event=add".equals(event.getValue()))
                    iHistoryToken.parse(event.getValue());
                else
                    iHistoryToken.reset(event.getValue());
                setup(false);
                if (LoadingWidget.getInstance().isShowing())
                    LoadingWidget.getInstance().hide();
            }
        }
    });
}

From source file:org.unitime.timetable.gwt.client.widgets.CourseSelectionSuggestBox.java

License:Apache License

public CourseSelectionSuggestBox(boolean showCourses, boolean showDefaultSuggestions) {
    iShowCourses = showCourses;/*w w  w . ja v  a2 s. c  o  m*/
    iShowDefaultSuggestions = showDefaultSuggestions;

    SuggestOracle courseOfferingOracle = new SuggestOracle() {
        public void requestSuggestions(Request request, Callback callback) {
            if (request.getQuery().equals(iHint))
                return;
            iDataProvider.getData(request.getQuery(), new SuggestCallback(request, callback));
        }

        public void requestDefaultSuggestions(Request request, Callback callback) {
            if (iShowDefaultSuggestions)
                iDataProvider.getData("", new SuggestCallback(request, callback));
            else
                super.requestDefaultSuggestions(request, callback);

        }

        public boolean isDisplayStringHTML() {
            return true;
        }
    };

    iSuggest = new AriaSuggestBox(courseOfferingOracle);
    iSuggest.setStyleName("unitime-TextBoxHint");

    iFinderButton = new ImageButton(RESOURCES.search_picker(), RESOURCES.search_picker_Down(),
            RESOURCES.search_picker_Over(), RESOURCES.search_picker_Disabled());
    iFinderButton.setTabIndex(-1);

    iVPanel = new VerticalPanel();

    iHPanel = new HorizontalPanel();
    iHPanel.add(iSuggest);
    iHPanel.add(iFinderButton);
    iVPanel.add(iHPanel);

    iError = new Label();
    iError.setStyleName("unitime-ErrorHint");
    iError.setVisible(false);
    Roles.getPresentationRole().setAriaHiddenState(iError.getElement(), true);
    iVPanel.add(iError);

    iFinderButton.addClickHandler(new ClickHandler() {
        public void onClick(ClickEvent event) {
            if (iSuggest.isEnabled()) {
                openDialogAsync();
            }
        }
    });

    iSuggest.addSelectionHandler(new SelectionHandler<Suggestion>() {
        public void onSelection(SelectionEvent<Suggestion> event) {
            String text = event.getSelectedItem().getReplacementString();
            iLastSuggestion = text;
            CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, text, !text.isEmpty());
        }
    });
    iSuggest.getValueBox().addChangeHandler(new ChangeHandler() {
        public void onChange(ChangeEvent event) {
            boolean valid = false;
            String text = iSuggest.getText();
            if (text.equalsIgnoreCase(iLastSuggestion))
                valid = true;
            else
                for (String course : iValidCourseNames) {
                    if (course.equalsIgnoreCase(text)) {
                        valid = true;
                        break;
                    }
                }
            CourseSelectionEvent.fire(CourseSelectionSuggestBox.this, text, valid);
        }
    });
    iSuggest.getValueBox().addKeyDownHandler(new KeyDownHandler() {
        public void onKeyDown(KeyDownEvent event) {
            if (!iSuggest.isEnabled())
                return;
            if ((event.getNativeEvent().getKeyCode() == 'F' || event.getNativeEvent().getKeyCode() == 'f')
                    && (event.isControlKeyDown() || event.isAltKeyDown())) {
                iSuggest.hideSuggestionList();
                openDialogAsync();
            }
            if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ESCAPE) {
                iSuggest.hideSuggestionList();
            }
            if ((event.getNativeEvent().getKeyCode() == 'L' || event.getNativeEvent().getKeyCode() == 'l')
                    && (event.isControlKeyDown() || event.isAltKeyDown())) {
                iSuggest.showSuggestionList();
            }
        }
    });
    iSuggest.getValueBox().addBlurHandler(new BlurHandler() {
        public void onBlur(BlurEvent event) {
            if (iSuggest.getText().isEmpty()) {
                if (iError.isVisible())
                    iError.setVisible(false);
                if (!iHint.isEmpty()) {
                    iSuggest.setText(iHint);
                    iSuggest.setStyleName("unitime-TextBoxHint");
                }
            }
        }
    });
    iSuggest.getValueBox().addFocusHandler(new FocusHandler() {
        public void onFocus(FocusEvent event) {
            iSuggest.setStyleName("gwt-SuggestBox");
            if (!iHint.isEmpty() && iSuggest.getText().equals(iHint))
                iSuggest.setText("");
            if (!iError.getText().isEmpty())
                AriaStatus.getInstance().setText(iError.getText());
        }
    });

    initWidget(iVPanel);
}