/*
JSR77 proxy: NOT exposed via WSStats
503963
public String[] getJ2EEStatisticNames() {
        ArrayList members = copyStatistics();
        if (members == null)
            return new String[0];

        String[] ret = new String[members.size()];
        for (int i = 0; i < ret.length; i++) {
            if (members.get(i) != null)
                ret[i] = ((StatisticImpl) members.get(i)).getName();
        }
        return ret;
    }
543199
function(client, sinfo) {
  let proxy = client.proxies;
  return !!proxy.sys && !! proxy.sys[sinfo.serverType];
}
234113
function createProxyHandler (proxies, urlRoot) {
  if (!proxies.length) {
    const nullProxy = (request, response, next) => next()
    nullProxy.upgrade = () => {}
    return nullProxy
  }

  function createProxy (request, response, next) {
    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`proxying request - ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.web(request, response)
    } else {
      return next()
    }
  }

  createProxy.upgrade = function (request, socket, head) {
    // special-case karma's route to avoid upgrading it
    if (request.url.startsWith(urlRoot)) {
      log.debug(`NOT upgrading proxyWebSocketRequest ${request.url}`)
      return
    }

    const proxyRecord = proxies.find((p) => request.url.startsWith(p.path))
    if (proxyRecord) {
      log.debug(`upgrade proxyWebSocketRequest ${request.url} to ${proxyRecord.host}:${proxyRecord.port}`)
      request.url = request.url.replace(proxyRecord.path, proxyRecord.baseUrl)
      proxyRecord.proxy.ws(request, socket, head)
    }
  }

  return createProxy
}
389932
function proxyOptsFromStr(str) {
    if (!str) {
        return (false);
    }

    var s = str;

    // Normalize: host:port -> http://host:port
    // FWIW `curl` supports using "http_proxy=host:port".
    if (!/^[a-z0-9]+:\/\//.test(s)) {
        s = 'http://' + s;
    }
    var parsed = url.parse(s);

    var proxyOpts = {
        protocol: parsed.protocol,
        host: parsed.hostname
    };

    if (parsed.port) {
        proxyOpts.port = Number(parsed.port);
    }

    if (parsed.auth) {
        proxyOpts.proxyAuth = parsed.auth;
    }

    return (proxyOpts);
}
794600
function WS(opts) {
	  var forceBase64 = opts && opts.forceBase64;
	  if (forceBase64) {
	    this.supportsBinary = false;
	  }
	  this.perMessageDeflate = opts.perMessageDeflate;
	  this.usingBrowserWebSocket = BrowserWebSocket && !opts.forceNode;
	  this.protocols = opts.protocols;
	  if (!this.usingBrowserWebSocket) {
	    WebSocket = NodeWebSocket;
	  }
	  Transport.call(this, opts);
	}
1215672
public void setWebServerScripting(
        String webserverscript,
        String targetpath,
        String configtemplate,
        String securetemplate,
        String filenameprefix,
        String loggingdir) {

        m_apacheConfig = new HashMap<String, String>();
        m_apacheConfig.put(WEB_SERVER_CONFIG_WEBSERVERSCRIPT, webserverscript);
        m_apacheConfig.put(WEB_SERVER_CONFIG_TARGETPATH, targetpath);
        m_apacheConfig.put(WEB_SERVER_CONFIG_CONFIGTEMPLATE, configtemplate);
        m_apacheConfig.put(WEB_SERVER_CONFIG_SECURETEMPLATE, securetemplate);
        m_apacheConfig.put(WEB_SERVER_CONFIG_FILENAMEPREFIX, filenameprefix);
        m_apacheConfig.put(WEB_SERVER_CONFIG_LOGGINGDIR, loggingdir);
    }
1175897
private static InetSocketAddress overrideProxy(String proxyHostPort) {
    if (proxyHostPort == null) {
      return null;
    }

    String[] parts = proxyHostPort.split(":", 2);
    int port = 80;
    if (parts.length > 1) {
      port = Integer.parseInt(parts[1]);
    }
    log.warning(
        "Detected GRPC_PROXY_EXP and will honor it, but this feature will "
            + "be removed in a future release. Use the JVM flags "
            + "\"-Dhttps.proxyHost=HOST -Dhttps.proxyPort=PORT\" to set the https proxy for "
            + "this JVM.");
    return new InetSocketAddress(parts[0], port);
  }
1297695
function ProxyGuest ( options ) {
	// prepare
	var name;

	// connection with server
	this.active = false;

	/**
	 * proxy instance configuration
	 * @namespace
	 */
	this.config = {
		// node.js server address
		host: '127.0.0.1',

		// http server port
		port: 8800,

		// session name
		name: 'anonymous',

		// cached url for posting requests
		urlPost: '',

		// cached url for info collecting
		urlInfo: ''
	};

	// single ajax object for performance
	this.xhr = new XMLHttpRequest();

	// validate and iterate input
	if ( options && typeof options === 'object' ) {
		for ( name in options ) {
			// rewrite defaults
			if ( options.hasOwnProperty(name) ) {
				this.config[name] = options[name];
			}
		}
	}

	// there may be some special chars
	name = encodeURIComponent(this.config.name);

	// cache final request urls
	this.config.urlPost = 'http://' + this.config.host + ':' + this.config.port + '/' + name;
	this.config.urlInfo = 'http://' + this.config.host + ':' + this.config.port + '/info/' + name;

	// check initial connection status
	this.active = this.info().active;

	console.log('%c[core]\t%c%s\t%c0\t%cconnection to the host %c(%s:%s): %c%s',
		'color:grey',
		'color:purple', this.config.name,
		'color:grey',
		'color:black',
		'color:grey', this.config.host, this.config.port,
		'color:' + (this.active ? 'green' : 'red'), this.active ? 'available' : 'not available'
	);
}
1323725
private void configureProxyServer(ChannelPipeline clientPipeline) {
        if (proxyServerConfiguration != null && sslConfig != null) {
            if (proxyServerConfiguration.getProxyUsername() != null
                    && proxyServerConfiguration.getProxyPassword() != null) {
                clientPipeline.addLast(Constants.PROXY_HANDLER,
                        new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress(),
                                proxyServerConfiguration.getProxyUsername(),
                                proxyServerConfiguration.getProxyPassword()));
            } else {
                clientPipeline.addLast(Constants.PROXY_HANDLER,
                        new HttpProxyHandler(proxyServerConfiguration.getInetSocketAddress()));
            }
        }
    }
