Exemplo n.º 1
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    StringBuffer person = null;
    try {
      ec.addElement(new StringElement(WebGoatI18N.get("EnterYourName") + ": "));

      person = new StringBuffer(s.getParser().getStringParameter(PERSON, ""));
      person.reverse();

      Input input = new Input(Input.TEXT, PERSON, person.toString());
      ec.addElement(input);

      Element b = ECSFactory.makeButton(WebGoatI18N.get("Go!"));
      ec.addElement(b);
    } catch (Exception e) {
      s.setMessage("Error generating " + this.getClass().getName());
      e.printStackTrace();
    }

    if (!person.toString().equals("") && getLessonTracker(s).getNumVisits() > 3) {
      makeSuccess(s);
    }

    return (ec);
  }
Exemplo n.º 2
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();
    Element b = ECSFactory.makeButton("Start the Course!");
    ec.addElement(new Center(b));

    return (ec);
  }
Exemplo n.º 3
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element makeInput(WebSession s) {
    Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
    TR row1 = new TR();
    TR row2 = new TR();
    row1.addElement(new TD(new StringElement(WebGoatI18N.get("Title") + ": ")));

    Input inputTitle = new Input(Input.TEXT, TITLE, "");
    row1.addElement(new TD(inputTitle));

    TD item1 = new TD();
    item1.setVAlign("TOP");
    item1.addElement(new StringElement(WebGoatI18N.get("Message") + ": "));
    row2.addElement(item1);

    TD item2 = new TD();
    TextArea ta = new TextArea(MESSAGE, 5, 60);
    item2.addElement(ta);
    row2.addElement(item2);
    t.addElement(row1);
    t.addElement(row2);

    Element b = ECSFactory.makeButton(WebGoatI18N.get("Submit"));
    ElementContainer ec = new ElementContainer();
    ec.addElement(t);
    ec.addElement(new P().addElement(b));

    return (ec);
  }
