/**
  * Sends event on successful response.
  *
  * @param inMembershipCriteria Requested criterion.
  * @param found If any query results found.
  */
 private void sendSuccessEvent(
     final MembershipCriteriaDTO inMembershipCriteria, final boolean found) {
   final EventBus eventBus = Session.getInstance().getEventBus();
   if (found) {
     eventBus.notifyObservers(new MembershipCriteriaAddedEvent(inMembershipCriteria, true));
   } else {
     eventBus.notifyObservers(new MembershipCriteriaVerificationNoUsersEvent());
   }
 }
 /** Put the widget in single activity mode. */
 private void setSingleActivityMode() {
   sortPanel.setVisible(false);
   titlePanel.setVisible(false);
   postContent.setVisible(false);
   stream.setVisible(false);
   searchStatusWidget.setVisible(false);
   searchBoxWidget.setVisible(false);
   feedLinkWidget.setVisible(false);
   sortSearchRow.setVisible(false);
   EventBus.getInstance().notifyObservers(new ChangeActivityModeEvent(true));
 }
  /**
   * Initialize with strategy.
   *
   * @param inPagerStrategy the strategy.
   */
  public void init(final PagerStrategy inPagerStrategy) {
    pagerStrategy = inPagerStrategy;

    EventBus.getInstance()
        .addObserver(
            PagerResponseEvent.class,
            new Observer<PagerResponseEvent>() {
              public void update(final PagerResponseEvent event) {
                if (event.getKey().equals(pagerStrategy.getKey())) {
                  boolean enablePaging = pagerStrategy.hasNext() || pagerStrategy.hasPrev();
                  buttonContainer.setVisible(enablePaging);
                  if (enablePaging) {
                    String resultsLabel =
                        String.valueOf(pagerStrategy.getStartIndex() + 1)
                            + " - "
                            + String.valueOf(pagerStrategy.getEndIndex() + 1)
                            + " of "
                            + String.valueOf(pagerStrategy.getTotal());

                    resultsNum.setText(resultsLabel);

                    if (!pagerStrategy.hasNext()) {
                      nextButton.addStyleName(style.pagingDisabled());
                    } else {
                      nextButton.removeStyleName(style.pagingDisabled());
                    }

                    if (!pagerStrategy.hasPrev()) {
                      prevButton.addStyleName(style.pagingDisabled());
                    } else {
                      prevButton.removeStyleName(style.pagingDisabled());
                    }
                  }

                  if (pageResults.getWidgetCount() != 0) {
                    slideAnimation.slide(
                        direction, event.getWidget(), pageResults, PAGER_ANIMATION_TIME);
                  } else {
                    pageResults.add(event.getWidget());
                  }
                }
              }
            });
  }
  /** Add events. */
  private void addEvents() {
    EventBus.getInstance()
        .addObserver(
            MessageStreamAppendEvent.class,
            new Observer<MessageStreamAppendEvent>() {
              public void update(final MessageStreamAppendEvent event) {
                attachment = null;
                addLinkComposite.close();
                postBox.setText("");
                postBox.reset();
                postBox.getElement().getStyle().clearHeight();
                postOptions.removeClassName(style.visiblePostBox());
                checkPostBox();
              }
            });

    EventBus.getInstance()
        .addObserver(
            PostableStreamScopeChangeEvent.class,
            new Observer<PostableStreamScopeChangeEvent>() {
              public void update(final PostableStreamScopeChangeEvent stream) {
                currentStream = stream.getResponse();
                if (currentStream != null && !"".equals(currentStream.getDisplayName())) {
                  if (currentStream.getScopeType().equals(ScopeType.PERSON)) {
                    if (currentStream.getDisplayName().endsWith("s")) {
                      postBox.setLabel("Post to " + currentStream.getDisplayName() + "' stream...");
                    } else {
                      postBox.setLabel(
                          "Post to " + currentStream.getDisplayName() + "'s stream...");
                    }
                  } else {
                    postBox.setLabel(
                        "Post to the " + currentStream.getDisplayName() + " stream...");
                  }
                } else {
                  postBox.setLabel("Post to your stream...");
                }

                postPanel.setVisible(stream.getResponse().getScopeType() != null);
              }
            });

    EventBus.getInstance()
        .addObserver(
            MessageAttachmentChangedEvent.class,
            new Observer<MessageAttachmentChangedEvent>() {
              public void update(final MessageAttachmentChangedEvent evt) {
                attachment = evt.getAttachment();
              }
            });

    EventBus.getInstance()
        .addObserver(
            GotSystemSettingsResponseEvent.class,
            new Observer<GotSystemSettingsResponseEvent>() {
              public void update(final GotSystemSettingsResponseEvent event) {
                String warning = event.getResponse().getContentWarningText();
                if (warning != null && !warning.isEmpty()) {
                  contentWarning.setText(warning);
                } else {
                  contentWarning.setVisible(false);
                  contentWarningContainer.getStyle().setDisplay(Display.NONE);
                }
              }
            });

    Session.getInstance()
        .getEventBus()
        .addObserver(
            GotAllPopularHashTagsResponseEvent.class,
            new Observer<GotAllPopularHashTagsResponseEvent>() {
              public void update(final GotAllPopularHashTagsResponseEvent event) {
                allHashTags = new ArrayList<String>(event.getResponse());
              }
            });
  }
  /**
   * Constructor.
   *
   * @param accountId Unique ID of person to display.
   */
  public UserProfileBadgeWidget(final String accountId) {
    final FlowPanel widget = new FlowPanel();
    widget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeContainer());
    initWidget(widget);

    widget.addStyleName(StaticResourceBundle.INSTANCE.coreCss().eurekaConnectLoading());

    EventBus.getInstance()
        .addObserver(
            GotPersonalInformationResponseEvent.class,
            new Observer<GotPersonalInformationResponseEvent>() {
              public void update(final GotPersonalInformationResponseEvent event) {
                widget.removeStyleName(
                    StaticResourceBundle.INSTANCE.coreCss().eurekaConnectLoading());
                PersonModelView entity = event.getResponse();

                if (entity == null) {
                  final AvatarWidget blankAvatar = new AvatarWidget(EntityType.PERSON, Size.Normal);
                  blankAvatar.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeAvatar());

                  widget.add(blankAvatar);

                  final Label blankName = new Label(accountId);
                  blankName.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeName());

                  widget.add(blankName);
                } else {
                  AvatarLinkPanel linkPanel =
                      new AvatarLinkPanel(
                          EntityType.PERSON,
                          entity.getAccountId(),
                          entity.getAvatarId(),
                          Size.Normal,
                          false);
                  linkPanel.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeAvatar());

                  widget.add(linkPanel);

                  String linkUrl =
                      "/#"
                          + Session.getInstance()
                              .generateUrl(
                                  new CreateUrlRequest(Page.PEOPLE, entity.getAccountId()));

                  Anchor name = new Anchor(entity.getDisplayName(), linkUrl, "_BLANK");
                  name.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeName());

                  Label title = new Label(entity.getTitle());
                  title.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeTitle());

                  Label company = new Label(entity.getCompanyName());
                  company.addStyleName(
                      StaticResourceBundle.INSTANCE.coreCss().eurekaConnectBadgeCompany());

                  widget.add(name);
                  widget.add(title);
                  widget.add(company);
                }
              }
            });

    PersonalInformationModel.getInstance().fetch(accountId, false);
  }
  /** Wires up events. */
  private void setupEvents() {
    // user clicked in message text box
    message.addFocusHandler(
        new FocusHandler() {
          public void onFocus(final FocusEvent inEvent) {
            if ((" " + getStyleName() + " ")
                .contains(StaticResourceBundle.INSTANCE.coreCss().small())) {
              removeStyleName(StaticResourceBundle.INSTANCE.coreCss().small());
              onExpand();
            }
          }
        });

    message.addValueChangedHandler(
        new ValueChangeHandler<String>() {
          public void onValueChange(final ValueChangeEvent<String> newValue) {
            checkMessageTextChanged();
          }
        });

    // user typed in message text box
    message.addKeystrokeHandler(
        new KeyUpHandler() {
          public void onKeyUp(final KeyUpEvent ev) {
            if (ev.getNativeKeyCode() == KeyCodes.KEY_ENTER
                && ev.isControlKeyDown()
                && message.getText().length() > 0) {
              checkMessageTextChanged();
              handlePostMessage();
            } else {
              checkMessageTextChanged();
            }
          }
        });

    // user clicked on post button
    postButton.addClickHandler(
        new ClickHandler() {
          public void onClick(final ClickEvent ev) {
            checkMessageTextChanged();
            handlePostMessage();
          }
        });

    final EventBus eventBus = Session.getInstance().getEventBus();
    eventBus.addObserver(
        MessageStreamAppendEvent.class,
        new Observer<MessageStreamAppendEvent>() {
          public void update(final MessageStreamAppendEvent event) {
            errorMsg.setVisible(false);
            addStyleName(StaticResourceBundle.INSTANCE.coreCss().small());
            messageText = "";
            message.setText(postBoxDefaultText);
            onRemainingCharactersChanged();
            links.close();
          }
        });

    eventBus.addObserver(
        GotSystemSettingsResponseEvent.class,
        new Observer<GotSystemSettingsResponseEvent>() {
          public void update(final GotSystemSettingsResponseEvent event) {
            String warning = event.getResponse().getContentWarningText();
            if (warning != null && !warning.isEmpty()) {
              contentWarning.getElement().setInnerHTML(warning);
            } else {
              contentWarning.setVisible(false);
            }
            message.setVisible(true);
          }
        });

    eventBus.addObserver(
        MessageTextAreaChangedEvent.getEvent(),
        new Observer<MessageTextAreaChangedEvent>() {
          public void update(final MessageTextAreaChangedEvent arg1) {
            // the value changed - make sure we're not stuck in the disabled, non-editable mode
            if ((" " + getStyleName() + " ")
                .contains(StaticResourceBundle.INSTANCE.coreCss().small())) {
              removeStyleName(StaticResourceBundle.INSTANCE.coreCss().small());
            }
            onRemainingCharactersChanged();
          }
        });

    eventBus.addObserver(
        MessageAttachmentChangedEvent.class,
        new Observer<MessageAttachmentChangedEvent>() {
          public void update(final MessageAttachmentChangedEvent evt) {
            errorMsg.setVisible(false);
            attachment = evt.getAttachment();
            if (attachment == null && messageText.isEmpty()) {
              hidePostButton();
            } else {
              showPostButton();
            }
          }
        });

    eventBus.addObserver(
        new ErrorPostingMessageToNullScopeEvent(),
        new Observer<ErrorPostingMessageToNullScopeEvent>() {
          public void update(final ErrorPostingMessageToNullScopeEvent event) {
            errorMsg.setText(event.getErrorMsg());
            errorMsg.setVisible(true);
            showPostButton();
          }
        });
  }
 /**
  * Fires of the UpdateGadgetPrefsEvent when called from the gadget container.
  *
  * @param inId - id of the gadget being updated.
  * @param inPrefs - updated preferences for the gadget.
  */
 public static void updateGadgetPrefs(final int inId, final String inPrefs) {
   UpdateGadgetPrefsEvent event = new UpdateGadgetPrefsEvent(new Long(inId), inPrefs);
   EventBus.getInstance().notifyObservers(event);
 }
 /**
  * Fires off a gadget change state event.
  *
  * @param id the gadget id
  * @param view the view to set.
  * @param params the optional parameters.
  */
 public static void changeGadgetState(final int id, final String view, final String params) {
   GadgetStateChangeEvent event =
       new GadgetStateChangeEvent(new Long(id), "gadgetId", view, params);
   EventBus.getInstance().notifyObservers(event);
 }
  /** Method that gets called during load of the EntryPoint. */
  public void onModuleLoad() {
    // The entry point will be invoked when just a Eureka Connect widget is desired, so do nothing
    // if the
    // appropriate full-app element is not found
    rootPanel = RootPanel.get(FULL_APP_ELEMENT_ID);
    if (rootPanel == null) {
      return;
    }

    ActionRPCServiceAsync service = (ActionRPCServiceAsync) GWT.create(ActionRPCService.class);
    processor = new ActionProcessorImpl(service);

    ((ServiceDefTarget) service).setServiceEntryPoint("/gwt_rpc");

    StaticResourceBundle.INSTANCE.coreCss().ensureInjected();
    StaticResourceBundle.INSTANCE.yuiCss().ensureInjected();

    session.setActionProcessor(processor);
    session.setEventBus(EventBus.getInstance());
    session.setPeriodicEventManager(
        new PeriodicEventManager(APP_IDLE_TIMEOUT, new TimerFactory(), processor));

    master = new MasterComposite();

    EventBus.getInstance()
        .addObserver(
            FormLoginCompleteEvent.class,
            new Observer<FormLoginCompleteEvent>() {
              public void update(final FormLoginCompleteEvent event) {
                Window.Location.reload();
              }
            });

    EventBus.getInstance()
        .addObserver(
            TermsOfServiceAcceptedEvent.class,
            new Observer<TermsOfServiceAcceptedEvent>() {
              public void update(final TermsOfServiceAcceptedEvent event) {
                displayTOS = false;
                loadPerson();
              }
            });

    setUpGwtFunctions();

    processor.makeRequest(
        new ActionRequestImpl<PersonModelView>("noOperation", null),
        new AsyncCallback<Serializable>() {
          public void onFailure(final Throwable caught) {
            if (caught.getMessage().contains("NO_CREDENTIALS")) {
              showLogin();
            } else if (caught.getMessage().contains("LOGIN_DISABLED")) {
              Window.Location.assign(ACCESS_DENIED_PAGE);
            } else {
              Dialog.showCentered(
                  new MessageDialogContent("Unable to Establish Connection", "Please Refresh."));
            }
          }

          public void onSuccess(final Serializable sessionId) {
            ActionProcessorImpl.setCurrentSessionId((String) sessionId);

            loadPerson();
          }
        });
  }
  /**
   * Initialize page.
   *
   * @param inShowRecipients if recipients should be shown.
   * @param itemRenderer Renderer for activities.
   */
  public StreamPanel(
      final ShowRecipient inShowRecipients, final ItemRenderer<ActivityDTO> itemRenderer) {
    addStyleName(StaticResourceBundle.INSTANCE.coreCss().layoutContainer());

    stream = new StreamListPanel(itemRenderer);
    stream.addStyleName(StaticResourceBundle.INSTANCE.coreCss().stream());
    stream.setVisible(false);

    // @author cm325 need to expose id
    stream.getElement().setId("ym-expose-stream-panel-stream");

    shadowPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().postToStreamContainer());
    shadowPanel.setVisible(false);

    searchBoxWidget = new StreamSearchBoxWidget();
    searchStatusWidget = new StreamSearchStatusWidget();

    lockedMessage.setVisible(false);
    error.setVisible(false);

    postContent.add(shadowPanel);

    titlePanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().streamTitlebar());
    streamTitleWidget = new StreamTitleWidget();
    titlePanel.add(streamTitleWidget);
    addGadgetWidget = new StreamAddAppWidget();
    titlePanel.add(addGadgetWidget);

    sortSearchRow.addStyleName(StaticResourceBundle.INSTANCE.coreCss().navpanel());
    sortSearchRow.add(sortPanel);
    sortSearchRow.add(feedLinkWidget);
    sortSearchRow.add(searchBoxWidget);

    // @author cm325 need to expose id
    sortSearchRow.getElement().setId("ym-expose-stream-panel-sort-search-row");

    this.add(postContent);
    this.add(titlePanel);
    this.add(searchStatusWidget);
    this.add(new UnseenActivityNotificationPanel());
    this.add(sortSearchRow);
    this.add(error);
    this.add(lockedMessage);
    this.add(stream);
    this.add(activityDetailPanel);

    stream.reinitialize();

    // ---- Wire up events ----
    final EventBus eventBus = Session.getInstance().getEventBus();

    eventBus.addObserver(
        UpdatedHistoryParametersEvent.class,
        new Observer<UpdatedHistoryParametersEvent>() {
          public void update(final UpdatedHistoryParametersEvent event) {
            checkHistory(event.getParameters());

            // Only process this once.
            eventBus.removeObserver(UpdatedHistoryParametersEvent.class, this);
          }
        },
        true);

    eventBus.addObserver(
        UpdatedHistoryParametersEvent.class,
        new Observer<UpdatedHistoryParametersEvent>() {
          public void update(final UpdatedHistoryParametersEvent event) {
            if (checkHistory(event.getParameters())) {
              eventBus.notifyObservers(StreamReinitializeRequestEvent.getEvent());
            }
          }
        });

    eventBus.addObserver(
        GotActivityResponseEvent.class,
        new Observer<GotActivityResponseEvent>() {
          public void update(final GotActivityResponseEvent event) {
            setSingleActivityMode();
            activityDetailPanel.clear();
            activityDetailPanel.add(new ActivityDetailPanel(event.getResponse(), inShowRecipients));
          }
        });

    eventBus.addObserver(
        StreamRequestMoreEvent.class,
        new Observer<StreamRequestMoreEvent>() {
          public void update(final StreamRequestMoreEvent arg1) {
            JSONObject jsonObj = StreamJsonRequestFactory.getJSONRequest(jsonQuery);
            jsonObj = StreamJsonRequestFactory.setMaxId(lastSeenId, jsonObj);

            // Must be sorted by date to request more.
            jsonObj = StreamJsonRequestFactory.setSort("date", jsonObj);

            if (!search.isEmpty()) {
              searchBoxWidget.setSearchTerm(search);
              searchStatusWidget.setSearchTerm(search);

              jsonObj = StreamJsonRequestFactory.setSearchTerm(search, jsonObj);
            }

            StreamModel.getInstance().fetch(jsonObj.toString(), false);
          }
        });

    eventBus.addObserver(
        GotStreamResponseEvent.class,
        new Observer<GotStreamResponseEvent>() {
          public void update(final GotStreamResponseEvent event) {
            PagedSet<ActivityDTO> activity = event.getStream();

            int numberOfActivities = activity.getPagedSet().size();
            if (numberOfActivities > 0) {
              lastSeenId = activity.getPagedSet().get(numberOfActivities - 1).getId();
            }

            MessageStreamUpdateEvent updateEvent = new MessageStreamUpdateEvent(activity);
            updateEvent.setMoreResults(activity.getTotal() > activity.getPagedSet().size());

            error.setText("");
            error.setVisible(false);
            eventBus.notifyObservers(updateEvent);
            stream.setVisible(true);
          }
        });

    eventBus.addObserver(
        StreamReinitializeRequestEvent.class,
        new Observer<StreamReinitializeRequestEvent>() {
          public void update(final StreamReinitializeRequestEvent event) {
            eventBus.notifyObservers(new StreamRequestEvent(streamName, jsonQuery, true));
          }
        });

    eventBus.addObserver(
        MessageStreamAppendEvent.class,
        new Observer<MessageStreamAppendEvent>() {
          public void update(final MessageStreamAppendEvent evt) {
            if ("date".equals(sortPanel.getSort())) {
              eventBus.notifyObservers(StreamReinitializeRequestEvent.getEvent());
            } else {
              sortPanel.updateSelected("date", true);
            }
          }
        });

    eventBus.addObserver(
        StreamRequestEvent.class,
        new Observer<StreamRequestEvent>() {
          public void update(final StreamRequestEvent event) {
            if (event.getForceReload() || !event.getJson().equals(jsonQuery)) {
              streamName = event.getStreamName();
              jsonQuery = event.getJson();
              if (activityId != 0L) {
                ActivityModel.getInstance().fetch(activityId, false);
              } else {
                setListMode();
                stream.reinitialize();

                String titleLinkUrl = null;
                String updatedJson = jsonQuery;
                JSONObject queryObject =
                    JSONParser.parse(updatedJson).isObject().get("query").isObject();

                // Only show cancel option if search is not part of the view.
                Boolean canChange = !queryObject.containsKey("keywords");

                if (queryObject.containsKey("keywords")) {
                  final String streamSearchText =
                      queryObject.get("keywords").isString().stringValue();

                  searchBoxWidget.setSearchTerm(streamSearchText);
                  searchStatusWidget.setSearchTerm(streamSearchText);

                  updatedJson =
                      StreamJsonRequestFactory.setSearchTerm(
                              streamSearchText,
                              StreamJsonRequestFactory.getJSONRequest(updatedJson))
                          .toString();
                } else if (!search.isEmpty()) {
                  searchBoxWidget.setSearchTerm(search);
                  searchStatusWidget.setSearchTerm(search);

                  updatedJson =
                      StreamJsonRequestFactory.setSearchTerm(
                              search, StreamJsonRequestFactory.getJSONRequest(updatedJson))
                          .toString();

                }
                // see if the stream belongs to a group and set up the stream title as a link
                else if (queryObject.containsKey("recipient")
                    && queryObject.get("recipient").isArray().size() == 1) {
                  JSONArray recipientArr = queryObject.get("recipient").isArray();
                  JSONObject recipientObj = recipientArr.get(0).isObject();

                  // only show the link if viewing a group stream on the activity page
                  if ("GROUP".equals(recipientObj.get("type").isString().stringValue())
                      && Session.getInstance().getUrlPage() == Page.ACTIVITY) {
                    String shortName = recipientObj.get("name").isString().stringValue();
                    titleLinkUrl =
                        Session.getInstance()
                            .generateUrl(new CreateUrlRequest(Page.GROUPS, shortName));
                  }
                  searchBoxWidget.onSearchCanceled();
                  searchStatusWidget.onSearchCanceled();
                } else {
                  searchBoxWidget.onSearchCanceled();
                  searchStatusWidget.onSearchCanceled();
                }

                sort = sortPanel.getSort();

                updatedJson =
                    StreamJsonRequestFactory.setSort(
                            sort, StreamJsonRequestFactory.getJSONRequest(updatedJson))
                        .toString();

                streamTitleWidget.setStreamTitle(streamName, titleLinkUrl);
                addGadgetWidget.setStreamTitle(streamName);
                searchBoxWidget.setCanChange(canChange);
                searchStatusWidget.setCanChange(canChange);

                StreamModel.getInstance().fetch(updatedJson, false);
              }
            }
          }
        });

    eventBus.addObserver(
        StreamSearchBeginEvent.class,
        new Observer<StreamSearchBeginEvent>() {
          public void update(final StreamSearchBeginEvent event) {
            eventBus.notifyObservers(
                new UpdateHistoryEvent(
                    new CreateUrlRequest("search", event.getSearchText(), false)));
          }
        });

    eventBus.addObserver(
        DeletedActivityResponseEvent.class,
        new Observer<DeletedActivityResponseEvent>() {
          public void update(final DeletedActivityResponseEvent ev) {
            eventBus.notifyObservers(
                new ShowNotificationEvent(new Notification("Activity has been deleted")));
          }
        });
  }