Beispiel #1
0
 static ECMAEscapedSavedQuery getFor(SavedQuery savedQuery) throws LensException {
   return new ECMAEscapedSavedQuery(
       savedQuery.getId(),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getName()),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getDescription()),
       StringEscapeUtils.escapeEcmaScript(savedQuery.getQuery()),
       StringEscapeUtils.escapeEcmaScript(serializeParameters(savedQuery)));
 }
 /**
  * Setting an ID lets the browser keep track of the last event fired so that if, the connection to
  * the server is dropped, a special HTTP header (Last-Event-ID) is set with the new request. This
  * lets the browser determine which event is appropriate to fire.
  *
  * @param eventId Unique event id.
  * @param data data associated with event
  */
 public void sendDataById(String eventId, String data) {
   out.write(
       "id: "
           + eventId
           + "\r\n"
           + "data: "
           + StringEscapeUtils.escapeEcmaScript(data)
           + "\r\n\r\n");
 }
 /**
  * A single event source can generate different types events by including an event name. On the
  * client, an event listener can be setup to listen to that particular event.
  *
  * @param eventName Unique name of the event.
  * @param data data associated with event
  * @deprecated Replaced by send
  */
 public void sendDataByName(String eventName, String data) {
   out.write(
       "event: "
           + eventName
           + "\r\n"
           + "data: "
           + StringEscapeUtils.escapeEcmaScript(data)
           + "\r\n\r\n");
 }
  public String escapeScript(String text) {

    String value = text;
    if (text == null) {
      return text;
    } else {
      value = StringEscapeUtils.escapeEcmaScript(value);
    }
    return value;
  }
 @PostConstruct
 public void refreshCache() {
   try {
     events = aapService.getAllFutureEvents();
     for (EventDto oneEventDto : events) {
       oneEventDto.setAddress(
           StringEscapeUtils.escapeEcmaScript(oneEventDto.getAddress().replaceAll("\n", "<br>")));
     }
     events = Collections.unmodifiableList(events);
   } catch (Exception e) {
     logger.error("unable to refresh Event Cache", e);
   }
 }
public class BuildsJavaScriptToWriteFailureHtmlTest {

  private static final String LEFT =
      "document.write(\"" + StringEscapeUtils.escapeEcmaScript("<div class=\"suite spec failed\">");
  private static final String RIGHT = StringEscapeUtils.escapeEcmaScript("</div>") + "\")";

  private final BuildsJavaScriptToWriteFailureHtml subject =
      new BuildsJavaScriptToWriteFailureHtml();

  @Test
  public void whenNothingIsPassedYouGetAnEmptyDiv() {
    assertThat(subject.build(""), is(LEFT + RIGHT));
  }

  @Test
  public void printsASimpleMessage() {
    assertThat(subject.build("pants"), is(LEFT + "pants" + RIGHT));
  }

  @Test
  public void esacpesMessageString() {
    assertThat(subject.build("<a>pant's</a>"), is(LEFT + "<a>pant\\'s<\\/a>" + RIGHT));
  }
}
  public void carregaComboQuest(
      DocumentHTML document, HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    final QuestionarioService questionarioService =
        (QuestionarioService)
            ServiceLocator.getInstance().getService(QuestionarioService.class, null);

    final HTMLSelect comboQuestionario = document.getSelectById("idQuestionario");
    @SuppressWarnings("unchecked")
    final ArrayList<QuestionarioDTO> tipos = (ArrayList) questionarioService.list();
    comboQuestionario.removeAllOptions();
    if (tipos != null && tipos.size() > 0) {
      comboQuestionario.addOption(
          "", "-- " + UtilI18N.internacionaliza(request, "alcada.limite.todos") + " --");
      for (final QuestionarioDTO tipo : tipos) {
        comboQuestionario.addOption(
            tipo.getIdQuestionario().toString(),
            StringEscapeUtils.escapeEcmaScript(tipo.getNomeQuestionario()));
      }
    }
  }