Exemplo n.º 4
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @param user Description of the Parameter
   * @param method Description of the Parameter
   * @return Description of the Return Value
   * @exception Exception Description of the Exception
   */
  protected Element makeUser(WebSession s, String user, String method) throws Exception {
    ElementContainer ec = new ElementContainer();
    ec.addElement(new P().addElement("Welcome, " + user));
    ec.addElement(new P().addElement("You have been authenticated with " + method));
    ec.addElement(new P().addElement(ECSFactory.makeLink("Logout", LOGOUT, true)));
    ec.addElement(new P().addElement(ECSFactory.makeLink("Refresh", "", "")));

    return (ec);
  }
 private void displayAttemptedFile(ElementContainer ec, File attemptedFile) {
   try {
     // Show them the attempted file.  if it is a bad file, they will see the exception message
     // Strip out some of the extra html from the "help" file
     ec.addElement(new BR());
     ec.addElement(new BR());
     ec.addElement(new HR().setWidth("100%"));
     if (attemptedFile.isFile()) {
       ec.addElement(getLabelManager().get("ViewingFile") + attemptedFile.getCanonicalPath());
     } else {
       ec.addElement(getLabelManager().get("ViewingFile") + attemptedFile.getName());
     }
     ec.addElement(new HR().setWidth("100%"));
     if (attemptedFile.length() > 80000) {
       throw new Exception(getLabelManager().get("FileTooLarge"));
     }
     String fileData = getFileText(new BufferedReader(new FileReader(attemptedFile)), false);
     if (fileData.indexOf(0x00) != -1) {
       throw new Exception(getLabelManager().get("FileBinary"));
     }
     ec.addElement(
         new StringElement(
             fileData
                 .replaceAll(System.getProperty("line.separator"), "<br>")
                 .replaceAll("(?s)<!DOCTYPE.*/head>", "")
                 .replaceAll("<br><br>", "<br>")
                 .replaceAll("<br>\\s<br>", "<br>")
                 .replaceAll("<\\?", "&lt;")
                 .replaceAll("<(r|u|t)", "&lt;$1")));
   } catch (Exception e) {
     ec.addElement(new BR());
     ec.addElement(getLabelManager().get("TheFollowingError"));
     ec.addElement(e.getMessage());
   }
 }
  public Element getCredits() {
    A partnet = new A("http://www.partnet.com");
    partnet.setPrettyPrint(false);
    partnet.addElement(new StringElement("PART"));
    partnet.addElement(new B().addElement(new StringElement("NET")).setPrettyPrint(false));
    partnet.setStyle("background-color:midnightblue;color:white");

    ElementContainer credits = new ElementContainer();
    credits.addElement(new StringElement("Contributed by "));
    credits.addElement(partnet);
    return credits;
  }
  protected Element makeInputLine(WebSession s) {
    ElementContainer ec = new ElementContainer();

    ec.addElement(new P().addElement("Please change your password: "******"Go!");
    ec.addElement(b);

    return ec;
  }
Exemplo n.º 8
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element makeLogin(WebSession s) {
    ElementContainer ec = new ElementContainer();

    ec.addElement(new H1().addElement("Sign In "));
    Table t =
        new Table()
            .setCellSpacing(0)
            .setCellPadding(2)
            .setBorder(0)
            .setWidth("90%")
            .setAlign("center");

    if (s.isColor()) {
      t.setBorder(1);
    }

    TR tr = new TR();
    tr.addElement(
        new TH()
            .addElement(
                "Please sign in to your account.  See the OWASP admin if you do not have an account.")
            .setColSpan(2)
            .setAlign("left"));
    t.addElement(tr);

    tr = new TR();
    tr.addElement(new TD().addElement("*Required Fields").setWidth("30%"));
    t.addElement(tr);

    tr = new TR();
    tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
    t.addElement(tr);

    TR row1 = new TR();
    TR row2 = new TR();
    row1.addElement(new TD(new B(new StringElement("*User Name: "))));
    row2.addElement(new TD(new B(new StringElement("*Password: "******"");
    Input input2 = new Input(Input.PASSWORD, PASSWORD, "");
    row1.addElement(new TD(input1));
    row2.addElement(new TD(input2));
    t.addElement(row1);
    t.addElement(row2);

    Element b = ECSFactory.makeButton("Login");
    t.addElement(new TR(new TD(b)));
    ec.addElement(t);

    return (ec);
  }
 /**
  * Displays the video refered by the specified URL into the specified XHTML container.
  *
  * @param attachmentId the identifier of the attached file containing the video to display.
  * @param template the template of the field to which is mapped the video.
  * @param xhtmlcontainer the XMLHTML container into which the video is displayed.
  */
 private void displayVideo(
     final String attachmentId,
     final FieldTemplate template,
     final ElementContainer xhtmlcontainer,
     final PagesContext pagesContext) {
   String videoURL = computeVideoURL(attachmentId, pagesContext);
   if (!videoURL.isEmpty()) {
     Map<String, String> parameters = template.getParameters(pagesContext.getLanguage());
     Element videoLink = createVideoLink(videoURL, parameters);
     xhtmlcontainer.addElement(videoLink);
   }
   Element player =
       createVideoPlayer(videoURL, template.getParameters(pagesContext.getLanguage()));
   xhtmlcontainer.addElement(player);
 }
Exemplo n.º 10
0
  /**
   * Sets up the widget with all required information. It initializes the JQuery comment plugin with
   * and it parameterizes from Silverpeas settings and from the resource for which the comments
   * should be rendered.
   *
   * @return a container of rendering elements.
   * @throws JspException if an error occurs while initializing the JQuery comment plugin.
   */
  public ElementContainer initWidget() throws JspException {
    String context = URLManager.getApplicationURL();
    ElementContainer xhtmlcontainer = new ElementContainer();
    div comments = new div();
    comments.setID(COMMENT_WIDGET_DIV_ID);
    comments.setClass(COMMENT_WIDGET_DIV_CLASS);
    script checkForm =
        new script().setType("text/javascript").setSrc(context + "/util/javaScript/checkForm.js");
    script initCommentPlugin =
        new script().setType("text/javascript").addElement(setUpJQueryCommentPlugin());

    xhtmlcontainer.addElement(comments).addElement(checkForm);
    JavascriptPluginInclusion.includeUserZoom(xhtmlcontainer);
    JavascriptPluginInclusion.includeComment(xhtmlcontainer);
    xhtmlcontainer.addElement(initCommentPlugin);
    return xhtmlcontainer;
  }
  @Override
  public void display(
      PrintWriter out, Field field, FieldTemplate template, PagesContext pagesContext)
      throws FormException {
    checkFieldType(template.getTypeName(), "VideoFieldDisplayer.display");
    String attachmentId = field.getValue();
    if (!StringUtil.isDefined(attachmentId)) {
      attachmentId = "";
    }
    if (!template.isHidden()) {
      ElementContainer xhtmlcontainer = new ElementContainer();
      if (template.isReadOnly()) {
        displayVideo(attachmentId, template, xhtmlcontainer, pagesContext);
      } else if (!template.isDisabled()) {
        displayVideoFormInput(attachmentId, template, xhtmlcontainer, pagesContext);
      }

      out.println(xhtmlcontainer.toString());
    }
  }
Exemplo n.º 12
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  public Element makeList(WebSession s) {
    Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);

    try {
      Connection connection = DatabaseUtilities.getConnection(s);

      // edit by Chuck Willis - Added logic to associate similar usernames
      // The idea is that users chuck-1, chuck-2, etc will see each other's messages
      // but not anyone elses. This allows users to try out XSS to grab another user's
      // cookies, but not get confused by other users scripts

      String query = "SELECT * FROM messages WHERE user_name LIKE ? and lesson_type = ?";
      PreparedStatement statement =
          connection.prepareStatement(
              query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      statement.setString(1, getNameroot(s.getUserName()) + "%");
      statement.setString(2, getClass().getName());
      ResultSet results = statement.executeQuery();

      if ((results != null) && (results.first() == true)) {
        results.beforeFirst();

        for (int i = 0; results.next(); i++) {
          A a = ECSFactory.makeLink(results.getString(TITLE_COL), NUMBER, results.getInt(NUM_COL));
          TD td = new TD().addElement(a);
          TR tr = new TR().addElement(td);
          t.addElement(tr);
        }
      }
    } catch (Exception e) {
      s.setMessage(WebGoatI18N.get("ErrorGeneratingMessageList"));
    }

    ElementContainer ec = new ElementContainer();
    ec.addElement(new H1(WebGoatI18N.get("MessageList")));
    ec.addElement(t);

    return (ec);
  }
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();
    try {
      ec.addElement(makeInputLine(s));

      password = s.getParser().getRawParameter(PASSWORD, null);

      PRE pre = new PRE();
      String xml = template1;
      xml = xml + (password == null ? "[password]" : password);
      xml = xml + template2;
      pre.addElement(HtmlEncoder.encode(xml));
      ec.addElement(pre);

      if (password != null) {
        ec.addElement(checkXML(s, xml));
      }
    } catch (Exception e) {
      s.setMessage("Error generating " + this.getClass().getName());
      e.printStackTrace();
    }
    return (ec);
  }
Exemplo n.º 14
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    addMessage(s);

    ElementContainer ec = new ElementContainer();
    ec.addElement(makeInput(s));
    ec.addElement(new HR());
    ec.addElement(makeCurrent(s));
    ec.addElement(new HR());
    ec.addElement(makeList(s));

    return (ec);
  }
Exemplo n.º 15
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element makeCurrent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    try {
      int messageNum = s.getParser().getIntParameter(NUMBER, 0);

      Connection connection = DatabaseUtilities.getConnection(s);

      // edit by Chuck Willis - Added logic to associate similar usernames
      // The idea is that users chuck-1, chuck-2, etc will see each other's messages
      // but not anyone elses. This allows users to try out XSS to grab another user's
      // cookies, but not get confused by other users scripts

      String query =
          "SELECT * FROM messages WHERE user_name LIKE ? and num = ? and lesson_type = ?";
      PreparedStatement statement =
          connection.prepareStatement(
              query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      statement.setString(1, getNameroot(s.getUserName()) + "%");
      statement.setInt(2, messageNum);
      statement.setString(3, this.getClass().getName());
      ResultSet results = statement.executeQuery();

      if ((results != null) && results.first()) {
        ec.addElement(
            new H1(WebGoatI18N.get("MessageContentsFor") + ": " + results.getString(TITLE_COL)));
        Table t = new Table(0).setCellSpacing(0).setCellPadding(0).setBorder(0);
        TR row1 = new TR(new TD(new B(new StringElement(WebGoatI18N.get("Title") + ":"))));
        row1.addElement(new TD(new StringElement(results.getString(TITLE_COL))));
        t.addElement(row1);

        String messageData = results.getString(MESSAGE_COL);
        TR row2 = new TR(new TD(new B(new StringElement(WebGoatI18N.get("Message") + ":"))));
        row2.addElement(new TD(new StringElement(messageData)));
        t.addElement(row2);

        // Edited by Chuck Willis - added display of the user who posted the message, so
        // that
        // if users use a cross site request forgery or XSS to make another user post a
        // message,
        // they can see that the message is attributed to that user

        TR row3 = new TR(new TD(new StringElement(WebGoatI18N.get("PostedBy") + ":")));
        row3.addElement(new TD(new StringElement(results.getString(USER_COL))));
        t.addElement(row3);

        ec.addElement(t);

        // Some sanity checks that the script may be correct
        if (messageData.toLowerCase().indexOf("<script>") != -1
            && messageData.toLowerCase().indexOf("</script>") != -1
            && messageData.toLowerCase().indexOf("alert") != -1) {
          makeSuccess(s);
        }

      } else {
        if (messageNum != 0) {
          ec.addElement(new P().addElement(WebGoatI18N.get("CouldNotFindMessage") + messageNum));
        }
      }
    } catch (Exception e) {
      s.setMessage(WebGoatI18N.get("ErrorGenerating") + this.getClass().getName());
      e.printStackTrace();
    }

    return (ec);
  }
Exemplo n.º 16
0
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();
    String regex1 = "^[0-9]{3}$"; // any three digits
    Pattern pattern1 = Pattern.compile(regex1);

    try {
      checkSuccess(s);

      String param1 = s.getParser().getRawParameter("field1", "111");
      // String param2 = HtmlEncoder.encode(s.getParser().getRawParameter("field2", "4128 3214
      // 0002 1999"));
      float quantity = 1.0f;
      float total = 0.0f;
      float runningTotal = 0.0f;

      // FIXME: encode output of field2, then s.setMessage( field2 );
      ec.addElement("<script src='javascript/eval.js'> </script>");
      // <script src='javascript/sameOrigin.js' language='JavaScript'></script>
      ec.addElement(new HR().setWidth("90%"));
      ec.addElement(new Center().addElement(new H1().addElement("Shopping Cart ")));
      Table t =
          new Table()
              .setCellSpacing(0)
              .setCellPadding(2)
              .setBorder(1)
              .setWidth("90%")
              .setAlign("center");

      if (s.isColor()) {
        t.setBorder(1);
      }

      TR tr = new TR();
      tr.addElement(new TH().addElement("Shopping Cart Items -- To Buy Now").setWidth("80%"));
      tr.addElement(new TH().addElement("Price").setWidth("10%"));
      tr.addElement(new TH().addElement("Quantity").setWidth("3%"));
      tr.addElement(new TH().addElement("Total").setWidth("7%"));
      t.addElement(tr);

      tr = new TR();
      tr.addElement(
          new TD().addElement("Studio RTA - Laptop/Reading Cart with Tilting Surface - Cherry "));
      tr.addElement(new TD().addElement("69.99").setAlign("right"));
      tr.addElement(
          new TD()
              .addElement(
                  new Input(Input.TEXT, "QTY1", s.getParser().getStringParameter("QTY1", "1")))
              .setAlign("right"));
      quantity = s.getParser().getFloatParameter("QTY1", 0.0f);
      total = quantity * 69.99f;
      runningTotal += total;
      tr.addElement(new TD().addElement("$" + total));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(new TD().addElement("Dynex - Traditional Notebook Case"));
      tr.addElement(new TD().addElement("27.99").setAlign("right"));
      tr.addElement(
          new TD()
              .addElement(
                  new Input(Input.TEXT, "QTY2", s.getParser().getStringParameter("QTY2", "1")))
              .setAlign("right"));
      quantity = s.getParser().getFloatParameter("QTY2", 0.0f);
      total = quantity * 27.99f;
      runningTotal += total;
      tr.addElement(new TD().addElement("$" + total));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(
          new TD().addElement("Hewlett-Packard - Pavilion Notebook with Intel® Centrino™"));
      tr.addElement(new TD().addElement("1599.99").setAlign("right"));
      tr.addElement(
          new TD()
              .addElement(
                  new Input(Input.TEXT, "QTY3", s.getParser().getStringParameter("QTY3", "1")))
              .setAlign("right"));
      quantity = s.getParser().getFloatParameter("QTY3", 0.0f);
      total = quantity * 1599.99f;
      runningTotal += total;
      tr.addElement(new TD().addElement("$" + total));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(new TD().addElement("3 - Year Performance Service Plan $1000 and Over "));
      tr.addElement(new TD().addElement("299.99").setAlign("right"));

      tr.addElement(
          new TD()
              .addElement(
                  new Input(Input.TEXT, "QTY4", s.getParser().getStringParameter("QTY4", "1")))
              .setAlign("right"));
      quantity = s.getParser().getFloatParameter("QTY4", 0.0f);
      total = quantity * 299.99f;
      runningTotal += total;
      tr.addElement(new TD().addElement("$" + total));
      t.addElement(tr);

      ec.addElement(t);

      t =
          new Table()
              .setCellSpacing(0)
              .setCellPadding(2)
              .setBorder(0)
              .setWidth("90%")
              .setAlign("center");

      if (s.isColor()) {
        t.setBorder(1);
      }

      ec.addElement(new BR());

      tr = new TR();
      tr.addElement(new TD().addElement("The total charged to your credit card:"));
      tr.addElement(new TD().addElement("$" + runningTotal));

      Input b = new Input();
      b.setType(Input.BUTTON);
      b.setValue("Update Cart");
      b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');");

      tr.addElement(new TD().addElement(b));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(new TD().addElement("&nbsp;").setColSpan(2));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(new TD().addElement("Enter your credit card number:"));
      tr.addElement(
          new TD()
              .addElement(
                  "<input id='field2' name='field2' type='TEXT' value='4128 3214 0002 1999'>"));
      t.addElement(tr);
      tr = new TR();
      tr.addElement(new TD().addElement("Enter your three digit access code:"));
      tr.addElement(
          new TD().addElement("<input id='field1' name='field1' type='TEXT' value='123'>"));
      // tr.addElement(new TD().addElement(new Input(Input.TEXT, "field1",param1)));
      t.addElement(tr);

      b = new Input();
      b.setType(Input.BUTTON);
      b.setValue("Purchase");
      b.addAttribute("onclick", "purchase('lessons/Ajax/eval.jsp');");

      tr = new TR();
      tr.addElement(new TD().addElement(b).setColSpan(2).setAlign("right"));
      t.addElement(tr);

      ec.addElement(t);
      ec.addElement(new BR());
      ec.addElement(new HR().setWidth("90%"));

    } catch (Exception e) {
      s.setMessage("Error generating " + this.getClass().getName());
      e.printStackTrace();
    }
    return (ec);
  }
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    try {
      Table t = new Table().setCellSpacing(0).setCellPadding(2).setWidth("90%").setAlign("center");

      if (s.isColor()) {
        t.setBorder(1);
      }
      List<File> htmlFiles = findHtmlFiles(LessonUtil.getLessonDirectory(s, this).getParentFile());
      List<String> htmlFilenames =
          Lists.newArrayList(
              Iterables.transform(
                  htmlFiles,
                  new Function<File, String>() {
                    @Override
                    public String apply(File input) {
                      return input.getName();
                    }
                  }));
      String[] list = htmlFilenames.toArray(new String[htmlFilenames.size()]);
      String listing =
          " <p><B>"
              + getLabelManager().get("CurrentDirectory")
              + "</B> "
              + Encoding.urlDecode(htmlFiles.get(0).getParent())
              + "<br><br>"
              + getLabelManager().get("ChooseFileToView")
              + "</p>";

      TR tr = new TR();
      tr.addElement(new TD().setColSpan(2).addElement(new StringElement(listing)));
      t.addElement(tr);

      tr = new TR();
      tr.addElement(
          new TD().setWidth("35%").addElement(ECSFactory.makePulldown(FILE, list, "", 15)));
      tr.addElement(new TD().addElement(ECSFactory.makeButton(getLabelManager().get("ViewFile"))));
      t.addElement(tr);

      ec.addElement(t);

      // FIXME: would be cool to allow encodings here -- hex, percent,
      // url, etc...
      final String file = s.getParser().getRawParameter(FILE, "");

      if (!file.equals("")) // first time in or missing parameter - just kick out
      {
        // defuse file searching
        boolean illegalCommand = true;
        // allow them to look at any file in the webgoat hierachy.
        // Don't allow them to look about the webgoat root,
        // except to see the LICENSE file
        if (upDirCount(file) == 3 && !file.endsWith("LICENSE")) {
          s.setMessage(getLabelManager().get("AccessDenied"));
          s.setMessage(getLabelManager().get("ItAppears1"));
        } else {
          if (upDirCount(file) > 5) {
            s.setMessage(getLabelManager().get("AccessDenied"));
            s.setMessage(getLabelManager().get("ItAppears2"));
          } else {
            illegalCommand = false;
          }
        }

        // provide a little guidance to help them along.  If the allowed file comes back as
        // null we have the potential for a real attack vector
        File allowedFile = guideTheAtack(s, file, htmlFiles);

        if (!illegalCommand) {
          File attemptedFile =
              new File(LessonUtil.getLessonDirectory(s, this) + "/lessonPlans/en/" + file);
          if (allowedFile == null) {
            // We have a potential attack
            if (file != null && attemptedFile.isFile() && attemptedFile.exists()) {
              // They have accessed something meaningful
              s.setMessage(
                  getLabelManager().get("CongratsAccessToFileAllowed")
                      + " ==> "
                      + Encoding.urlDecode(attemptedFile.getCanonicalPath()));
              makeSuccess(s);
            } else if (file != null && file.length() != 0) {
              s.setMessage(
                  getLabelManager().get("AccessToFileDenied1")
                      + Encoding.urlDecode(file)
                      + getLabelManager().get("AccessToFileDenied2"));
            } else {
              // do nothing, probably entry screen
            }
          } else {
            attemptedFile = allowedFile;
          }

          displayAttemptedFile(ec, attemptedFile);
        }
      }

    } catch (Exception e) {
      s.setMessage(getLabelManager().get("ErrorGenerating") + this.getClass().getName());
      e.printStackTrace();
    }
    return (ec);
  }
  /**
   * if TRANSFER_FUND_PARAMETER is a parameter, them doTransfer is invoked. doTranser presents the
   * web content to confirm and then execute a simulated transfer of funds. An initial request
   * should have a dollar amount specified. The amount will be stored and a confirmation form is
   * presented. The confirmation can be canceled or confirmed. Confirming the transfer will mark
   * this lesson as completed.
   *
   * @param s
   * @return Element will appropriate web content for a transfer of funds.
   */
  protected Element doTransfer(WebSession s) {
    String transferFunds =
        HtmlEncoder.encode(s.getParser().getRawParameter(TRANSFER_FUNDS_PARAMETER, ""));
    ElementContainer ec = new ElementContainer();

    if (transferFunds.length() != 0) {

      HttpSession httpSession = s.getRequest().getSession();
      Integer transferAmount = (Integer) httpSession.getAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE);

      if (transferFunds.equalsIgnoreCase(TRANSFER_FUNDS_PAGE)) {

        // present transfer form
        ec.addElement(new H1("Electronic Transfer:"));
        String action = getLink();
        Form form = new Form(action, Form.POST);
        form.addElement(new Input(Input.text, TRANSFER_FUNDS_PARAMETER, "0"));
        // if this token is present we won't mark the lesson as completed
        form.addElement(new Input(Input.submit));
        ec.addElement(form);

      } else if (transferFunds.equalsIgnoreCase(CONFIRM_TRANFER) && transferAmount != null) {

        // transfer is confirmed
        ec.addElement(new H1("Electronic Transfer Complete"));
        ec.addElement(new StringElement("Amount Transfered: " + transferAmount));
        makeSuccess(s);

      } else if (transferFunds.equalsIgnoreCase(CANCEL_TRANSFER)) {

        // clear any pending fund transfer
        s.getRequest().removeAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE);

      } else if (transferFunds.length() > 0) {

        // save the transfer amount in the session
        transferAmount = new Integer(transferFunds);
        httpSession.setAttribute(TRANSFER_FUND_AMOUNT_ATTRIBUTE, transferAmount);

        // prompt for confirmation

        ec.addElement(new H1("Electronic Transfer Confirmation:"));
        ec.addElement(new StringElement("Amount to transfer: " + transferAmount));
        ec.addElement(new BR());
        String action = getLink();
        Form form = new Form(action, Form.POST);
        form.addElement(new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CONFIRM_TRANFER));
        form.addElement(new Input(Input.submit, TRANSFER_FUNDS_PARAMETER, CANCEL_TRANSFER));
        ec.addElement(form);
      }
    }
    // white space
    ec.addElement(new BR());
    ec.addElement(new BR());
    ec.addElement(new BR());
    return ec;
  }
  /**
   * Prints the HTML value of the field. The displayed value must be updatable by the end user. The
   * value format may be adapted to a local language. The fieldName must be used to name the html
   * form input. Never throws an Exception but log a silvertrace and writes an empty string when :
   *
   * <UL>
   *   <LI>the field type is not a managed type.
   * </UL>
   *
   * @param out
   * @param field
   * @param template
   * @param pageContext
   * @throws FormException
   */
  @Override
  public void display(
      PrintWriter out, TextField field, FieldTemplate template, PagesContext pageContext)
      throws FormException {
    String value = "";
    String html = "";

    String fieldName = template.getFieldName();
    SilverTrace.info(
        "form", "TimeFieldDisplayer.display", "root.MSG_GEN_PARAM_VALUE", "fieldName=" + fieldName);
    Map<String, String> parameters = template.getParameters(pageContext.getLanguage());
    if (field == null) {
      return;
    }
    if (!field.getTypeName().equals(TextField.TYPE)) {
      SilverTrace.info(
          "form", "TimeFieldDisplayer.display", "form.INFO_NOT_CORRECT_TYPE", TextField.TYPE);
    }

    String defaultParam = (parameters.containsKey("default") ? parameters.get("default") : "");
    String defaultValue = "";
    if ("now".equalsIgnoreCase(defaultParam) && !pageContext.isIgnoreDefaultValues()) {
      defaultValue = DateUtil.formatTime(new Date());
    }
    value = (!field.isNull() ? field.getValue(pageContext.getLanguage()) : defaultValue);
    if (pageContext.isBlankFieldsUse()) {
      value = "";
    }

    if (template.isReadOnly() && !template.isHidden()) {
      html = value;
    } else {
      input inputField = new input();
      inputField.setName(template.getFieldName());
      inputField.setID(template.getFieldName());
      inputField.setValue(EncodeHelper.javaStringToHtmlString(value));
      inputField.setType(template.isHidden() ? input.hidden : input.text);
      inputField.setMaxlength("5");
      inputField.setSize("10");
      if (template.isDisabled()) {
        inputField.setDisabled(true);
      } else if (template.isReadOnly()) {
        inputField.setReadOnly(true);
      }

      img image = null;
      if (template.isMandatory()
          && !template.isDisabled()
          && !template.isReadOnly()
          && !template.isHidden()
          && pageContext.useMandatory()) {
        image = new img();
        image.setSrc(Util.getIcon("mandatoryField"));
        image.setWidth(5);
        image.setHeight(5);
        image.setBorder(0);
      }

      // print field
      if (image != null) {
        ElementContainer container = new ElementContainer();
        container.addElement(inputField);
        container.addElement("&nbsp;");
        container.addElement(image);
        out.println(container.toString());
      } else {
        out.println(inputField.toString());
      }
    }
    out.println(html);
  }
  /**
   * Displays the form part corresponding to the video input. The form input is a way to change or
   * to remove the video file if this one exists.
   *
   * @param attachmentId the identifier of the attached file containing the video to display.
   * @param template the template of the field to which is mapped the video.
   * @param pagesContext the context of the displaying page.
   */
  private void displayVideoFormInput(
      final String attachmentId,
      final FieldTemplate template,
      final ElementContainer xhtmlContainer,
      final PagesContext pagesContext) {
    String fieldName = template.getFieldName();
    String language = pagesContext.getLanguage();
    String deletionIcon = Util.getIcon("delete");
    String deletionLab = Util.getString("removeFile", language);
    String videoURL = computeVideoURL(attachmentId, pagesContext);
    Operation defaultOperation = Operation.ADD;

    if (!videoURL.isEmpty()) {
      defaultOperation = Operation.UPDATE;
      Map<String, String> parameters = template.getParameters(pagesContext.getLanguage());
      parameters.remove(PARAMETER_WIDTH);
      parameters.remove(PARAMETER_HEIGHT);
      // a link to the video
      Element videoLink = createVideoLink(videoURL, parameters);

      // a link to the deletion operation
      img deletionImage = new img();
      deletionImage
          .setAlt(deletionLab)
          .setSrc(deletionIcon)
          .setWidth(15)
          .setHeight(15)
          .setAlt(deletionLab)
          .setTitle(deletionLab);
      a removeLink = new a();
      removeLink
          .setHref("#")
          .addElement(deletionImage)
          .setOnClick(
              "javascript: document.getElementById('"
                  + fieldName
                  + "Video').style.display='none'; document."
                  + pagesContext.getFormName()
                  + "."
                  + fieldName
                  + OPERATION_KEY
                  + ".value='"
                  + Operation.DELETION.name()
                  + "';");
      div videoDiv = new div();
      videoDiv.setID(fieldName + "Video");
      videoDiv.setClass("video");
      videoDiv.addElement(videoLink);
      videoDiv.addElement("&nbsp;");
      videoDiv.addElement(removeLink);

      xhtmlContainer.addElement(videoDiv);
    }

    // the input from which a video file can be selected
    input fileInput = new input();
    fileInput.setID(fieldName);
    fileInput.setType("file");
    fileInput.setSize(50);
    fileInput.setName(fieldName);
    input attachmentInput = new input();
    attachmentInput
        .setType("hidden")
        .setName(fieldName + Field.FILE_PARAM_NAME_SUFFIX)
        .setValue(attachmentId)
        .setID(fieldName + Field.FILE_PARAM_NAME_SUFFIX);
    input operationInput = new input();
    operationInput
        .setType("hidden")
        .setName(fieldName + OPERATION_KEY)
        .setValue(defaultOperation.name())
        .setID(fieldName + OPERATION_KEY);
    div selectionDiv = new div();
    selectionDiv.setID(fieldName + "Selection");
    selectionDiv.addElement(fileInput);
    selectionDiv.addElement(attachmentInput);
    selectionDiv.addElement(operationInput);
    if (template.isMandatory() && pagesContext.useMandatory()) {
      selectionDiv.addElement(Util.getMandatorySnippet());
    }
    xhtmlContainer.addElement(selectionDiv);

    Element player =
        createVideoPlayer(videoURL, template.getParameters(pagesContext.getLanguage()));
    xhtmlContainer.addElement(player);
  }
  /**
   * Description of the Method
   *
   * @param s Description of the Parameter
   * @return Description of the Return Value
   */
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    try {
      boolean failed = false;

      // select element
      ec.addElement(
          new Div().addElement(new StringElement("Select field with two possible values:")));

      String[] allowedSelect = {"foo", "bar"};

      ec.addElement(new org.apache.ecs.html.Select("select", allowedSelect));

      // radio button element
      ec.addElement(new P());
      ec.addElement(
          new Div().addElement(new StringElement("Radio button with two possible values:")));

      Input radiofoo = new Input("radio", "radio", "foo");
      radiofoo.setChecked(true);
      ec.addElement(radiofoo);
      ec.addElement(new StringElement("foo"));
      ec.addElement(new BR());
      ec.addElement(new Input("radio", "radio", "bar"));
      ec.addElement(new StringElement("bar"));

      // checkbox
      ec.addElement(new P());
      ec.addElement(new Div().addElement(new StringElement("Checkbox:")));
      Input checkbox = new Input("checkbox", "checkbox");
      checkbox.setChecked(true);
      ec.addElement(checkbox);
      ec.addElement(new StringElement("checkbox"));

      // create shortinput
      ec.addElement(new P());
      ec.addElement(
          new Div().addElement(new StringElement("Input field restricted to 5 characters:")));
      Input shortinput = new Input(Input.TEXT, "shortinput", "12345");
      shortinput.setMaxlength(5);
      ec.addElement(shortinput);

      ec.addElement(new P());
      ec.addElement(new Div().addElement(new StringElement("Disabled input field:")));
      String defaultdisabledinputtext = "disabled";
      Input disabledinput = new Input(Input.TEXT, "disabledinput", defaultdisabledinputtext);
      disabledinput.setDisabled(true);
      ec.addElement(disabledinput);
      ec.addElement(new BR());

      // Submit Button
      ec.addElement(new P());
      ec.addElement(new Div().addElement(new StringElement("Submit button:")));
      String submittext = "Submit";
      Element b = ECSFactory.makeButton(submittext);
      ec.addElement(b);

      //  Now check inputs that were submitted (if any)

      // check select field

      String submittedselect = s.getParser().getRawParameter("select");
      if (submittedselect.equals("foo")) failed = true;
      if (submittedselect.equals("bar")) failed = true;

      // check radio buttons
      String submittedradio = s.getParser().getRawParameter("radio");
      if (submittedselect.equals("foo")) failed = true;
      if (submittedselect.equals("bar")) failed = true;

      // check checkbox (note - if the box is not checked, this will throw an exception, but that
      // is okay)
      if (s.getParser().getRawParameter("checkbox").equals("on")) failed = true;

      // check shortinput
      if (s.getParser().getRawParameter("shortinput").length() < 6) failed = true;

      // check disabledinput (note - if the field was not re-enabled, this will throw an exception,
      // but that
      // is okay)
      if (s.getParser().getRawParameter("disabledinput").equals(defaultdisabledinputtext))
        failed = true;

      // check submitbutton
      if (s.getParser().getRawParameter("SUBMIT").equals(submittext)) failed = true;

      // if we didn't fail, we succeeded!
      if (failed != true) {
        makeSuccess(s);
      }

    } catch (ParameterNotFoundException e) {
      // s.setMessage("Error, required parameter not found");
      // e.printStackTrace();
    }

    return (ec);
  }
