<commit_before>/*
Copyright 2007-2011 WebDriver committers

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.openqa.grid.internal.utils;

import static org.openqa.grid.common.RegistrationRequest.AUTO_REGISTER;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.Servlet;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.exception.GridConfigurationException;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.web.servlet.ResourceServlet;
import org.openqa.grid.web.utils.ExtraServletUtil;
import org.openqa.jetty.http.HttpContext;
import org.openqa.jetty.jetty.Server;
import org.openqa.jetty.jetty.servlet.ServletHandler;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;

public class SelfRegisteringRemote {

	private static final Logger log = Logger.getLogger(SelfRegisteringRemote.class.getName());

	private RegistrationRequest nodeConfig;

	public SelfRegisteringRemote(RegistrationRequest config) {
		this.nodeConfig = config;
	}

	public URL getRemoteURL() {
		String base = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HOST) + ":"
				+ nodeConfig.getConfiguration().get(RegistrationRequest.PORT);
		String url = null;
		switch (nodeConfig.getRole()) {
		case REMOTE_CONTROL:
			url = base + "/selenium-server/driver";
			break;
		case WEBDRIVER:
			url = base + "/wd/hub";
			break;
		default:
			throw new GridConfigurationException("Cannot launch a node with role " + nodeConfig.getRole());
		}
		try {
			return new URL(url);
		} catch (MalformedURLException e) {
			throw new GridConfigurationException("error building the node url " + e.getMessage(), e);
		}
	}

	private SeleniumServer server;

	public void startRemoteServer() throws Exception {
		nodeConfig.validate();

		System.setProperty("org.openqa.jetty.http.HttpRequest.maxFormContentSize", "0");

		server = new SeleniumServer(nodeConfig.getRemoteControlConfiguration());

		Server jetty = server.getServer();

		String servletsStr = (String) nodeConfig.getConfiguration().get(GridNodeConfiguration.SERVLETS);
		if (servletsStr != null) {
			List<String> servlets = Arrays.asList(servletsStr.split(","));
			if (servlets != null) {
				HttpContext extra = new HttpContext();

				extra.setContextPath("/extra");
				ServletHandler handler = new ServletHandler();
				handler.addServlet("/resources/*", ResourceServlet.class.getName());

				for (String s : servlets) {
					Class<? extends Servlet> servletClass = ExtraServletUtil.createServlet(s);
					if (servletClass != null) {
						String path = "/" + servletClass.getSimpleName() + "/*";
						String clazz = servletClass.getCanonicalName();
						handler.addServlet(path, clazz);
						log.info("started extra node servlet visible at : http://xxx:" + nodeConfig.getConfiguration().get(RegistrationRequest.PORT)
								+ "/extra" + path);
					}
				}
				extra.addHandler(handler);
				jetty.addContext(extra);
			}
		}

		server.boot();
	}

	public void stopRemoteServer() {
		if (server != null) {
			server.stop();
		}
	}

	public void deleteAllBrowsers() {
		nodeConfig.getCapabilities().clear();
	}

	public void addBrowser(DesiredCapabilities cap, int instances) {
		String s = cap.getBrowserName();
		if (s == null || "".equals(s)) {
			throw new InvalidParameterException(cap + " does seems to be a valid browser.");
		}
		cap.setPlatform(Platform.getCurrent());
		cap.setCapability(RegistrationRequest.MAX_INSTANCES, instances);
		nodeConfig.getCapabilities().add(cap);
	}

	/**
	 * sends 1 registration request, bypassing the retry logic and the proxy
	 * already registered check. Use only for testing.
	 */
	public void sendRegistrationRequest() {

		registerToHub(false);
	}

	/**
	 * register the hub following the configuration :
	 * 
	 * - check if the proxy is already registered before sending a reg request.
	 * 
	 * - register again every X ms is specified in the config of the node.
	 */
	public void startRegistrationProcess() {
		log.info("using the json request : " + nodeConfig.toJSON());

		Boolean register = (Boolean) nodeConfig.getConfiguration().get(AUTO_REGISTER);

		if (!register) {
			log.info("no registration sent ( " + AUTO_REGISTER + " = false )");
		} else {
			final Integer o = (Integer) nodeConfig.getConfiguration().get(RegistrationRequest.REGISTER_CYCLE);
			System.out.println("O:" + o);
			if (o != null) {
<commit_msg>FrancoisReynaud: removing leftover sysout.<commit_after>/*
Copyright 2007-2011 WebDriver committers

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.openqa.grid.internal.utils;

import static org.openqa.grid.common.RegistrationRequest.AUTO_REGISTER;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.Servlet;

import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.grid.common.RegistrationRequest;
import org.openqa.grid.common.exception.GridConfigurationException;
import org.openqa.grid.common.exception.GridException;
import org.openqa.grid.web.servlet.ResourceServlet;
import org.openqa.grid.web.utils.ExtraServletUtil;
import org.openqa.jetty.http.HttpContext;
import org.openqa.jetty.jetty.Server;
import org.openqa.jetty.jetty.servlet.ServletHandler;
import org.openqa.selenium.Platform;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;

public class SelfRegisteringRemote {

	private static final Logger log = Logger.getLogger(SelfRegisteringRemote.class.getName());

	private RegistrationRequest nodeConfig;

	public SelfRegisteringRemote(RegistrationRequest config) {
		this.nodeConfig = config;
	}

	public URL getRemoteURL() {
		String base = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HOST) + ":"
				+ nodeConfig.getConfiguration().get(RegistrationRequest.PORT);
		String url = null;
		switch (nodeConfig.getRole()) {
		case REMOTE_CONTROL:
			url = base + "/selenium-server/driver";
			break;
		case WEBDRIVER:
			url = base + "/wd/hub";
			break;
		default:
			throw new GridConfigurationException("Cannot launch a node with role " + nodeConfig.getRole());
		}
		try {
			return new URL(url);
		} catch (MalformedURLException e) {
			throw new GridConfigurationException("error building the node url " + e.getMessage(), e);
		}
	}

	private SeleniumServer server;

	public void startRemoteServer() throws Exception {
		nodeConfig.validate();

		System.setProperty("org.openqa.jetty.http.HttpRequest.maxFormContentSize", "0");

		server = new SeleniumServer(nodeConfig.getRemoteControlConfiguration());

		Server jetty = server.getServer();

		String servletsStr = (String) nodeConfig.getConfiguration().get(GridNodeConfiguration.SERVLETS);
		if (servletsStr != null) {
			List<String> servlets = Arrays.asList(servletsStr.split(","));
			if (servlets != null) {
				HttpContext extra = new HttpContext();

				extra.setContextPath("/extra");
				ServletHandler handler = new ServletHandler();
				handler.addServlet("/resources/*", ResourceServlet.class.getName());

				for (String s : servlets) {
					Class<? extends Servlet> servletClass = ExtraServletUtil.createServlet(s);
					if (servletClass != null) {
						String path = "/" + servletClass.getSimpleName() + "/*";
						String clazz = servletClass.getCanonicalName();
						handler.addServlet(path, clazz);
						log.info("started extra node servlet visible at : http://xxx:" + nodeConfig.getConfiguration().get(RegistrationRequest.PORT)
								+ "/extra" + path);
					}
				}
				extra.addHandler(handler);
				jetty.addContext(extra);
			}
		}

		server.boot();
	}

	public void stopRemoteServer() {
		if (server != null) {
			server.stop();
		}
	}

	public void deleteAllBrowsers() {
		nodeConfig.getCapabilities().clear();
	}

	public void addBrowser(DesiredCapabilities cap, int instances) {
		String s = cap.getBrowserName();
		if (s == null || "".equals(s)) {
			throw new InvalidParameterException(cap + " does seems to be a valid browser.");
		}
		cap.setPlatform(Platform.getCurrent());
		cap.setCapability(RegistrationRequest.MAX_INSTANCES, instances);
		nodeConfig.getCapabilities().add(cap);
	}

	/**
	 * sends 1 registration request, bypassing the retry logic and the proxy
	 * already registered check. Use only for testing.
	 */
	public void sendRegistrationRequest() {

		registerToHub(false);
	}

	/**
	 * register the hub following the configuration :
	 * 
	 * - check if the proxy is already registered before sending a reg request.
	 * 
	 * - register again every X ms is specified in the config of the node.
	 */
	public void startRegistrationProcess() {
		log.info("using the json request : " + nodeConfig.toJSON());

		Boolean register = (Boolean) nodeConfig.getConfiguration().get(AUTO_REGISTER);

		if (!register) {
			log.info("no registration sent ( " + AUTO_REGISTER + " = false )");
		} else {
			final Integer o = (Integer) nodeConfig.getConfiguration().get(RegistrationRequest.REGISTER_CYCLE);
			if (o != null) {

{'fraction_non_alphanumeric': 0.11210563629918469, 'fraction_numerical': 0.0024813895781637717, 'mean_word_length': 4.58940069341258, 'pattern_counts': {'":': 2, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, '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': '5760328', 'n_tokens_mistral': 3581, 'n_tokens_neox': 3207, 'n_words': 827}