<commit_before>package org.openqa.selenium.server;

import org.openqa.jetty.http.HttpRequest;
import org.openqa.jetty.http.HttpResponse;
import org.openqa.jetty.util.IO;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class InjectionHelper {
  static Logger log = Logger.getLogger(InjectionHelper.class.getName());
  private static boolean failOnError = true;
  private static boolean browserSideLogEnabled = true;
  private static boolean INJECT_SCRIPT_TAGS = true;
  private static boolean tryToInjectInHead = false;
  private static String injectionHtml = "/core/scripts/injection.html";
  private static HashMap<String, HashMap<String, String>> jsStateInitializersBySessionId =
      new HashMap<String, HashMap<String, String>>();
  private static HashMap<String, String> sessionIdToUniqueId = new HashMap<String, String>();

  private static HashMap<String, String> contentTransformations = new HashMap<String, String>();
  private static List<String> userJsInjectionFiles = new LinkedList<String>();

  public static void setBrowserSideLogEnabled(boolean browserSideLogEnabled) {
    InjectionHelper.browserSideLogEnabled = browserSideLogEnabled;
  }

  public static void setInjectScriptTags(boolean injectScriptTags) {
    InjectionHelper.INJECT_SCRIPT_TAGS = injectScriptTags;
  }

  public static void setTryToInjectInHead(boolean tryToInjectInHead) {
    InjectionHelper.tryToInjectInHead = tryToInjectInHead;
  }

  public static void setInjectionHtml(String injectionHtml) {
    InjectionHelper.injectionHtml = injectionHtml;
  }

  public static void saveJsStateInitializer(String sessionId, String uniqueId, String jsVarName,
      String jsStateInitializer) {
    // when a new uniqueId is seen for a given sessionId, that means the page has
    // reloaded and the old state should be discarded
    if (sessionIdToUniqueId.containsKey(sessionId) &&
        !sessionIdToUniqueId.get(sessionId).equals(uniqueId)) {
      jsStateInitializersBySessionId.remove(sessionId);
      sessionIdToUniqueId.put(sessionId, uniqueId);
    }
    log.fine("Saving JavaScript state for session " + sessionId + "/" + uniqueId + " " + jsVarName +
        ": " + jsStateInitializer);
    if (!jsStateInitializersBySessionId.containsKey(sessionId)) {
      jsStateInitializersBySessionId.put(sessionId, new HashMap<String, String>());
    }
    HashMap<String, String> h = jsStateInitializersBySessionId.get(sessionId);
    StringBuffer sb = new StringBuffer("if (uniqueId!='");
    sb.append(uniqueId)
        .append("') {")
        .append(jsStateInitializer)
        .append("}");
    h.put(jsVarName, sb.toString());
  }

  public static String restoreJsStateInitializer(String sessionId, String uniqueId) {
    if (!jsStateInitializersBySessionId.containsKey(sessionId)) {
      return "";
    }
    HashMap<String, String> h = jsStateInitializersBySessionId.get(sessionId);
    if (h.isEmpty()) {
      return "";
    }
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : h.entrySet()) {
      final String jsVarName = entry.getKey();
      final String jsStateInitializer = entry.getValue();
      sb.append(jsStateInitializer)
          .append('\n');
      log.fine("Restoring JavaScript state for session " + sessionId + "/" + uniqueId
          + ": key=" + jsVarName + ": " + jsStateInitializer);
    }
    return sb.toString();
  }

  /**
   * re-read selenium js. Don't maintain it indefinitely for now since then we would need to restart
   * the server to see changes. Once the selenium js is firm, this should change.
   */
  public static void init() {
    String key = <KEY>";

    StringBuffer sb = new StringBuffer();
    if (!INJECT_SCRIPT_TAGS) { // DGF experiment with using script tags
      try {
        appendFileContent(sb, "/core/scripts/xmlextras.js");
        appendFileContent(sb, "/core/lib/sizzle.js");
        appendFileContent(sb, "/core/scripts/htmlutils.js");
        appendFileContent(sb, "/core/scripts/ui-element.js");
        appendFileContent(sb, "/core/scripts/selenium-browserdetect.js");
        appendFileContent(sb, "/core/scripts/selenium-browserbot.js");
        appendFileContent(sb, "/core/scripts/find_matching_child.js");
        appendFileContent(sb, "/core/scripts/selenium-api.js");
        appendFileContent(sb,
            "/core/scripts/selenium-commandhandlers.js");
        appendFileContent(sb, "/core/scripts/selenium-executionloop.js");
        appendFileContent(sb, "/core/scripts/selenium-remoterunner.js");
        appendFileContent(sb, "/core/scripts/selenium-logging.js");
        appendFileContent(sb, "/core/xpath/util.js");
        appendFileContent(sb, "/core/xpath/xmltoken.js");
        appendFileContent(sb, "/core/xpath/dom.js");
        appendFileContent(sb, "/core/xpath/xpath.js");
        appendFileContent(sb, "/core/xpath/javascript-xpath-0.1.11.js");
        appendFileContent(sb, "/core/scripts/user-extensions.js");
      } catch (Exception e) {
        if (failOnError) {
          throw new RuntimeException(e);
        }
        log.info("failOnError is false, ignoring problems: "
            + e.getMessage());
        log.log(Level.FINE, "Ignored exception", e);
      }
    }
    contentTransformations.put(key, sb.toString());
  }

  private static void writeScriptTags(OutputStream os) throws IOException {
    // DGF script tags are SLOWER than regular injection! (remember, we disable the browser cache
    // entirely)
    writeScriptTag(os, "/core/scripts/xmlextras.js");
    writeScriptTag(os, "/core/lib/cssQuery/cssQuery-p.js");
    writeScriptTag(os, "/core/scripts/htmlutils.js");
    writeScriptTag(os, "/core/scripts/ui-element.js");
    writeScriptTag(os, "/core/scripts/selenium-browserdetect.js");
    writeScriptTag(os, "/core/scripts/selenium-browserbot.js");
    writeScriptTag(os, "/core/scripts/find_matching_child.js");
    writeScriptTag(os, "/core/scripts/selenium-api.js");
    writeScriptTag(os, "/core/scripts/selenium-commandhandlers.js");
    writeScriptTag(os, "/core/scripts/selenium-executionloop.js");
    writeScriptTag(os, "/core/scripts/selenium-remoterunner.js");
    writeScriptTag(os, "/core/scripts/selenium-logging.js");
    writeScriptTag(os, "/core/xpath/util.js");
    writeScriptTag(os, "/core/xpath/xmltoken.js");
    writeScriptTag(os, "/core/xpath/dom.js");
    writeScriptTag(os, "/core/xpath/xpath.js");
    writeScriptTag(os, "/core/xpath/javascript-xpath-0.1.11.js");
    writeScriptTag(os, "/core/scripts/user-extensions.js");
  }

  private static void writeScriptTag(OutputStream os, String url) throws IOException {
    os.write("<script type=\"text/javascript\" src=\"/selenium-server".getBytes());<commit_msg>SimonStewart: Turns out that pii mode has been broken for a while.<commit_after>package org.openqa.selenium.server;

import org.openqa.jetty.http.HttpRequest;
import org.openqa.jetty.http.HttpResponse;
import org.openqa.jetty.util.IO;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class InjectionHelper {
  static Logger log = Logger.getLogger(InjectionHelper.class.getName());
  private static boolean failOnError = true;
  private static boolean browserSideLogEnabled = true;
  private static boolean INJECT_SCRIPT_TAGS = true;
  private static boolean tryToInjectInHead = false;
  private static String injectionHtml = "/core/scripts/injection.html";
  private static HashMap<String, HashMap<String, String>> jsStateInitializersBySessionId =
      new HashMap<String, HashMap<String, String>>();
  private static HashMap<String, String> sessionIdToUniqueId = new HashMap<String, String>();

  private static HashMap<String, String> contentTransformations = new HashMap<String, String>();
  private static List<String> userJsInjectionFiles = new LinkedList<String>();

  public static void setBrowserSideLogEnabled(boolean browserSideLogEnabled) {
    InjectionHelper.browserSideLogEnabled = browserSideLogEnabled;
  }

  public static void setInjectScriptTags(boolean injectScriptTags) {
    InjectionHelper.INJECT_SCRIPT_TAGS = injectScriptTags;
  }

  public static void setTryToInjectInHead(boolean tryToInjectInHead) {
    InjectionHelper.tryToInjectInHead = tryToInjectInHead;
  }

  public static void setInjectionHtml(String injectionHtml) {
    InjectionHelper.injectionHtml = injectionHtml;
  }

  public static void saveJsStateInitializer(String sessionId, String uniqueId, String jsVarName,
      String jsStateInitializer) {
    // when a new uniqueId is seen for a given sessionId, that means the page has
    // reloaded and the old state should be discarded
    if (sessionIdToUniqueId.containsKey(sessionId) &&
        !sessionIdToUniqueId.get(sessionId).equals(uniqueId)) {
      jsStateInitializersBySessionId.remove(sessionId);
      sessionIdToUniqueId.put(sessionId, uniqueId);
    }
    log.fine("Saving JavaScript state for session " + sessionId + "/" + uniqueId + " " + jsVarName +
        ": " + jsStateInitializer);
    if (!jsStateInitializersBySessionId.containsKey(sessionId)) {
      jsStateInitializersBySessionId.put(sessionId, new HashMap<String, String>());
    }
    HashMap<String, String> h = jsStateInitializersBySessionId.get(sessionId);
    StringBuffer sb = new StringBuffer("if (uniqueId!='");
    sb.append(uniqueId)
        .append("') {")
        .append(jsStateInitializer)
        .append("}");
    h.put(jsVarName, sb.toString());
  }

  public static String restoreJsStateInitializer(String sessionId, String uniqueId) {
    if (!jsStateInitializersBySessionId.containsKey(sessionId)) {
      return "";
    }
    HashMap<String, String> h = jsStateInitializersBySessionId.get(sessionId);
    if (h.isEmpty()) {
      return "";
    }
    StringBuffer sb = new StringBuffer();
    for (Map.Entry<String, String> entry : h.entrySet()) {
      final String jsVarName = entry.getKey();
      final String jsStateInitializer = entry.getValue();
      sb.append(jsStateInitializer)
          .append('\n');
      log.fine("Restoring JavaScript state for session " + sessionId + "/" + uniqueId
          + ": key=" + jsVarName + ": " + jsStateInitializer);
    }
    return sb.toString();
  }

  /**
   * re-read selenium js. Don't maintain it indefinitely for now since then we would need to restart
   * the server to see changes. Once the selenium js is firm, this should change.
   */
  public static void init() {
    String key = "__SELENIUM_JS__";

    StringBuffer sb = new StringBuffer();
    if (!INJECT_SCRIPT_TAGS) { // DGF experiment with using script tags
      try {
        appendFileContent(sb, "/core/scripts/xmlextras.js");
        appendFileContent(sb, "/core/lib/sizzle.js");
        appendFileContent(sb, "/core/scripts/htmlutils.js");
        appendFileContent(sb, "/core/scripts/ui-element.js");
        appendFileContent(sb, "/core/scripts/selenium-browserdetect.js");
        appendFileContent(sb, "/core/scripts/selenium-browserbot.js");
        appendFileContent(sb, "/core/scripts/find_matching_child.js");
        appendFileContent(sb, "/core/scripts/selenium-api.js");
        appendFileContent(sb,
            "/core/scripts/selenium-commandhandlers.js");
        appendFileContent(sb, "/core/scripts/selenium-executionloop.js");
        appendFileContent(sb, "/core/scripts/selenium-remoterunner.js");
        appendFileContent(sb, "/core/scripts/selenium-logging.js");
        appendFileContent(sb, "/core/xpath/util.js");
        appendFileContent(sb, "/core/xpath/xmltoken.js");
        appendFileContent(sb, "/core/xpath/dom.js");
        appendFileContent(sb, "/core/xpath/xpath.js");
        appendFileContent(sb, "/core/xpath/javascript-xpath-0.1.11.js");
        appendFileContent(sb, "/core/scripts/user-extensions.js");
      } catch (Exception e) {
        if (failOnError) {
          throw new RuntimeException(e);
        }
        log.info("failOnError is false, ignoring problems: "
            + e.getMessage());
        log.log(Level.FINE, "Ignored exception", e);
      }
    }
    contentTransformations.put(key, sb.toString());
  }

  private static void writeScriptTags(OutputStream os) throws IOException {
    // DGF script tags are SLOWER than regular injection! (remember, we disable the browser cache
    // entirely)

    writeScriptTag(os, "/core/scripts/xmlextras.js");
    writeScriptTag(os, "/core/lib/sizzle.js");
    writeScriptTag(os, "/core/scripts/atoms.js");
    writeScriptTag(os, "/core/scripts/htmlutils.js");
    writeScriptTag(os, "/core/scripts/ui-element.js");
    writeScriptTag(os, "/core/scripts/selenium-browserdetect.js");
    writeScriptTag(os, "/core/scripts/selenium-browserbot.js");
    writeScriptTag(os, "/core/scripts/find_matching_child.js");
    writeScriptTag(os, "/core/scripts/selenium-api.js");
    writeScriptTag(os, "/core/scripts/selenium-commandhandlers.js");
    writeScriptTag(os, "/core/scripts/selenium-executionloop.js");
    writeScriptTag(os, "/core/scripts/selenium-remoterunner.js");
    writeScriptTag(os, "/core/scripts/selenium-logging.js");
    writeScriptTag(os, "/core/xpath/util.js");
    writeScriptTag(os, "/core/xpath/xmltoken.js");
    writeScriptTag(os, "/core/xpath/dom.js");
    writeScriptTag(os, "/core/xpath/xpath.js");
    writeScriptTag(os, "/core/xpath/javascript-xpath-0.1.11.js");
    writeScriptTag(os, "/core/scripts/user-extensions.js");
  }

  private static void writeScriptTag(OutputStream os, String url) throws IOException {
    os.write("<script type=\"text/javascript\" src=\"/selenium-server".getBytes());
{'fraction_non_alphanumeric': 0.12524836786829407, 'fraction_numerical': 0.0011353959693443088, 'mean_word_length': 3.8832293832293834, 'pattern_counts': {'":': 6, '<': 34, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 8}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3019050', 'n_tokens_mistral': 4247, 'n_tokens_neox': 4173, 'n_words': 848}