public ComposeNewMessage(String id) {
    super(id);

    // current user
    final String userId = sakaiProxy.getCurrentUserId();

    // setup model
    NewMessageModel newMessage = new NewMessageModel();
    newMessage.setFrom(userId);

    // feedback for form submit action
    formFeedback = new Label("formFeedback");
    formFeedback.setOutputMarkupPlaceholderTag(true);
    add(formFeedback);

    // setup form
    final Form<NewMessageModel> form =
        new Form<NewMessageModel>("form", new Model<NewMessageModel>(newMessage));

    // close button
    /*
    WebMarkupContainer closeButton = new WebMarkupContainer("closeButton");
    closeButton.add(new AjaxFallbackLink<Void>("link") {
    	private static final long serialVersionUID = 1L;

    	public void onClick(AjaxRequestTarget target) {
    		if(target != null) {
    			target.prependJavascript("$('#" + thisPanel.getMarkupId() + "').slideUp();");
    			target.appendJavascript("setMainFrameHeight(window.name);");
    		}
    	}
    }.add(new ContextImage("img",new Model<String>(ProfileConstants.CLOSE_IMAGE))));
    form.add(closeButton);
    */

    // to label
    form.add(new Label("toLabel", new ResourceModel("message.to")));

    // get connections
    final List<Person> connections = connectionsLogic.getConnectionsForUser(userId);
    Collections.sort(connections);

    // list provider
    AutoCompletionChoicesProvider<Person> provider =
        new AutoCompletionChoicesProvider<Person>() {
          private static final long serialVersionUID = 1L;

          public Iterator<Person> getChoices(String input) {
            return connectionsLogic
                .getConnectionsSubsetForSearch(connections, input, true)
                .iterator();
          }
        };

    // renderer
    ObjectAutoCompleteRenderer<Person> renderer =
        new ObjectAutoCompleteRenderer<Person>() {
          private static final long serialVersionUID = 1L;

          protected String getIdValue(Person p) {
            return p.getUuid();
          }

          protected String getTextValue(Person p) {
            return p.getDisplayName();
          }
        };

    // autocompletefield builder
    ObjectAutoCompleteBuilder<Person, String> builder =
        new ObjectAutoCompleteBuilder<Person, String>(provider);
    builder.autoCompleteRenderer(renderer);
    builder.searchLinkImage(ResourceReferences.CROSS_IMG_LOCAL);
    builder.preselect();

    // autocompletefield
    final ObjectAutoCompleteField<Person, String> autocompleteField =
        builder.build("toField", new PropertyModel<String>(newMessage, "to"));
    toField = autocompleteField.getSearchTextField();
    toField.setMarkupId("messagerecipientinput");
    toField.setOutputMarkupId(true);
    toField.add(new AttributeModifier("class", true, new Model<String>("formInputField")));
    toField.setRequired(true);
    form.add(autocompleteField);

    // subject
    form.add(new Label("subjectLabel", new ResourceModel("message.subject")));
    final TextField<String> subjectField =
        new TextField<String>("subjectField", new PropertyModel<String>(newMessage, "subject"));
    subjectField.setMarkupId("messagesubjectinput");
    subjectField.setOutputMarkupId(true);
    subjectField.add(new RecipientEventBehavior("onfocus"));
    form.add(subjectField);

    // body
    form.add(new Label("messageLabel", new ResourceModel("message.message")));
    final TextArea<String> messageField =
        new TextArea<String>("messageField", new PropertyModel<String>(newMessage, "message"));
    messageField.setMarkupId("messagebodyinput");
    messageField.setOutputMarkupId(true);
    messageField.setRequired(true);
    messageField.add(new RecipientEventBehavior("onfocus"));
    form.add(messageField);

    // send button
    IndicatingAjaxButton sendButton =
        new IndicatingAjaxButton("sendButton", form) {
          private static final long serialVersionUID = 1L;

          protected void onSubmit(AjaxRequestTarget target, Form form) {

            // get the backing model
            NewMessageModel newMessage = (NewMessageModel) form.getModelObject();

            // generate the thread id
            String threadId = ProfileUtils.generateUuid();

            // save it, it will be abstracted into its proper parts and email notifications sent
            if (messagingLogic.sendNewMessage(
                newMessage.getTo(),
                newMessage.getFrom(),
                threadId,
                newMessage.getSubject(),
                newMessage.getMessage())) {

              // post event
              sakaiProxy.postEvent(
                  ProfileConstants.EVENT_MESSAGE_SENT, "/profile/" + newMessage.getTo(), true);

              // success
              formFeedback.setDefaultModel(new ResourceModel("success.message.send.ok"));
              formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));

              // target.appendJavascript("$('#" + form.getMarkupId() + "').slideUp();");
              target.appendJavaScript("setMainFrameHeight(window.name);");

              // PRFL-797 all fields when successful, to prevent multiple messages.
              // User can just click Compose message again to get a new form
              this.setEnabled(false);
              autocompleteField.setEnabled(false);
              subjectField.setEnabled(false);
              messageField.setEnabled(false);
              target.add(this);
              target.add(autocompleteField);
              target.add(subjectField);
              target.add(messageField);

            } else {
              // error
              formFeedback.setDefaultModel(new ResourceModel("error.message.send.failed"));
              formFeedback.add(
                  new AttributeModifier("class", true, new Model<String>("alertMessage")));
            }

            formFeedback.setVisible(true);
            target.add(formFeedback);
          }

          protected void onError(AjaxRequestTarget target, Form form) {

            // check which item didn't validate and update the feedback model
            if (!toField.isValid()) {
              formFeedback.setDefaultModel(new ResourceModel("error.message.required.to"));
            }
            if (!messageField.isValid()) {
              formFeedback.setDefaultModel(new ResourceModel("error.message.required.body"));
            }
            formFeedback.add(
                new AttributeModifier("class", true, new Model<String>("alertMessage")));

            target.add(formFeedback);
          }
        };
    form.add(sendButton);
    sendButton.setModel(new ResourceModel("button.message.send"));

    add(form);
  }
  private void constructPageComponent() {
    add(new FeedbackPanel("errorMessages"));

    errorMsg =
        new Label(
            "smsAuthenticationError", getLocalizer().getString("smsAuthentication.error", this));
    errorMsg.setVisible(false);
    errorMsg.setOutputMarkupId(true);
    errorMsg.setOutputMarkupPlaceholderTag(true);

    final WebMarkupContainer backDiv = new WebMarkupContainer("backDiv");
    backDiv.setOutputMarkupId(true);
    backDiv.setVisible(false);
    backDiv.setOutputMarkupPlaceholderTag(true);
    Form<?> backForm = new Form("backForm", new CompoundPropertyModel<SmsAuthenticationPage>(this));
    backForm.add(
        new Button("back") {
          @Override
          public void onSubmit() {
            // TODO
          }
        });
    backDiv.add(backForm);

    retryDiv = new WebMarkupContainer("retryDiv");
    retryDiv.setOutputMarkupId(true);
    retryDiv.setOutputMarkupPlaceholderTag(true);
    retryDiv.setVisible(false);
    Form<?> retryForm =
        new Form("retryForm", new CompoundPropertyModel<SmsAuthenticationPage>(this));
    retryForm.add(
        new Button("retry") {
          @Override
          public void onSubmit() {
            // TODO
          }
        });
    retryDiv.add(retryForm);

    cancelDiv = new WebMarkupContainer("cancelDiv");
    cancelDiv.setOutputMarkupId(true);
    cancelDiv.setOutputMarkupPlaceholderTag(true);
    cancelDiv.setVisible(false);
    Form<?> cancelForm =
        new Form("cancelForm", new CompoundPropertyModel<SmsAuthenticationPage>(this));
    cancelForm.add(
        new Button("cancel") {
          @Override
          public void onSubmit() {
            // TODO
          }
        }.setVisible(false));
    cancelDiv.add(cancelForm);

    final AbstractDefaultAjaxBehavior behave =
        new AbstractDefaultAjaxBehavior() {
          protected void respond(final AjaxRequestTarget target) {
            if (!isRedirected) {
              checkStatus(target);
            }
          }
        };
    add(behave);

    Form<?> ajaxForm =
        new Form("ajaxForm", new CompoundPropertyModel<SmsAuthenticationPage>(this)) {
          @Override
          protected void onComponentTag(ComponentTag tag) {
            super.onComponentTag(tag);
            tag.put("action", behave.getCallbackUrl());
          }
        };
    add(errorMsg);
    add(backDiv);
    add(retryDiv);
    add(cancelDiv);
    add(ajaxForm);
  }
  private void build() {

    feedbackPanel = new FeedbackPanel("feedback");
    add(feedbackPanel);

    form = new Form("questionForm");
    form.setOutputMarkupId(true);

    questionTitleField = new TextField("questionTitleField", new Model(""));
    questionTitleField.setRequired(true);
    questionTitleField.add(new FocusOnLoadBehavior());
    form.add(questionTitleField);

    if (question.getType().equals(Question.QuestionType.ALTER)) {
      form.add(new Label("promptHelpText", "(Refer to the alter as $$)"));
    } else if (question.getType().equals(Question.QuestionType.ALTER_PAIR)) {
      form.add(new Label("promptHelpText", "(Refer to the alters as $$1 and $$2)"));
    } else {
      form.add(new Label("promptHelpText", ""));
    }

    numericLimitsPanel = new NumericLimitsPanel("numericLimitsPanel", question);
    form.add(numericLimitsPanel);
    numericLimitsPanel.setVisible(false);

    multipleSelectionLimitsPanel = new MultipleSelectionLimitsPanel("multipleSelectionLimitsPanel");
    form.add(multipleSelectionLimitsPanel);
    multipleSelectionLimitsPanel.setVisible(false);

    timeUnitsPanel = new TimeUnitsPanel("timeUnitsPanel", question);
    form.add(timeUnitsPanel);
    timeUnitsPanel.setVisible(false);

    listLimitsPanel = new ListLimitsPanel("listLimitsPanel", question);
    form.add(listLimitsPanel);
    listLimitsPanel.setVisible(question.getAskingStyleList());

    questionPromptField = new TextArea("questionPromptField", new Model(""));
    questionPromptField.setRequired(true);
    form.add(questionPromptField);

    questionPrefaceField = new TextArea("questionPrefaceField", new Model(""));
    form.add(questionPrefaceField);

    questionCitationField = new TextArea("questionCitationField", new Model(""));
    form.add(questionCitationField);

    questionResponseTypeModel = new Model(Answer.AnswerType.TEXTUAL); // Could also leave this null.
    dropDownQuestionTypes =
        new DropDownChoice(
            "questionResponseTypeField",
            questionResponseTypeModel,
            Arrays.asList(Answer.AnswerType.values()));

    dropDownQuestionTypes.add(
        new AjaxFormComponentUpdatingBehavior("onchange") {
          protected void onUpdate(AjaxRequestTarget target) {
            onSelectionChanged(Integer.parseInt(dropDownQuestionTypes.getModelValue()));
            // target.addComponent(form);
            target.addComponent(numericLimitsPanel);
            target.addComponent(multipleSelectionLimitsPanel);
            target.addComponent(noneButtonLabel);
            target.addComponent(noneButtonCheckBox);
            target.addComponent(otherSpecifyLabel);
            target.addComponent(otherSpecifyCheckBox);
            target.addComponent(timeUnitsPanel);
            target.addComponent(listLimitsPanel);
          }
        });

    form.add(dropDownQuestionTypes);

    questionAnswerReasonModel = new Model(answerAlways);
    List<Object> answerChoices = new ArrayList<Object>();
    answerChoices.add(answerAlways);
    for (Expression expression : Expressions.forStudy(question.getStudyId())) {
      answerChoices.add(expression);
    }
    form.add(
        new DropDownChoice("questionAnswerReasonField", questionAnswerReasonModel, answerChoices));

    Label askingStyleListLabel = new Label("askingStyleListLabel", "Ask with list of alters:");
    askingStyleModel = new Model();
    askingStyleModel.setObject(Boolean.FALSE);
    AjaxCheckBox askingStyleListField =
        new AjaxCheckBox("askingStyleListField", askingStyleModel) {
          protected void onUpdate(AjaxRequestTarget target) {
            Boolean listLimitsVisible = false;

            if (questionResponseTypeModel.getObject().equals(Answer.AnswerType.MULTIPLE_SELECTION)
                || questionResponseTypeModel.getObject().equals(Answer.AnswerType.SELECTION))
              listLimitsVisible = (Boolean) askingStyleModel.getObject();

            listLimitsPanel.setVisible(listLimitsVisible);
            target.addComponent(form);
          }
        };
    askingStyleListLabel.setOutputMarkupId(true);
    askingStyleListLabel.setOutputMarkupPlaceholderTag(true);
    askingStyleListField.setOutputMarkupId(true);
    askingStyleListField.setOutputMarkupPlaceholderTag(true);
    form.add(askingStyleListLabel);
    form.add(askingStyleListField);
    if (question.getType().equals(Question.QuestionType.EGO)
        || question.getType().equals(Question.QuestionType.EGO_ID)) {
      askingStyleListLabel.setVisible(false);
      askingStyleListField.setVisible(false);
    }

    otherSpecifyLabel = new Label("otherSpecifyLabel", "Other/Specify Type Question?: ");
    otherSpecifyModel = new Model();
    otherSpecifyModel.setObject(Boolean.FALSE);
    otherSpecifyCheckBox = new CheckBox("otherSpecifyField", otherSpecifyModel);
    form.add(otherSpecifyLabel);
    form.add(otherSpecifyCheckBox);
    otherSpecifyLabel.setOutputMarkupId(true);
    otherSpecifyCheckBox.setOutputMarkupId(true);
    otherSpecifyLabel.setOutputMarkupPlaceholderTag(true);
    otherSpecifyCheckBox.setOutputMarkupPlaceholderTag(true);
    noneButtonLabel = new Label("noneButtonLabel", "NONE Button?: ");
    noneButtonModel = new Model();
    noneButtonModel.setObject(Boolean.FALSE);
    noneButtonCheckBox = new CheckBox("noneButtonField", noneButtonModel);
    form.add(noneButtonLabel);
    form.add(noneButtonCheckBox);
    noneButtonLabel.setOutputMarkupId(true);
    noneButtonCheckBox.setOutputMarkupId(true);
    noneButtonLabel.setOutputMarkupPlaceholderTag(true);
    noneButtonCheckBox.setOutputMarkupPlaceholderTag(true);
    noneButtonLabel.setVisible(false);
    noneButtonCheckBox.setVisible(false);

    // questionUseIfField = new TextField("questionUseIfField", new Model(""));
    // form.add(questionUseIfField);

    form.add(
        new AjaxFallbackButton("submitQuestion", form) {
          @Override
          public void onSubmit(AjaxRequestTarget target, Form form) {
            insertFormFieldsIntoQuestion(question);
            if (question.getId() == null) {
              List<Question> questions =
                  Questions.getQuestionsForStudy(question.getStudyId(), question.getType());
              questions.add(question);
              for (Integer i = 0; i < questions.size(); i++) {
                questions.get(i).setOrdering(i);
                DB.save(questions.get(i));
              }
            } else {
              DB.save(question);
            }
            form.setVisible(false);
            target.addComponent(parentThatNeedsUpdating);
            target.addComponent(form);
          }
        });
    add(form);

    setFormFieldsFromQuestion(question);
  }
