/**
   * Rewrites the given browser string based on server settings.
   *
   * @param inputString the input browser string
   * @return a possibly-modified browser string.
   * @throws IllegalArgumentException if inputString is null.
   */
  private String validateBrowserString(String inputString, RemoteControlConfiguration configuration)
      throws IllegalArgumentException {
    String browserString = inputString;
    if (configuration.getForcedBrowserMode() != null) {
      browserString = configuration.getForcedBrowserMode();
      log.info("overriding browser mode w/ forced browser mode setting: " + browserString);
    }
    if (configuration.getProxyInjectionModeArg() && browserString.equals("*iexplore")) {
      log.warning(
          "running in proxy injection mode, but you used a *iexplore browser string; this is "
              + "almost surely inappropriate, so I'm changing it to *piiexplore...");
      browserString = "*piiexplore";
    } else if (configuration.getProxyInjectionModeArg()
        && (browserString.equals("*firefox")
            || browserString.equals("*firefox2")
            || browserString.equals("*firefox3"))) {
      log.warning(
          "running in proxy injection mode, but you used a "
              + browserString
              + " browser string; this is "
              + "almost surely inappropriate, so I'm changing it to *pifirefox...");
      browserString = "*pifirefox";
    }

    if (null == browserString) {
      throw new IllegalArgumentException("browser string may not be null");
    }
    return browserString;
  }
 @Test
 public void testWithDontTouchLogging() {
   RemoteControlConfiguration remoteControlConfiguration = new RemoteControlConfiguration();
   remoteControlConfiguration.setDontTouchLogging(true);
   LoggingManager.configureLogging(remoteControlConfiguration, true);
   assertNotNull(LoggingManager.perSessionLogHandler());
 }
  @BeforeClass
  public static void setUp() throws Exception {
    System.out.println("*** Starting selenium ... ***");
    RemoteControlConfiguration seleniumConfig = new RemoteControlConfiguration();
    seleniumConfig.setPort(4444);
    seleniumServer = new SeleniumServer(seleniumConfig);
    seleniumServer.start();

    String host = System.getProperty("myParam", "localhost");
    selenium = createSeleniumClient("http://" + host + ":" + "8080/client/");
    selenium.start();
    System.out.println("*** Started selenium ***");
  }
 /**
  * Gets a new browser session, using the SeleniumServer static fields to populate parameters.
  *
  * @param browserString
  * @param startURL
  * @param extensionJs per-session user extension Javascript
  * @param configuration Remote Control configuration. Cannot be null.
  * @return the BrowserSessionInfo for the new browser session.
  * @throws RemoteCommandException
  */
 public BrowserSessionInfo getNewBrowserSession(
     String browserString,
     String startURL,
     String extensionJs,
     Capabilities browserConfigurations,
     RemoteControlConfiguration configuration)
     throws RemoteCommandException {
   return getNewBrowserSession(
       browserString,
       startURL,
       extensionJs,
       browserConfigurations,
       configuration.reuseBrowserSessions(),
       configuration.isEnsureCleanSession(),
       configuration);
 }
  @Test
  public void launchRemoteSession_generatesSslCertsIfBrowserSideLogEnabled() throws Exception {
    String location = null;

    generator = createStrictMock(SslCertificateGenerator.class);
    generator.generateSSLCertsForLoggingHosts();
    expectLastCall().once();

    remoteConfiguration.setSeleniumServer(generator);
    ((DesiredCapabilities) browserOptions).setCapability("browserSideLog", true);

    launcher =
        new SafariCustomProfileLauncher(browserOptions, remoteConfiguration, "session", location) {
          @Override
          protected void launch(String url) {}

          @Override
          protected BrowserInstallation locateSafari(String location) {
            return new BrowserInstallation("", "");
          }
        };

    replay(generator);
    launcher.launchRemoteSession("http://url");
    verify(generator);
  }
 public void run() {
   try {
     String startURL =
         "http://localhost:"
             + configuration.getPortDriversShouldContact()
             + "/selenium-server/driver/?sessionId="
             + sessionId
             + "&uniqueId="
             + uniqueId;
     String commandLine =
         doBrowserRequest(
             startURL + "&seleniumStart=true&sequenceNumber=" + sequenceNumber++, "START");
     while (!interrupted) {
       log.info("MOCK: " + commandLine);
       RemoteCommand sc = DefaultRemoteCommand.parse(commandLine);
       String result = doCommand(sc);
       if (browserOptions.is("browserSideLog") && !interrupted) {
         for (int i = 0; i < 3; i++) {
           doBrowserRequest(
               startURL + "&logging=true&sequenceNumber=" + sequenceNumber++,
               "logLevel=debug:dummy log message " + i + "\n");
         }
       }
       if (!interrupted) {
         commandLine = doBrowserRequest(startURL + "&sequenceNumber=" + sequenceNumber++, result);
       }
     }
     log.info("MOCK: interrupted, exiting");
   } catch (Exception e) {
     RuntimeException re = new RuntimeException("Exception in mock browser", e);
     re.printStackTrace();
     throw re;
   }
 }
 public void testThrowsExceptionOnFailedBrowserLaunch() throws Exception {
   RemoteControlConfiguration configuration = new RemoteControlConfiguration();
   configuration.setTimeoutInSeconds(3);
   SeleniumServer server = new SeleniumServer(false, configuration);
   server.start();
   SeleniumDriverResourceHandler sdrh = new SeleniumDriverResourceHandler(server);
   try {
     sdrh.getNewBrowserSession("*mock", null, "", null);
     fail("Launch should have failed");
   } catch (RemoteCommandException rce) {
     // passes.
   } finally {
     if (server != null) {
       server.stop();
     }
   }
 }
  /**
   * Gets a new browser session
   *
   * @param browserString
   * @param startURL
   * @param extensionJs per-session user extension Javascript
   * @param configuration Remote Control configuration. Cannot be null.
   * @param useCached if a cached session should be used if one is available
   * @param ensureClean if a clean session (e.g. no previous cookies) is required.
   * @return the BrowserSessionInfo for the new browser session.
   * @throws RemoteCommandException
   */
  protected BrowserSessionInfo getNewBrowserSession(
      String browserString,
      String startURL,
      String extensionJs,
      Capabilities browserConfigurations,
      boolean useCached,
      boolean ensureClean,
      RemoteControlConfiguration configuration)
      throws RemoteCommandException {

    BrowserSessionInfo sessionInfo = null;
    browserString = validateBrowserString(browserString, configuration);

    if (configuration.getProxyInjectionModeArg()) {
      InjectionHelper.setBrowserSideLogEnabled(configuration.isBrowserSideLogEnabled());
      InjectionHelper.init();
    }

    if (useCached) {
      log.info("grabbing available session...");
      sessionInfo = grabAvailableSession(browserString, startURL);
    }

    // couldn't find one in the cache, or not reusing sessions.
    if (null == sessionInfo) {
      log.info("creating new remote session");
      sessionInfo =
          createNewRemoteSession(
              browserString,
              startURL,
              extensionJs,
              browserConfigurations,
              ensureClean,
              configuration);
    }

    assert null != sessionInfo;
    if (false /* ensureClean */) {
      // need to add this to the launcher API.
      // sessionInfo.launcher.hideCurrentSessionData();
    }
    return sessionInfo;
  }
 /**
  * Ends a browser session.
  *
  * @param sessionId the id of the session to be ended
  * @param configuration Remote Control configuration. Cannot be null.
  * @param ensureClean if clean sessions (e.g. no leftover cookies) are required.
  */
 protected void endBrowserSession(
     boolean forceClose,
     String sessionId,
     RemoteControlConfiguration configuration,
     boolean ensureClean) {
   BrowserSessionInfo sessionInfo = lookupInfoBySessionId(sessionId, activeSessions);
   if (null != sessionInfo) {
     activeSessions.remove(sessionInfo);
     try {
       if (forceClose || !configuration.reuseBrowserSessions()) {
         shutdownBrowserAndClearSessionData(sessionInfo);
       } else {
         if (null != sessionInfo.session) { // optional field
           sessionInfo.session.reset(sessionInfo.baseUrl);
         }
         // mark what time this session was ended
         sessionInfo.lastClosedAt = System.currentTimeMillis();
         availableSessions.add(sessionInfo);
       }
     } finally {
       LoggingManager.perSessionLogHandler().removeSessionLogs(new SessionId(sessionId));
       if (ensureClean) {
         // need to add this to the launcher API.
         // sessionInfo.launcher.restoreOriginalSessionData();
       }
     }
   } else {
     // look for it in the available sessions.
     sessionInfo = lookupInfoBySessionId(sessionId, availableSessions);
     if (null != sessionInfo && (forceClose || !configuration.reuseBrowserSessions())) {
       try {
         availableSessions.remove(sessionInfo);
         shutdownBrowserAndClearSessionData(sessionInfo);
       } finally {
         LoggingManager.perSessionLogHandler().removeSessionLogs(new SessionId(sessionId));
         if (ensureClean) {
           // sessionInfo.launcher.restoreOriginalSessionData();
         }
       }
     }
   }
 }
  @BeforeSuite(alwaysRun = true)
  public void setupBeforeSuite(ITestContext context) {
    String seleniumHost = "localhost";
    String seleniumPort = "9080";
    String seleniumBrowser = "firefox";
    String seleniumUrl = "http://localhost:8080/molgenis_apps/";

    RemoteControlConfiguration rcc = new RemoteControlConfiguration();
    rcc.setSingleWindow(true);
    rcc.setPort(Integer.parseInt(seleniumPort));

    try {
      server = new SeleniumServer(false, rcc);
      server.boot();
    } catch (Exception e) {
      throw new IllegalStateException("Can't start selenium server", e);
    }

    proc =
        new HttpCommandProcessor(
            seleniumHost, Integer.parseInt(seleniumPort), seleniumBrowser, seleniumUrl);
    selenium = new DefaultSelenium(proc);
    selenium.start();
  }
  public FrameGroupCommandQueueSet(
      String sessionId, int portDriversShouldContact, RemoteControlConfiguration configuration) {

    this.sessionId = sessionId;
    this.portDriversShouldContact = portDriversShouldContact;
    this.configuration = configuration;
    this.extensionJs = "";
    proxyInjectionMode = configuration.getProxyInjectionModeArg();

    /*
     * Initialize delay, using the static CommandQueue getSpeed
     * in order to imitate previous behavior, wherein that static
     * field would control the speed for all sessions.  The
     * speed for a frame group's queues will only be changed if
     * they're changed via this class's setSpeed().
     */
    millisecondDelayBetweenOperations = new AtomicInteger(CommandQueue.getSpeed());
  }
  /**
   * Method to start selenium server
   *
   * @author Gaurav Bansal
   */
  public void startSeleniumServer() {
    logger.info("Starting Selenium Server.........This might take around 10-15 seconds.");
    RemoteControlConfiguration rcc = new RemoteControlConfiguration();
    rcc.setPort(4444);
    rcc.setTimeoutInSeconds(600);
    rcc.setSingleWindow(false);

    rcc.setFirefoxProfileTemplate(
        new File(ConfigFileReader.getConfigItemValue("selenium.firefox.profile")));
    // rcc.setAvoidProxy(true);
    rcc.setTrustAllSSLCertificates(true);

    try {
      server = new SeleniumServer(false, rcc);
      server.boot();

    } catch (Exception e) {
      logger.info(e.getMessage());
      logger.info("Server is already running so reusing that.....");
    }
  }
  /**
   * Creates and tries to open a new session.
   *
   * @param browserString
   * @param startURL
   * @param extensionJs
   * @param configuration Remote Control configuration. Cannot be null.
   * @param ensureClean if a clean session is required
   * @return the BrowserSessionInfo of the new session.
   * @throws RemoteCommandException if the browser failed to launch and request work in the required
   *     amount of time.
   */
  protected BrowserSessionInfo createNewRemoteSession(
      String browserString,
      String startURL,
      String extensionJs,
      Capabilities browserConfiguration,
      boolean ensureClean,
      RemoteControlConfiguration configuration)
      throws RemoteCommandException {

    final FrameGroupCommandQueueSet queueSet;
    final BrowserSessionInfo sessionInfo;
    final BrowserLauncher launcher;
    String sessionId;

    sessionId = UUID.randomUUID().toString().replace("-", "");
    if ("*webdriver".equals(browserString) && browserConfiguration != null) {
      Object id = browserConfiguration.getCapability("webdriver.remote.sessionid");
      if (id != null && id instanceof String) {
        sessionId = (String) id;
      }
    }

    queueSet = makeQueueSet(sessionId, configuration.getPortDriversShouldContact(), configuration);
    queueSet.setExtensionJs(extensionJs);

    try {
      launcher =
          browserLauncherFactory.getBrowserLauncher(
              browserString, sessionId, configuration, browserConfiguration);
    } catch (InvalidBrowserExecutableException e) {
      throw new RemoteCommandException(e.getMessage(), "");
    }

    sessionInfo = new BrowserSessionInfo(sessionId, browserString, startURL, launcher, queueSet);
    SessionIdTracker.setLastSessionId(sessionId);
    log.info("Allocated session " + sessionId + " for " + startURL + ", launching...");

    final PerSessionLogHandler perSessionLogHandler = LoggingManager.perSessionLogHandler();
    perSessionLogHandler.attachToCurrentThread(new SessionId(sessionId));
    try {
      launcher.launchRemoteSession(startURL);
      queueSet.waitForLoad(configuration.getTimeoutInSeconds() * 1000l);

      // TODO DGF log4j only
      // NDC.push("sessionId="+sessionId);
      FrameGroupCommandQueueSet queue = getQueueSet(sessionId);
      queue.doCommand("setContext", sessionId, "");

      activeSessions.add(sessionInfo);
      return sessionInfo;
    } catch (Exception e) {
      /*
       * At this point the session might not have been added to neither available nor active
       * sessions. This session is unlikely to be of any practical use so we need to make sure we
       * close the browser and clear all session data.
       */
      log.log(
          Level.SEVERE,
          "Failed to start new browser session, shutdown browser and clear all session data",
          e);
      shutdownBrowserAndClearSessionData(sessionInfo);
      throw new RemoteCommandException("Error while launching browser", "", e);
    } finally {
      perSessionLogHandler.detachFromCurrentThread();
    }
  }
 /**
  * Isolated dependency
  *
  * @param sessionId
  * @param port
  * @param configuration
  * @return a new FrameGroupCommandQueueSet instance
  */
 protected FrameGroupCommandQueueSet makeQueueSet(
     String sessionId, int port, RemoteControlConfiguration configuration) {
   return FrameGroupCommandQueueSet.makeQueueSet(
       sessionId, configuration.getPortDriversShouldContact(), configuration);
 }
 /**
  * Ends a browser session, using SeleniumServer static fields to populate parameters.
  *
  * @param sessionId the id of the session to be ended
  * @param configuration Remote Control configuration. Cannot be null.
  */
 public void endBrowserSession(
     boolean forceClose, String sessionId, RemoteControlConfiguration configuration) {
   endBrowserSession(forceClose, sessionId, configuration, configuration.isEnsureCleanSession());
 }
 protected static void startJettyProxy() throws Exception {
   RemoteControlConfiguration config = new RemoteControlConfiguration();
   config.setPort(SELENIUM_SERVER_PORT);
   jettyProxy = new SeleniumServer(config);
   jettyProxy.start();
 }