public static String[] getHostNameAndPort(String hostName, int port, SessionId session) { String[] hostAndPort = new String[2]; String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: \n"; try { HttpHost host = new HttpHost(hostName, port); CloseableHttpClient client = HttpClients.createSystem(); URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); String url = extractUrlFromResponse(response); if (url != null) { URL myURL = new URL(url); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostAndPort[0] = myURL.getHost(); hostAndPort[1] = Integer.toString(myURL.getPort()); } } } catch (Exception e) { Logger.getLogger(GridInfoExtractor.class.getName()).log(Level.SEVERE, null, errorMsg + e); } return hostAndPort; }
/** * Fetches and stores available logs from the given session and driver. * * @param sessionId The id of the session. * @param driver The driver to get the logs from. * @throws IOException If there was a problem reading from file. */ @Override public synchronized void fetchAndStoreLogsFromDriver(SessionId sessionId, WebDriver driver) throws IOException { if (!perSessionDriverEntries.containsKey(sessionId)) { perSessionDriverEntries.put(sessionId, Maps.<String, LogEntries>newHashMap()); } Map<String, LogEntries> typeToEntriesMap = perSessionDriverEntries.get(sessionId); if (storeLogsOnSessionQuit) { typeToEntriesMap.put(LogType.SERVER, getSessionLog(sessionId)); Set<String> logTypeSet = driver.manage().logs().getAvailableLogTypes(); for (String logType : logTypeSet) { typeToEntriesMap.put(logType, driver.manage().logs().get(logType)); } } }
/** * This creates a mapping between session and file representation of logs if doesnt exist already. * Writes the log records to the log file. This does *NOT* flush the logs to file. This does *NOT* * clear the records after writing to file. * * @param sessionId session-id to which the log records belong * @param records logRecords that need to be stored * @throws IOException */ synchronized public void flushRecordsToLogFile(SessionId sessionId, List<LogRecord> records) throws IOException { LogFile logFile = sessionToLogFileMap.get(sessionId); if (logFile == null) { createLogFileAndAddToMap(sessionId); logFile = sessionToLogFileMap.get(sessionId); } logFile.openLogWriter(); for (LogRecord record : records) { logFile.getLogWriter().writeObject(record); } logFile.closeLogWriter(); }
/** * This returns the log records storied in the corresponding log file. This does *NOT* clear the * log records in the file. * * @param sessionId session-id for which the file logs needs to be returned. * @return A List of LogRecord objects, which can be <i>null</i>. * @throws IOException */ public List<LogRecord> getLogRecords(SessionId sessionId) throws IOException { LogFile logFile = sessionToLogFileMap.get(sessionId); if (logFile == null) { return new ArrayList<LogRecord>(); } logFile.openLogReader(); ObjectInputStream logObjInStream = logFile.getLogReader(); List<LogRecord> logRecords = new ArrayList<LogRecord>(); try { LogRecord tmpLogRecord; while (null != (tmpLogRecord = (LogRecord) logObjInStream .readObject())) { logRecords.add(tmpLogRecord); } } catch (IOException ex) { logFile.closeLogReader(); return logRecords; } catch (ClassNotFoundException e) { logFile.closeLogReader(); return logRecords; } logFile.closeLogReader(); return logRecords; }
private DefaultSession(final DriverFactory factory, TemporaryFilesystem tempFs, SessionId sessionId, final Capabilities capabilities) throws Exception { this.knownElements = new KnownElements(); this.sessionId = sessionId; this.tempFs = tempFs; final BrowserCreator browserCreator = new BrowserCreator(factory, capabilities); final FutureTask<EventFiringWebDriver> webDriverFutureTask = new FutureTask<EventFiringWebDriver>(browserCreator); executor = new ThreadPoolExecutor(1, 1, 600L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>()); // Ensure that the browser is created on the single thread. EventFiringWebDriver initialDriver = execute(webDriverFutureTask); if (!isQuietModeEnabled(browserCreator, capabilities)) { // Memo to self; this is not a constructor escape of "this" - probably ;) initialDriver.register(new SnapshotScreenListener(this)); } this.driver = initialDriver; this.capabilities = browserCreator.getCapabilityDescription(); updateLastAccessTime(); }
/** * getTestNodeIP * Getter/Creator for the Test Node IP * * @param hostName the name of the host (root) * @param port the port to run against (if any) * @param session the Browser Session * @return hostAndPort (String) */ public String[] getTestNodeIP(String hostName, int port, SessionId session) { String[] hostAndPort = new String[2]; String errorMsg = "Failed to acquire remote webdriver node and port info. Root cause: "; try { HttpHost host = new HttpHost(hostName, port); HttpClient client = HttpClientBuilder.create().build(); URL sessionURL = new URL("http://" + hostName + ":" + port + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, r); JSONObject object = extractObject(response); URL myURL = new URL(object.getString("proxyId")); if ((myURL.getHost() != null) && (myURL.getPort() != -1)) { hostAndPort[0] = myURL.getHost(); hostAndPort[1] = Integer.toString(myURL.getPort()); } } catch (Exception e) { LOG.fatal(errorMsg + e); throw new RuntimeException(errorMsg, e); } return hostAndPort; }
public static GridInfo getHostNameAndPort(String hubHost, int hubPort, SessionId session) { GridInfo retVal = null; try { HttpHost host = new HttpHost(hubHost, hubPort); DefaultHttpClient client = new DefaultHttpClient(); URL sessionURL = new URL("http://" + hubHost + ":" + hubPort + "/grid/api/testsession?session=" + session); BasicHttpEntityEnclosingRequest basicHttpEntityEnclosingRequest = new BasicHttpEntityEnclosingRequest("POST", sessionURL.toExternalForm()); HttpResponse response = client.execute(host, basicHttpEntityEnclosingRequest); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { JSONObject object = extractObject(response); retVal = new GridInfo(object); } else { System.out.println("Problem connecting to Grid Server"); } } catch (JSONException | IOException e) { throw new RuntimeException("Failed to acquire remote webdriver node and port info", e); } return retVal; }
public void getSessions() { driver = new JavaDriver(); JavaDriver driver1 = new JavaDriver(); SessionId id1 = ((RemoteWebDriver) driver).getSessionId(); SessionId id2 = driver1.getSessionId(); AssertJUnit.assertFalse(id1.equals(id2)); }
@Override public WebDriver createDriver(final Browser browser, final XmlConfig config) { final RemoteWebDriver driver = mock(RemoteWebDriver.class); when(driver.getScreenshotAs(OutputType.BYTES)).thenReturn(new byte[]{1, 2, 3}); doReturn(new SessionId(randomAlphanumeric(14))).when(driver).getSessionId(); return driver; }
private static Boolean isSessionEmpty(){ Boolean isEmpty = false; SessionId session = ((AndroidDriver)getDriver()).getSessionId(); if(session == null){ isEmpty = true; }else{ isEmpty = false; } return isEmpty; }
public SessionId newSession(Capabilities desiredCapabilities) throws Exception { SessionId sessionId = new SessionId(UUID.randomUUID().toString()); Session session = DefaultSession.createSession(factory, sessionId, desiredCapabilities); sessionIdToDriver.put(sessionId, session); return sessionId; }
/** * New handler keeping track of log records per session. * * @param capacity The capacity * @param minimumLevel Only keep track of records whose level is equal or greater than * minimumLevel. * @param formatter Formatter to use when retrieving log messages. * @param captureLogsOnQuit Whether to enable log capture on quit. */ public DefaultPerSessionLogHandler(int capacity, Level minimumLevel, Formatter formatter, boolean captureLogsOnQuit) { this.capacity = capacity; this.formatter = formatter; this.storeLogsOnSessionQuit = captureLogsOnQuit; this.perSessionRecords = Maps.<SessionId, List<LogRecord>>newHashMap(); this.perThreadTempRecords = Maps.<ThreadKey, List<LogRecord>>newHashMap(); this.threadToSessionMap = Maps.<ThreadKey, SessionId>newHashMap(); this.sessionToThreadMap = Maps.<SessionId, ThreadKey>newHashMap(); this.logFileRepository = new SessionLogsToFileRepository(); this.perSessionDriverEntries = Maps.<SessionId, Map<String, LogEntries>>newHashMap(); }
private String formattedRecords(SessionId sessionId) throws IOException { final StringWriter writer; writer = new StringWriter(); for (LogRecord record : records(sessionId)) { writer.append(formatter.format(record)); } return writer.toString(); }
@Override public synchronized void attachToCurrentThread(SessionId sessionId) { ThreadKey threadId = new ThreadKey(); if (threadToSessionMap.get(threadId) == null || threadToSessionMap.get(threadId).equals(sessionId)) { threadToSessionMap.put(threadId, sessionId); sessionToThreadMap.put(sessionId, threadId); } transferThreadTempLogsToSessionLogs(sessionId); }
@Override public void transferThreadTempLogsToSessionLogs(SessionId sessionId) { ThreadKey threadId = new ThreadKey(); List<LogRecord> threadRecords = perThreadTempRecords.get(threadId); List<LogRecord> sessionRecords = perSessionRecords.get(sessionId); if (threadRecords != null) { if (sessionRecords == null) { sessionRecords = new ArrayList<LogRecord>(); perSessionRecords.put(sessionId, sessionRecords); } sessionRecords.addAll(threadRecords); } clearThreadTempLogs(); }
@Override public synchronized void detachFromCurrentThread() { ThreadKey threadId = new ThreadKey(); SessionId sessionId = threadToSessionMap.get(threadId); if (sessionId != null) { threadToSessionMap.remove(threadId); sessionToThreadMap.remove(sessionId); clearThreadTempLogs(); } }
/** * Removes session logs for the given session id. * * NB! If the handler has been configured to capture logs on quit no logs will be removed. * * @param sessionId The session id to use. */ @Override public synchronized void removeSessionLogs(SessionId sessionId) { if (storeLogsOnSessionQuit) { return; } ThreadKey threadId = sessionToThreadMap.get(sessionId); SessionId sessionIdForThread = threadToSessionMap.get(threadId); if (threadId != null && sessionIdForThread != null && sessionIdForThread.equals(sessionId)) { threadToSessionMap.remove(threadId); sessionToThreadMap.remove(sessionId); } perSessionRecords.remove(sessionId); logFileRepository.removeLogFile(sessionId); }
/** * This returns Selenium Remote Control logs associated with the sessionId. * * @param sessionId session-id for which the RC logs will be returned. * @return String RC logs for the sessionId * @throws IOException when the elves go bad */ @Override public synchronized String getLog(SessionId sessionId) throws IOException { // TODO(chandra): Provide option to clear logs after getLog() String logs = formattedRecords(sessionId); logs = "\n<RC_Logs RC_Session_ID=" + sessionId + ">\n" + logs + "\n</RC_Logs>\n"; return logs; }
/** * Returns the server log for the given session id. * * @param sessionId The session id. * @return The available server log entries for the session. * @throws IOException If there was a problem reading from file. */ @Override public synchronized LogEntries getSessionLog(SessionId sessionId) throws IOException { List<LogEntry> entries = Lists.<LogEntry>newLinkedList(); LogRecord[] records = records(sessionId); if (records != null) { for (LogRecord record : records) { if (record.getLevel().intValue() >= serverLogLevel.intValue()) entries.add(new LogEntry(record.getLevel(), record.getMillis(), record.getMessage())); } } return new LogEntries(entries); }
/** * Returns a list of session IDs for which there are logs. * * The type of logs that are available depends on the log types provided * by the driver. An included session id will at least have server logs. * * @return The list of session IDs. */ @Override public synchronized List<SessionId> getLoggedSessions() { // TODO: Find a solution that can handle large numbers of sessions, maybe by // reading them from disc. ImmutableList.Builder<SessionId> builder = new ImmutableList.Builder<SessionId>(); builder.addAll(perSessionDriverEntries.keySet()); return builder.build(); }
/** * Gets all logs for a session. * * @param sessionId The id of the session. * @return The logs for the session, ordered after log types in a session logs object. */ @Override public synchronized SessionLogs getAllLogsForSession(SessionId sessionId) { SessionLogs sessionLogs = new SessionLogs(); if (perSessionDriverEntries.containsKey(sessionId)) { Map<String, LogEntries> typeToEntriesMap = perSessionDriverEntries.get(sessionId); for (String logType : typeToEntriesMap.keySet()) { sessionLogs.addLog(logType, typeToEntriesMap.get(logType)); } perSessionDriverEntries.remove(sessionId); } return sessionLogs; }
/** * This creates log file object which represents logs in file form. This opens ObjectOutputStream * which is used to write logRecords to log file and opens a ObjectInputStream which is used to * read logRecords from the file. * * @param sessionId session-id for the log file entry needs to be created. * @throws IOException */ public void createLogFileAndAddToMap(SessionId sessionId) throws IOException { File rcLogFile; // create logFile; rcLogFile = File.createTempFile(sessionId.toString(), ".rclog"); rcLogFile.deleteOnExit(); LogFile logFile = new LogFile(rcLogFile.getAbsolutePath()); sessionToLogFileMap.put(sessionId, logFile); }
public void removeLogFile(SessionId sessionId) { LogFile logFile = sessionToLogFileMap.get(sessionId); sessionToLogFileMap.remove(sessionId); if (logFile == null) { return; } try { logFile.removeLogFile(); } catch (IOException e) { throw new RuntimeException(e); } }
@Override public Map<String, SessionLogs> handle() throws Exception { ImmutableMap.Builder<String, SessionLogs> builder = ImmutableMap.<String, SessionLogs>builder(); for (SessionId sessionId : LoggingManager.perSessionLogHandler().getLoggedSessions()) { builder.put(sessionId.toString(), LoggingManager.perSessionLogHandler().getAllLogsForSession(sessionId)); } return builder.build(); }
private Function<SessionId, SessionInfo> toSessionInfo() { return new Function<SessionId, SessionInfo>() { public SessionInfo apply(SessionId id) { Map<String, ?> capabilities = allSessions.get(id).getCapabilities().asMap(); return new SessionInfo(id, capabilities); } }; }
private void throwUpIfSessionTerminated(SessionId sessId) throws SessionNotFoundException { if (sessId == null) return; Session session = sessions.get(sessId); final boolean isTerminated = session == null; if (isTerminated){ throw new SessionNotFoundException(); } }
/** * Creates a response object for a successful command execution. * * @param sessionId ID of the session that executed the command. * @param value the command result value. * @return the new response object. */ public static Response success(SessionId sessionId, Object value) { Response response = new Response(); response.setSessionId(sessionId != null ? sessionId.toString() : null); response.setValue(value); response.setStatus(ErrorCodes.SUCCESS); response.setState(ErrorCodes.SUCCESS_STRING); return response; }
/** * Creates a response object for a failed command execution. * * @param sessionId ID of the session that executed the command. * @param reason the failure reason. * @return the new response object. */ public static Response failure(SessionId sessionId, Throwable reason) { Response response = new Response(); response.setSessionId(sessionId != null ? sessionId.toString() : null); response.setValue(reason); response.setStatus(ERROR_CODES.toStatusCode(reason)); response.setState(ERROR_CODES.toState(response.getStatus())); return response; }
/** * Creates a response object for a failed command execution. * * @param sessionId ID of the session that executed the command. * @param reason the failure reason. * @param screenshot a base64 png screenshot to include with the failure. * @return the new response object. */ public static Response failure( SessionId sessionId, Throwable reason, Optional<String> screenshot) { Response response = new Response(); response.setSessionId(sessionId != null ? sessionId.toString() : null); response.setStatus(ERROR_CODES.toStatusCode(reason)); response.setState(ERROR_CODES.toState(response.getStatus())); if (reason != null) { JsonObject json = new BeanToJsonConverter().convertObject(reason).getAsJsonObject(); json.addProperty("screen", screenshot.orNull()); response.setValue(json); } return response; }
public static Session createSession(DriverFactory factory, SessionId sessionId, Capabilities capabilities) throws Exception { File tmpDir = new File(System.getProperty("java.io.tmpdir"), sessionId.toString()); if (!tmpDir.mkdir()) { throw new WebDriverException("Cannot create temp directory: " + tmpDir); } TemporaryFilesystem tempFs = TemporaryFilesystem.getTmpFsBasedOn(tmpDir); return new DefaultSession(factory, tempFs, sessionId, capabilities); }
/** * Check the tear down. */ @Test public void testTearDown() throws IOException { // insert mock to test object firespottingIT.popupPage = this.popupPage; // mock rest client firespottingIT.restClient = mock(Resty.class); // mock some objects for session key RemoteWebDriver remoteWebDriver = mock(RemoteWebDriver.class); SessionId sessionId = mock(SessionId.class); when(popupPage.getDriver()).thenReturn(remoteWebDriver); when(remoteWebDriver.getSessionId()).thenReturn(sessionId); when(sessionId.toString()).thenReturn("72345863"); doReturn("sauceUsername").when(firespottingIT).getSystemVariable("SAUCE_USERNAME"); doReturn("sauceKey").when(firespottingIT).getSystemVariable("SAUCE_ACCESS_KEY"); doReturn("platform").when(firespottingIT).getSystemVariable("PLATFORM"); doReturn("travisBuildNr").when(firespottingIT).getSystemVariable("TRAVIS_BUILD_NUMBER"); // run test method firespottingIT.tearDown(); // is the method called to tear down correctly? verify(popupPage, atLeastOnce()).tearDown(); // verify rest client actions if environment variables are set // @TODO: add better verification! (no more anyStrings; check the values!) verify(firespottingIT.restClient, atLeastOnce()).authenticate(anyString(), anyString(), anyString().toCharArray()); verify(firespottingIT.restClient, atLeastOnce()).withHeader("Content-Type", "application/json"); }
public static SessionId getSessionId() { return sessionId.get(); }
public static void setSessionId(SessionId sessionId) { SeleniumHolder.sessionId.set(sessionId); }
public WebDriver resolve(BrowserType browser, String version) { try { boolean enableVnc = getBoolean("sel.jup.vnc"); recording = getBoolean("sel.jup.recording"); DesiredCapabilities capabilities = getCapabilities(browser, enableVnc); String imageVersion; if (version != null && !version.isEmpty() && !version.equalsIgnoreCase("latest")) { if (version.startsWith("latest-")) { version = selenoidConfig.getVersionFromLabel(browser, version); } imageVersion = selenoidConfig.getImageVersion(browser, version); capabilities.setCapability("version", imageVersion); } else { imageVersion = selenoidConfig.getDefaultBrowser(browser); } int selenoidPort = startDockerBrowser(browser, version, recording); int novncPort = 0; if (enableVnc) { novncPort = startDockerNoVnc(); } String dockerServerIp = dockerService.getDockerServerHost(); String selenoidHubUrl = format("http://%s:%d/wd/hub", dockerServerIp, selenoidPort); WebDriver webdriver = new RemoteWebDriver(new URL(selenoidHubUrl), capabilities); SessionId sessionId = ((RemoteWebDriver) webdriver).getSessionId(); String parameterName = parameter.getName(); name = parameterName + "_" + browser + "_" + imageVersion + "_" + ((RemoteWebDriver) webdriver).getSessionId(); Optional<Method> testMethod = context.getTestMethod(); if (testMethod.isPresent()) { name = testMethod.get().getName() + "_" + name; } if (index != null) { name += index; } if (enableVnc) { String vncUrl = format( "http://%s:%d/vnc.html?host=%s&port=%d&path=vnc/%s&resize=scale&autoconnect=true&password=%s", dockerServerIp, novncPort, dockerServerIp, selenoidPort, sessionId, getString("sel.jup.selenoid.vnc.password")); log.debug("Session {} VNC URL: {}", sessionId, vncUrl); if (getBoolean("sel.jup.vnc.create.redirect.html.page")) { String outputFolder = getOutputFolder(context); String vncHtmlPage = format( "<html><body onload=\"window.location.href='%s'\"></html>", vncUrl); write(Paths.get(outputFolder, name + ".html"), vncHtmlPage.getBytes()); } } if (recording) { recordingFile = new File(hostVideoFolder, sessionId + ".mp4"); } return webdriver; } catch (Exception e) { throw new SeleniumJupiterException(e); } }
private void updateSessionIdIfKnown() { SessionId sessionId = webdriverManager.getSessionId(); if (sessionId != null) { getCurrentTestOutcome().setSessionId(sessionId.toString()); } }
public static SessionId getSessionId(WebDriver driver) { if (driver instanceof RemoteWebDriver) { return ((RemoteWebDriver) driver).getSessionId(); } throw new IllegalArgumentException(); }
public Session get(SessionId sessionId) { return sessionIdToDriver.get(sessionId); }
public void deleteSession(SessionId sessionId) { final Session removedSession = sessionIdToDriver.remove(sessionId); if (removedSession != null) { removedSession.close(); } }
public Set<SessionId> getSessions() { return Collections.unmodifiableSet(sessionIdToDriver.keySet()); }
void checkExpiry() { for (SessionId sessionId : driverSessions.getSessions()) { Session session = driverSessions.get(sessionId); if (session != null) { boolean useDeleteSession = false; boolean killed = false; boolean inUse = session.isInUse(); if (!inUse && session.isTimedOut(clientGoneTimeout)) { useDeleteSession = true; log.info("Session " + session.getSessionId() + " deleted due to client timeout"); } if (inUse && session.isTimedOut(insideBrowserTimeout)) { WebDriver driver = session.getDriver(); if (driver instanceof EventFiringWebDriver){ driver = ((EventFiringWebDriver)driver).getWrappedDriver(); } if (driver instanceof Killable) { //session.interrupt(); ((Killable) driver).kill(); killed = true; log.warning("Browser killed and session " + session.getSessionId() + " terminated due to in-browser timeout."); } else { useDeleteSession = true; log.warning("Session " + session.getSessionId() + " deleted due to in-browser timeout. " + "Terminating driver with DeleteSession since it does not support Killable, " + "the driver in question does not support selenium-server timeouts fully"); } } if (useDeleteSession) { DeleteSession deleteSession = new DeleteSession(session); try { deleteSession.call(); } catch (Exception e) { throw new RuntimeException(e); } } if (useDeleteSession || killed) { driverSessions.deleteSession(sessionId); final PerSessionLogHandler logHandler = LoggingManager.perSessionLogHandler(); logHandler.transferThreadTempLogsToSessionLogs(sessionId); logHandler.removeSessionLogs(sessionId); } } } }