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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.Speed;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.FileHandler;
import org.openqa.selenium.internal.FindsByClassName;
import org.openqa.selenium.internal.FindsById;
import org.openqa.selenium.internal.FindsByLinkText;
import org.openqa.selenium.internal.FindsByName;
import org.openqa.selenium.internal.FindsByTagName;
import org.openqa.selenium.internal.FindsByXPath;
import org.openqa.selenium.internal.TemporaryFilesystem;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.Context;
import org.openqa.selenium.remote.SessionId;

public class ChromeDriver implements WebDriver, SearchContext, JavascriptExecutor,
FindsById, FindsByClassName, FindsByLinkText, FindsByName, FindsByTagName, FindsByXPath {

  private Process clientProcess;
  private ChromeCommandExecutor executor;
  
  public ChromeDriver() throws Exception {
    init();
  }
  
  private void init() throws Exception {
    this.executor = new ChromeCommandExecutor(9700, 9701);
    try {
      startClient();
    } catch (Exception e) {
      executor.stopListening();
      stopClient();
      throw e;
    }
    //Ick, we sleep for a little bit in case the browser hasn't quite loaded
    Thread.sleep(2500);
  }
  
  /**
   * By default will try to load Chrome from system property
   * webdriver.chrome.bin and the extension from
   * webdriver.chrome.extensiondir.  If the former fails, will try to guess the
   * path to Chrome.  If the latter fails, will try to unzip from the JAR we 
   * hope we're in.  If these fail, throws exceptions.
   */
  protected void startClient() {
    try {
      File extensionDir = getExtensionDir();
      if (!extensionDir.isDirectory()) {
        throw new FileNotFoundException("Could not find extension directory" +
            "(" + extensionDir + ").  Try setting webdriver.chrome.extensiondir."); 
      }
      File chromeFile = getChromeFile();
      if (!chromeFile.isFile()) {
        throw new FileNotFoundException("Could not find chrome binary(" +
            chromeFile.getCanonicalPath() + ").  " +
            "Try setting webdriver.chrome.bin.");
      }
      
      File profileDir = TemporaryFilesystem.createTempDir("profile", "");
      
      String[] toExec = new String[3];
      toExec[0] = chromeFile.getCanonicalPath();
      toExec[1] = "--user-data-dir=" + wrapInQuotesIfWindows(profileDir.getCanonicalPath());
      toExec[2] = " --load-extension=" + wrapInQuotesIfWindows(extensionDir.getCanonicalPath()); 
      clientProcess = Runtime.getRuntime().exec(toExec);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  protected void stopClient() {
    if (clientProcess != null) {
      System.out.println("Killing browser");
      clientProcess.destroy();
      clientProcess = null;
    }
    try {
      executor.stopListening();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  Response execute(String commandName, Object... parameters) {
    Command command = new Command(new SessionId("[No sessionId]"),
                                  new Context("[No context]"),
                                  commandName,
                                  parameters);
    try {
      return executor.execute(command);
    } catch (Exception e) {
      if (e instanceof UnsupportedOperationException ||
          e instanceof IllegalArgumentException ||
          e instanceof FatalChromeException) {
        /*if (e instanceof ChromeDriverException) {
          try { Thread.sleep(100000); } catch (Exception e2) {}
        }*/
        //These exceptions may leave the extension hung, or in an
        //inconsistent state, so we restart Chrome
        stopClient();
        try {
          executor.stopListening();
          init();
        } catch (Exception e2) {
          throw new RuntimeException(e2);
        }
      }
      if (e instanceof RuntimeException) {
        throw (RuntimeException)e;
      } else {
        throw new RuntimeException(e);
      }
    }
  }
  
  protected File getExtensionDir() throws IOException {
    File extensionDir = null;
    String extensionDirSystemProperty = System.getProperty(
        "webdriver.chrome.extensiondir");
    if (extensionDirSystemProperty != null &&
        extensionDirSystemProperty != "") {
      //Default to reading from the property
      extensionDir = new File(extensionDirSystemProperty);
    } else {
      //If property not set, try to unpack the zip from the jar
      extensionDir = FileHandler.unzip(this.getClass().getResourceAsStream(
          "/chrome-extension.zip"));
    }
    return extensionDir;
  }
  
  /**
   * This is a fairly ugly way of getting the path
   * @return Absolute path to chrome executable
   * @throws IOException if file could not be found/accessed
   */
  protected File getChromeFile() throws IOException {
    File chromeFile = null;
    String chromeFileSystemProperty = System.getProperty(
        "webdriver.chrome.bin");
    if (chromeFileSystemProperty != null) {
      chromeFile = new File(chromeFileSystemProperty);
    } else {
      StringBuilder chromeFileString = new StringBuilder();
      if (System.getProperty("os.name").equals("Windows XP")) {
        chromeFileString.append(System.getProperty("user.home"))
                        .append("\\Local Settings\\Application Data\\")
                        .append("Google\\Chrome\\Application\\chrome.exe");
      } else if (System.getProperty("os.name").equals("Windows Vista")) {
        chromeFileString.append("C:\\Users\\")
                        .append(System.getProperty("user.name"))
                        .append("\\AppData\\Local\\")
                        .append("Google\\Chrome\\Application\\chrome.exe");
      } else if (System.getProperty("os.name").equals("Linux")) {
        chromeFileString.append("/usr/bin/google-chrome");
      } else if (System.getProperty("os.name").startsWith("Mac OS")) {
        File binary = new File("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome");
        if (binary.exists()) {
          chromeFileString.append(binary.getCanonicalFile());
        } else {
          binary = new File("/Users/" + System.getProperty("user.name") +
              binary.getCanonicalPath());
          if (binary.exists()) {
            chromeFileString.append(binary.getCanonicalFile());
          } else {
            throw new WebDriverException("Couldn't locate Chrome.  " +
                "Set webdriver.chrome.bin");
          }
        }
      } else {
        throw new WebDriverException("Unsupported operating system.  " +
            "Could not locate Chrome.  Set webdriver.chrome.bin");
      }
      chromeFile = new File(chromeFileString.toString());
    }
    return chromeFile;
  }
  
  private String wrapInQuotesIfWindows(String arg) {
    if (System.getProperty("os.name").startsWith("Windows")) {
      return "\"" + arg + "\"";
    } else {
      return arg;
    }
  }

  public void close() {
    throw new UnsupportedOperationException("Not yet supported in Chrome");
  }

  public WebElement findElement(By by) {
    return by.findElement((SearchContext)this);
  }

  public List<WebElement> findElements(By by) {
    return by.findElements((SearchContext)this);
  }

  public void get(String url) {
    execute("get", url);<commit_msg>DanielWagnerHall: Use the Platform enum<commit_after>package org.openqa.selenium.chrome;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.Speed;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.internal.FileHandler;
import org.openqa.selenium.internal.FindsByClassName;
import org.openqa.selenium.internal.FindsById;
import org.openqa.selenium.internal.FindsByLinkText;
import org.openqa.selenium.internal.FindsByName;
import org.openqa.selenium.internal.FindsByTagName;
import org.openqa.selenium.internal.FindsByXPath;
import org.openqa.selenium.internal.TemporaryFilesystem;
import org.openqa.selenium.remote.Command;
import org.openqa.selenium.remote.Context;
import org.openqa.selenium.remote.SessionId;

public class ChromeDriver implements WebDriver, SearchContext, JavascriptExecutor,
FindsById, FindsByClassName, FindsByLinkText, FindsByName, FindsByTagName, FindsByXPath {

  private Process clientProcess;
  private ChromeCommandExecutor executor;
  
  public ChromeDriver() throws Exception {
    init();
  }
  
  private void init() throws Exception {
    this.executor = new ChromeCommandExecutor(9700, 9701);
    try {
      startClient();
    } catch (Exception e) {
      executor.stopListening();
      stopClient();
      throw e;
    }
    //Ick, we sleep for a little bit in case the browser hasn't quite loaded
    Thread.sleep(2500);
  }
  
  /**
   * By default will try to load Chrome from system property
   * webdriver.chrome.bin and the extension from
   * webdriver.chrome.extensiondir.  If the former fails, will try to guess the
   * path to Chrome.  If the latter fails, will try to unzip from the JAR we 
   * hope we're in.  If these fail, throws exceptions.
   */
  protected void startClient() {
    try {
      File extensionDir = getExtensionDir();
      if (!extensionDir.isDirectory()) {
        throw new FileNotFoundException("Could not find extension directory" +
            "(" + extensionDir + ").  Try setting webdriver.chrome.extensiondir."); 
      }
      File chromeFile = getChromeFile();
      if (!chromeFile.isFile()) {
        throw new FileNotFoundException("Could not find chrome binary(" +
            chromeFile.getCanonicalPath() + ").  " +
            "Try setting webdriver.chrome.bin.");
      }
      
      File profileDir = TemporaryFilesystem.createTempDir("profile", "");
      
      String[] toExec = new String[3];
      toExec[0] = chromeFile.getCanonicalPath();
      toExec[1] = "--user-data-dir=" + wrapInQuotesIfWindows(profileDir.getCanonicalPath());
      toExec[2] = " --load-extension=" + wrapInQuotesIfWindows(extensionDir.getCanonicalPath()); 
      clientProcess = Runtime.getRuntime().exec(toExec);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
  
  protected void stopClient() {
    if (clientProcess != null) {
      System.out.println("Killing browser");
      clientProcess.destroy();
      clientProcess = null;
    }
    try {
      executor.stopListening();
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
  
  Response execute(String commandName, Object... parameters) {
    Command command = new Command(new SessionId("[No sessionId]"),
                                  new Context("[No context]"),
                                  commandName,
                                  parameters);
    try {
      return executor.execute(command);
    } catch (Exception e) {
      if (e instanceof UnsupportedOperationException ||
          e instanceof IllegalArgumentException ||
          e instanceof FatalChromeException) {
        /*if (e instanceof ChromeDriverException) {
          try { Thread.sleep(100000); } catch (Exception e2) {}
        }*/
        //These exceptions may leave the extension hung, or in an
        //inconsistent state, so we restart Chrome
        stopClient();
        try {
          executor.stopListening();
          init();
        } catch (Exception e2) {
          throw new RuntimeException(e2);
        }
      }
      if (e instanceof RuntimeException) {
        throw (RuntimeException)e;
      } else {
        throw new RuntimeException(e);
      }
    }
  }
  
  protected File getExtensionDir() throws IOException {
    File extensionDir = null;
    String extensionDirSystemProperty = System.getProperty(
        "webdriver.chrome.extensiondir");
    if (extensionDirSystemProperty != null &&
        extensionDirSystemProperty != "") {
      //Default to reading from the property
      extensionDir = new File(extensionDirSystemProperty);
    } else {
      //If property not set, try to unpack the zip from the jar
      extensionDir = FileHandler.unzip(this.getClass().getResourceAsStream(
          "/chrome-extension.zip"));
    }
    return extensionDir;
  }
  
  /**
   * This is a fairly ugly way of getting the path
   * @return Absolute path to chrome executable
   * @throws IOException if file could not be found/accessed
   */
  protected File getChromeFile() throws IOException {
    File chromeFile = null;
    String chromeFileSystemProperty = System.getProperty(
        "webdriver.chrome.bin");
    if (chromeFileSystemProperty != null) {
      chromeFile = new File(chromeFileSystemProperty);
    } else {
      StringBuilder chromeFileString = new StringBuilder();
      if (Platform.getCurrent().is(Platform.XP)) {
        chromeFileString.append(System.getProperty("user.home"))
                        .append("\\Local Settings\\Application Data\\")
                        .append("Google\\Chrome\\Application\\chrome.exe");
      } else if (Platform.getCurrent().is(Platform.VISTA)) {
        chromeFileString.append("C:\\Users\\")
                        .append(System.getProperty("user.name"))
                        .append("\\AppData\\Local\\")
                        .append("Google\\Chrome\\Application\\chrome.exe");
      } else if (Platform.getCurrent().is(Platform.UNIX)) {
        chromeFileString.append("/usr/bin/google-chrome");
      } else if (Platform.getCurrent().is(Platform.MAC)) {
        String[] paths = new String[] {
          "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
          "/Users/" + System.getProperty("user.name") +
              "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"};
        boolean foundPath = false;
        for (String path : paths) {
          File binary = new File(path);
          if (binary.exists()) {
            chromeFileString.append(binary.getCanonicalFile());
            foundPath = true;
            break;
          }
        }
        if (!foundPath) {
          throw new WebDriverException("Couldn't locate Chrome.  " +
              "Set webdriver.chrome.bin");
        }
      } else {
        throw new WebDriverException("Unsupported operating system.  " +
            "Could not locate Chrome.  Set webdriver.chrome.bin");
      }
      chromeFile = new File(chromeFileString.toString());
    }
    return chromeFile;
  }
  
  private String wrapInQuotesIfWindows(String arg) {
    if (Platform.getCurrent().is(Platform.WINDOWS)) {
      return "\"" + arg + "\"";
    } else {
      return arg;
    }
  }

  public void close() {
    throw new UnsupportedOperationException("Not yet supported in Chrome");
  }

  public WebElement findElement(By by) {
    return by.findElement((SearchContext)this);
  }

  public List<WebElement> findElements(By by) {
    return by.findElements((SearchContext)this);
  }

  public void get(String url) {
    execute("get", url);
{'fraction_non_alphanumeric': 0.11072144288577154, 'fraction_numerical': 0.0031312625250501003, 'mean_word_length': 2.7389370170920158, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3107090', 'n_tokens_mistral': 4479, 'n_tokens_neox': 4351, 'n_words': 1046}