Beispiel #8
0
  /**
   * Evaluate the given javascript in the current window. Upon completion, if the framework has loaded and is in a
   * test mode, then assert that there are no uncaught javascript errors.
   * <p>
   * As an implementation detail, we accomplish this by wrapping the given javascript so that we can perform the error
   * check on each evaluation without doing a round-trip to the browser (which might be long in cases of remote test
   * runs).
   *
   * @return the result of calling {@link JavascriptExecutor#executeScript(String, Object...) with the given
   *         javascript and args.
   */
  public Object getEval(final String javascript, Object... args) {
    /**
     * Wrapping the javascript on the native Android browser is broken. By not using the wrapper we
     * won't catch any javascript errors here, but on passing cases this should behave the same
     * functionally. See W-1481593.
     */
    if (driver instanceof RemoteWebDriver
        && "android".equals(((RemoteWebDriver) driver).getCapabilities().getBrowserName())) {
      return getRawEval(javascript, args);
    }

    /**
     * Wrap the given javascript to evaluate and then check for any collected errors. Then, return
     * the result and errors back to the WebDriver. We must return as an array because {@link
     * JavascriptExecutor#executeScript(String, Object...)} cannot handle Objects as return values."
     */
    String escapedJavascript = StringEscapeUtils.escapeEcmaScript(javascript);
    String wrapper =
        "var ret,scriptExecException;"
            + String.format("var func = new Function('arguments', \"%s\");\n", escapedJavascript)
            + "try\n{"
            + " ret = func.call(this, arguments);\n"
            + "}\n"
            + "catch(e){\n"
            + " scriptExecException = e.message || e.toString();\n"
            + "}\n"
            + //
            "var jstesterrors = (window.$A && window.$A.test) ? window.$A.test.getErrors() : '';\n"
            + "return [ret, jstesterrors, scriptExecException];";

    try {
      @SuppressWarnings("unchecked")
      List<Object> wrapResult = (List<Object>) getRawEval(wrapper, args);
      Assert.assertEquals(
          "Wrapped javsascript execution expects an array of exactly 3 elements",
          3,
          wrapResult.size());
      Object exception = wrapResult.get(2);
      Assert.assertNull(
          "Following JS Exception occured while evaluating provided script:\n"
              + exception
              + "\n"
              + "Arguments: ("
              + Arrays.toString(args)
              + ")\n"
              + "Script:\n"
              + javascript
              + "\n",
          exception);
      String errors = (String) wrapResult.get(1);
      assertJsTestErrors(errors);
      rerunCount = 0;
      return wrapResult.get(0);
    } catch (WebDriverException e) {
      // shouldn't come here that often as we are also wrapping the js
      // script being passed to us in try/catch above
      Assert.fail(
          "Script execution failed.\n"
              + "Exception type: "
              + e.getClass().getName()
              + "\n"
              + "Failure Message: "
              + e.getMessage()
              + "\n"
              + "Arguments: ("
              + Arrays.toString(args)
              + ")\n"
              + "Script:\n"
              + javascript
              + "\n");
      throw e;
    } catch (NullPointerException npe) {
      // Although it should never happen, ios-driver is occasionally returning null when trying to
      // execute the
      // wrapped javascript. Re-run the script a couple more times before failing.
      if (++rerunCount > 2) {
        Assert.fail(
            "Script execution failed.\n"
                + "Failure Message: "
                + npe.getMessage()
                + "\n"
                + "Arguments: ("
                + Arrays.toString(args)
                + ")\n"
                + "Script:\n"
                + javascript
                + "\n");
      }
      return getEval(javascript, args);
    }
  }