Beispiel #4
0
  /**
   * Constructor that is invoked when page is invoked without a session.
   *
   * @param parameters Page parameters
   */
  public JavascriptPage(final PageParameters parameters) {
    super("Javascript binding");

    // Container to insert the wiQuery javascript binding
    Form<String> jsForm = new Form<String>("jsForm");
    add(jsForm);

    feedback = new FeedbackPanel("feedback");
    feedback.setOutputMarkupId(true);
    jsForm.add(feedback);

    StringBuffer exampleJavaCode = new StringBuffer();
    exampleJavaCode.append("Options options = new Options();");
    exampleJavaCode.append("\n");
    exampleJavaCode.append("options.put(\"autoOpen\", false);");
    exampleJavaCode.append("\n");
    exampleJavaCode.append("\n");
    exampleJavaCode.append(
        "return new JsQuery(component).$().chain(\"dialog\", \"open\", options.getJavaScriptOptions());");

    binding = new Model<String>(exampleJavaCode.toString());
    TextArea<String> jsCode = new TextArea<String>("jsCode", binding);
    jsCode.add(new StringValidator.MaximumLengthValidator(200));
    jsForm.add(jsCode);

    AjaxSubmitLink jsSubmit =
        new AjaxSubmitLink("jsSubmit") {
          private static final long serialVersionUID = 1L;

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#getAjaxCallDecorator()
           */
          @Override
          protected IAjaxCallDecorator getAjaxCallDecorator() {
            AjaxPreprocessingCallDecorator pre =
                new AjaxPreprocessingCallDecorator(null) {
                  private static final long serialVersionUID = 1L;

                  /* (non-Javadoc)
                   * @see org.apache.wicket.ajax.calldecorator.AjaxPreprocessingCallDecorator#decorateScript(java.lang.CharSequence)
                   */
                  @Override
                  public CharSequence decorateScript(CharSequence script) {
                    return "this.disabled=true; this.value='Generating';" + script;
                  }
                };

            AjaxPostprocessingCallDecorator post =
                new AjaxPostprocessingCallDecorator(pre) {
                  private static final long serialVersionUID = 1L;

                  /* (non-Javadoc)
                   * @see org.apache.wicket.ajax.calldecorator.AjaxPostprocessingCallDecorator#postDecorateOnSuccessScript(java.lang.CharSequence)
                   */
                  @Override
                  public CharSequence postDecorateOnSuccessScript(CharSequence script) {
                    return script + "this.disabled=false; this.value='Generate';";
                  }
                };
            return post;
          }

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#onError(org.apache.wicket.ajax.AjaxRequestTarget, org.apache.wicket.markup.html.form.Form)
           */
          @Override
          protected void onError(AjaxRequestTarget target, Form<?> form) {
            super.onError(target, form);

            target.addComponent(feedback);
          }

          /* (non-Javadoc)
           * @see org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink#onSubmit(org.apache.wicket.ajax.AjaxRequestTarget, org.apache.wicket.markup.html.form.Form)
           */
          @Override
          protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
            try {
              getSession().cleanupFeedbackMessages();

              StringBuffer groovyScript = new StringBuffer();
              groovyScript.append("import org.odlabs.wiquery.core.javascript.*;").append("\n");
              groovyScript
                  .append("import org.odlabs.wiquery.core.javascript.helper.*")
                  .append("\n");
              groovyScript.append("import org.odlabs.wiquery.ui.core.*;").append("\n");
              groovyScript.append("import org.odlabs.wiquery.core.options.*;").append("\n");
              groovyScript.append(binding.getObject());

              GroovyCodeSource codeSource =
                  new GroovyCodeSource(
                      groovyScript.toString(), "wiQueryScript", "/serverCodeBase/restrictedClient");

              GroovyShell groovyShell = ((WicketApplication) getApplication()).getGroovyShell();
              groovyShell.setVariable("component", jsGenerated);
              Object returnObject = groovyShell.evaluate(codeSource);

              if (returnObject instanceof JsStatement
                  || returnObject instanceof JsQuery
                  || returnObject instanceof JsScope) {

                String render = null;

                if (returnObject instanceof JsStatement) {
                  render = ((JsStatement) returnObject).render().toString();

                } else if (returnObject instanceof JsQuery) {
                  render = ((JsQuery) returnObject).getStatement().render().toString();

                } else {
                  render = ((JsScope) returnObject).render().toString();
                }

                jsGenerated.setDefaultModelObject(render);

              } else {
                error("The Java code must return a JsQuery or a JsStatement or a JsScope");
                jsGenerated.setDefaultModelObject("");
              }

            } catch (Exception e) {
              error("Generation error / Bad syntax");
              jsGenerated.setDefaultModelObject("");
              e.printStackTrace();
            }

            target.addComponent(feedback);
            target.addComponent(jsGenerated);
          }
        };
    jsForm.add(jsSubmit);

    // Container to display generatd javascript
    jsGenerated = new Label("jsGenerated", new Model<String>());
    jsGenerated.setOutputMarkupPlaceholderTag(true);
    add(jsGenerated);
  }