1228017
private String fetchStats(InetSocketAddress jn) throws IOException {
    try {
      return DFSUtil.getHTMLContentWithTimeout(new URI("http", null, jn.getAddress().getHostAddress(), jn
          .getPort(), "/journalStats", null, null).toURL(), HTTP_CONNECT_TIMEOUT, HTTP_READ_TIMEOUT);
    } catch (Exception e) {
      LOG.error("Problem connecting to " + getHostAddress(jn), e);
      return null;
    }
  }
495065
function startBrowserSync(serverRoot) {

    console.log('Starting BrowserSync on port ' + 8010 + ' for ' + serverRoot);

    var options = {
        //proxy: 'localhost:' + port,
        port: 8010,
        ws: true,
        server: {
            baseDir: serverRoot
        },
        reloadDelay: 2000
    };

    browserSync.init(options);

}
458358
function (testOverride) {
    var ret = '127.0.0.1'
    os = testOverride || os
    var interfaces = os.networkInterfaces()

    Object.keys(interfaces).forEach(function (el) {
      interfaces[el].forEach(function (el2) {
        if (!el2.internal && el2.family === 'IPv4') {
          ret = el2.address
        }
      })
    })

    return ret
  }
1007136
function getProxyMiddleware(context, uri) {
  const pathRewrite = {};
  pathRewrite[`^${context}`] = url.parse(uri).pathname;

  return proxy({
    target: getHost(uri),
    changeOrigin: true,
    logLevel: 'warn',
    pathRewrite: pathRewrite,
  });
}
174688
function sub (subURI, callback) {
  var PING_TIMEOUT = process.env['PING_TIMEOUT']

  if (!subURI) {
    callback(new Error('uri is required'))
    return
  }
  var domain = subURI.split('/')[2]
  var wss = 'wss://' + domain + '/'

  var Socket = new ws(wss, {
    origin: 'http://websocket.org'
  })

  Socket.on('open', function open () {
    debug('connected')
    Socket.send('sub ' + subURI)

    if (PING_TIMEOUT && parseInt(PING_TIMEOUT) && parseInt(PING_TIMEOUT) > 0 ) {
      setInterval(function() {
        debug('sending ping')
        Socket.send('ping')
      }, parseInt(PING_TIMEOUT * 1000))
    }

  })

  Socket.on('close', function close () {
    debug('disconnected')
  })

  Socket.on('message', function message (data, flags) {
    debug(data)
    callback(null, data)
  })
}
324099
function runInspectorProxy(port: number) {
  const inspectorProxy = new InspectorProxy();
  const app = require('connect')();
  app.use(inspectorProxy.processRequest.bind(inspectorProxy));

  const httpServer = require('http').createServer(app);
  httpServer.listen(port, '127.0.0.1', () => {
    inspectorProxy.addWebSocketListener(httpServer);
  });
}
513745
function swsReqResStats(apdex_threshold) {
    this.requests=0;                // Total number of requests received
    this.responses=0;               // Total number of responses sent
    this.errors=0;                  // Total number of error responses
    this.info=0;                    // Total number of informational responses
    this.success=0;                 // Total number of success responses
    this.redirect=0;                // Total number of redirection responses
    this.client_error=0;            // Total number of client error responses
    this.server_error=0;            // Total number of server error responses
    this.total_time=0;              // Sum of total processing time (from request received to response finished)
    this.max_time=0;                // Maximum observed processed time
    this.avg_time=0;                // Average processing time
    this.total_req_clength=0;       // Total (Sum) of Content Lengths of received requests
    this.max_req_clength=0;         // Maximum observed Content length in received requests
    this.avg_req_clength=0;         // Average Content Length in received requests
    this.total_res_clength=0;       // Total (Sum) of Content Lengths of sent responses
    this.max_res_clength=0;         // Maximum observed Content Length in sent responses
    this.avg_res_clength=0;         // Average Content Length in sent responses
    this.req_rate=0;                // Request Rate
    this.err_rate=0;                // Error Rate
    this.apdex_threshold = typeof apdex_threshold !== 'undefined' ? apdex_threshold : 50;   // Apdex threshold
    this.apdex_satisfied = 0;       // Total number of "satisfied" responses for Apdex: time <= apdex_threshold
    this.apdex_tolerated = 0;       // Total number of "tolerated" responses for Apdex: time <= (apdex_threshold*4)
    this.apdex_score = 0;           // Apdex score: (apdex_satisfied + (apdex_tolerated/2))/responses
    // TODO Consider: counts by exact response code
}
1275999
private void findDefaultProxy() {
        ProxySearch proxySearch = new ProxySearch();
        proxySearch.addStrategy(ProxySearch.Strategy.JAVA);
        proxySearch.addStrategy(ProxySearch.Strategy.ENV_VAR);
        proxySearch.addStrategy(ProxySearch.Strategy.OS_DEFAULT);
        proxySearch.addStrategy(ProxySearch.Strategy.BROWSER);
        ProxySelector proxySelector = proxySearch.getProxySelector();

        if (proxySelector != null) {
            ProxySelector.setDefault(proxySelector);
            try {
                List<Proxy> proxyList = proxySelector.select(new URI(serviceUrl));
                if (proxyList != null && !proxyList.isEmpty()) {
                    for (Proxy proxy : proxyList) {
                        InetSocketAddress address = (InetSocketAddress) proxy.address();
                        if (address != null) {
                            String host = address.getHostName();
                            int port = address.getPort();
                            String username = System.getProperty(HTTP_PROXY_USER);
                            String password = System.getProperty(HTTP_PROXY_PASSWORD);
                            setProxy(host, port, username, password);
                        }
                    }
                }
            } catch (URISyntaxException e) {
                logger.error("Bad service url: " + serviceUrl, e);
            }
        }
    }