Beispiel #9
0
  public String buildUrl(
      String action,
      HttpServletRequest request,
      HttpServletResponse response,
      Map<String, Object> params,
      String urlScheme,
      boolean includeContext,
      boolean encodeResult,
      boolean forceAddSchemeHostAndPort,
      boolean escapeAmp) {

    StringBuilder link = new StringBuilder();
    boolean changedScheme = false;

    String scheme = null;
    if (isValidScheme(urlScheme)) {
      scheme = urlScheme;
    }

    // only append scheme if it is different to the current scheme *OR*
    // if we explicity want it to be appended by having forceAddSchemeHostAndPort = true
    if (forceAddSchemeHostAndPort) {
      String reqScheme = request.getScheme();
      changedScheme = true;
      link.append(scheme != null ? scheme : reqScheme);
      link.append("://");
      link.append(request.getServerName());

      if (scheme != null) {
        // If switching schemes, use the configured port for the particular scheme.
        if (!scheme.equals(reqScheme)) {
          if ((HTTP_PROTOCOL.equals(scheme) && (httpPort != DEFAULT_HTTP_PORT))
              || (HTTPS_PROTOCOL.equals(scheme) && httpsPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(HTTP_PROTOCOL.equals(scheme) ? httpPort : httpsPort);
          }
          // Else use the port from the current request.
        } else {
          int reqPort = request.getServerPort();

          if ((scheme.equals(HTTP_PROTOCOL) && (reqPort != DEFAULT_HTTP_PORT))
              || (scheme.equals(HTTPS_PROTOCOL) && reqPort != DEFAULT_HTTPS_PORT)) {
            link.append(":");
            link.append(reqPort);
          }
        }
      }
    } else if ((scheme != null) && !scheme.equals(request.getScheme())) {
      changedScheme = true;
      link.append(scheme);
      link.append("://");
      link.append(request.getServerName());

      if ((scheme.equals(HTTP_PROTOCOL) && (httpPort != DEFAULT_HTTP_PORT))
          || (HTTPS_PROTOCOL.equals(scheme) && httpsPort != DEFAULT_HTTPS_PORT)) {
        link.append(":");
        link.append(HTTP_PROTOCOL.equals(scheme) ? httpPort : httpsPort);
      }
    }

    if (action != null) {
      // Check if context path needs to be added
      // Add path to absolute links
      if (action.startsWith("/") && includeContext) {
        String contextPath = request.getContextPath();
        if (!contextPath.equals("/")) {
          link.append(contextPath);
        }
      } else if (changedScheme) {

        // (Applicable to Servlet 2.4 containers)
        // If the request was forwarded, the attribute below will be set with the original URL
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");

        // If the attribute wasn't found, default to the value in the request object
        if (uri == null) {
          uri = request.getRequestURI();
        }

        link.append(uri.substring(0, uri.lastIndexOf('/') + 1));
      }

      // Add page
      link.append(action);
    } else {
      // Go to "same page"
      String requestURI = (String) request.getAttribute("struts.request_uri");

      // (Applicable to Servlet 2.4 containers)
      // If the request was forwarded, the attribute below will be set with the original URL
      if (requestURI == null) {
        requestURI = (String) request.getAttribute("javax.servlet.forward.request_uri");
      }

      // If neither request attributes were found, default to the value in the request object
      if (requestURI == null) {
        requestURI = request.getRequestURI();
      }

      link.append(requestURI);
    }

    // if the action was not explicitly set grab the params from the request
    if (escapeAmp) {
      buildParametersString(params, link, AMP);
    } else {
      buildParametersString(params, link, "&");
    }

    String result = link.toString();

    if (StringUtils.containsIgnoreCase(result, "<script")) {
      result = StringEscapeUtils.escapeEcmaScript(result);
    }
    try {
      result = encodeResult ? response.encodeURL(result) : result;
    } catch (Exception ex) {
      LOG.debug("Could not encode the URL for some reason, use it unchanged", ex);
      result = link.toString();
    }

    return result;
  }
 public static String filter(String src) {
   String s = StringEscapeUtils.escapeEcmaScript(src);
   logger.debug("{src:{}, result:{}}", src, s);
   return s;
 }
 protected String format(String msg, final Object... params) {
   msg = msg.replaceAll("\\{\\}", "%s");
   return StringEscapeUtils.escapeEcmaScript(String.format(msg, params));
 }
  public ClienteEmailCentralServicoDTO readMessage(
      DocumentHTML document,
      HttpServletRequest request,
      HttpServletResponse response,
      String messageId)
      throws Exception {
    ClienteEmailCentralServicoDTO clienteEmailCentralServicoDto =
        new ClienteEmailCentralServicoDTO();
    clienteEmailCentralServicoDto.setResultSucess(true);

    try {
      if (CONEXAO_EMAIL_SERVIDOR.equals("")
          || CONEXAO_EMAIL_PROVIDER.equals("")
          || CONEXAO_EMAIL_CAIXA.equals("")
          || CONEXAO_EMAIL_SENHA.equals("")
          || CONEXAO_EMAIL_PASTA.equals("")) {
        clienteEmailCentralServicoDto.setResultSucess(false);
        clienteEmailCentralServicoDto.setResultMessage(
            UtilI18N.internacionaliza(
                request, "clienteEmailCentralServico.problemasRealizarleituraEmailsParametros"));
      } else {
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", CONEXAO_EMAIL_PROVIDER);

        props.setProperty("mail.imaps.auth.plain.disable", "true");
        props.setProperty("mail.imaps.ssl.trust", "*");
        // props.setProperty("mail.debug", "true");

        if (!CONEXAO_EMAIL_PORTA.equals(""))
          props.setProperty("mail." + CONEXAO_EMAIL_PROVIDER + ".port", CONEXAO_EMAIL_PORTA);

        Session session = Session.getInstance(props, null);
        Store store = session.getStore();
        store.connect(CONEXAO_EMAIL_SERVIDOR, CONEXAO_EMAIL_CAIXA, CONEXAO_EMAIL_SENHA);

        Folder inbox = store.getFolder(CONEXAO_EMAIL_PASTA);
        inbox.open(Folder.READ_WRITE);

        SearchTerm searchTerm = new MessageIDTerm(messageId);
        Message[] messages = inbox.search(searchTerm);

        if (messages != null && messages.length > 0) {
          ArrayList<ClienteEmailCentralServicoMessagesDTO> emailMessages =
              new ArrayList<ClienteEmailCentralServicoMessagesDTO>();
          for (Message message : messages) {
            ClienteEmailCentralServicoMessagesDTO clienteEmailMessagesDto =
                new ClienteEmailCentralServicoMessagesDTO();

            MimeMessage m = (MimeMessage) inbox.getMessage(message.getMessageNumber());
            clienteEmailMessagesDto.setMessageId(m.getMessageID());
            clienteEmailMessagesDto.setMessageNumber(message.getMessageNumber());

            Address[] in = message.getFrom();
            clienteEmailMessagesDto.setMessageEmail(
                (in == null ? null : ((InternetAddress) in[0]).getAddress()));

            clienteEmailMessagesDto.setMessageSubject(message.getSubject());
            clienteEmailMessagesDto.setMessageReceivedDate(message.getReceivedDate());
            clienteEmailMessagesDto.setSeen(message.isSet(Flags.Flag.SEEN));

            Object objRef = message.getContent();
            String content = "";

            if (!(objRef instanceof Multipart)) {
              content = (String) message.getContent();
            } else {
              Multipart mp = (Multipart) message.getContent();
              BodyPart bp = mp.getBodyPart(0);

              content = getContent(bp);
            }

            if (content != null) {
              // content = content.replaceAll("(\r\n|\r|\n)", "<br />");
              content = StringEscapeUtils.escapeEcmaScript(content);

              clienteEmailMessagesDto.setMessageContent(content);
            }

            emailMessages.add(clienteEmailMessagesDto);
          }

          clienteEmailCentralServicoDto.setEmailMessages(emailMessages);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
      clienteEmailCentralServicoDto.setResultSucess(false);
      clienteEmailCentralServicoDto.setResultMessage(
          UtilI18N.internacionaliza(
              request, "clienteEmailCentralServico.problemasRealizarleituraEmails"));
    }

    return clienteEmailCentralServicoDto;
  }