Exemplo n.º 22
0
  protected Element createContent(WebSession s) {
    ElementContainer ec = new ElementContainer();

    Table t1 = new Table().setCellSpacing(0).setCellPadding(2);

    if (s.isColor()) {
      t1.setBorder(1);
    }
    TR tr = new TR();
    tr.addElement(new TD("Enter your account number: "));
    tr.addElement(new TD(new Input(Input.TEXT, "id", "101")));
    t1.addElement(tr);

    tr = new TR();
    tr.addElement(new TD("Select the fields to return: "));
    tr.addElement(
        new TD(
            new Select("field")
                .setMultiple(true)
                .addElement(new Option(firstName).addElement("First Name"))
                .addElement(new Option(lastName).addElement("Last Name"))
                .addElement(new Option(loginCount).addElement("Login Count"))));
    t1.addElement(tr);

    tr = new TR();
    Element b = ECSFactory.makeButton("Submit");
    tr.addElement(new TD(b).setAlign("CENTER").setColSpan(2));
    t1.addElement(tr);

    ec.addElement(t1);

    try {
      String[] fields = s.getParser().getParameterValues("field");
      int id = s.getParser().getIntParameter("id");

      Table t = new Table().setCellSpacing(0).setCellPadding(2).setBorder(1);

      if (s.isColor()) {
        t.setBorder(1);
      }
      TR header = new TR();
      TR results = new TR();
      int port = s.getRequest().getServerPort();
      for (int i = 0; i < fields.length; i++) {
        header.addElement(new TD().addElement(fields[i]));
        results.addElement(
            new TD()
                .addElement(
                    (String)
                        accessWGService(
                            s, "WSDLScanning", port, fields[i], "acct_num", new Integer(id))));
      }
      if (fields.length == 0) {
        s.setMessage("Please select a value to return.");
      }
      t.addElement(header);
      t.addElement(results);
      ec.addElement(new P().addElement(t));
    } catch (Exception e) {

    }
    try {
      A a = new A("services/WSDLScanning?WSDL", "WebGoat WSDL File");
      ec.addElement(
          new P()
              .addElement(
                  "View the web services definition language (WSDL) to see the complete API:"));
      ec.addElement(new BR());
      ec.addElement(a);
      // getLessonTracker( s ).setCompleted( completed );

      if (completed && !getLessonTracker(s).getCompleted() && !beenRestartedYet) {
        makeSuccess(s);
        beenRestartedYet = true;
      } else if (completed && !getLessonTracker(s).getCompleted() && beenRestartedYet) {
        completed = false;
        beenRestartedYet = false;
      }

      // accessWGService("WSDLScanning", "getCreditCard", "acct_num", new Integer(101));
    } catch (Exception e) {
      s.setMessage("Error generating " + this.getClass().getName());
      e.printStackTrace();
    }
    return (ec);
  }
 @Override
 public void doTag() throws JspException, IOException {
   ElementContainer xhtml = new ElementContainer();
   try {
     SupportedJavaScriptPlugins jsPlugin = SupportedJavaScriptPlugins.valueOf(getName());
     switch (jsPlugin) {
       case embedPlayer:
         includeEmbedPlayer(xhtml);
         break;
       case audioPlayer:
         includeAudioPlayer(xhtml);
         break;
       case videoPlayer:
         includeVideoPlayer(xhtml);
         break;
       case qtip:
         includeQTip(xhtml);
         break;
       case datepicker:
         includeDatePicker(xhtml, getLanguage());
         break;
       case pagination:
         includePagination(xhtml);
         break;
       case breadcrumb:
         includeBreadCrumb(xhtml);
         break;
       case userZoom:
         includeUserZoom(xhtml);
         break;
       case invitme:
         includeInvitMe(xhtml);
         break;
       case messageme:
         includeMessageMe(xhtml);
         break;
       case wysiwyg:
         includeWysiwygEditor(xhtml);
         break;
       case responsibles:
         includeResponsibles(xhtml, getLanguage());
         break;
       case popup:
         includePopup(xhtml);
         break;
       case calendar:
         includeCalendar(xhtml);
         break;
       case iframeajaxtransport:
         includeIFrameAjaxTransport(xhtml);
         break;
       case preview:
         includePreview(xhtml);
         break;
       case notifier:
         includeNotifier(xhtml);
         break;
       case password:
         includePassword(xhtml);
         break;
       case gauge:
         includeGauge(xhtml);
         break;
       case jquery:
         includeJQuery(xhtml);
         break;
       case tags:
         includeTags(xhtml);
         break;
       case pdc:
         includePdc(xhtml);
         break;
       case tkn:
         includeSecurityTokenizing(xhtml);
         break;
       case rating:
         includeRating(xhtml);
         break;
       case toggle:
         includeToggle(xhtml);
         break;
       case lightslideshow:
         includeLightweightSlideshow(xhtml);
         break;
       case lang:
         includeLang(xhtml);
         break;
       case ticker:
         includeTicker(xhtml);
     }
   } catch (IllegalArgumentException ex) {
     // ignore
   }
   xhtml.output(getJspContext().getOut());
 }