In a cold start ME Environment, the proxy handler needs to be created.
971405
private void createProxyHandler() throws MessageStoreException {
        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.entry(tc, "createProxyHandler");

        _multiMEProxyHandler = new MultiMEProxyHandler(this, _txManager);
        _persistentStore.addItemStream(_multiMEProxyHandler, _txManager
                        .createAutoCommitTransaction());

        if (TraceComponent.isAnyTracingEnabled()
            && tc.isEntryEnabled())
            SibTr.exit(tc, "createProxyHandler");
    }
1320666
def start(self):
        '''
        
        '''
        super(ProxyMinion, self).start()
        try:
            if check_user(self.config['user']):
                self.action_log_info('The Proxy Minion is starting up')
                self.verify_hash_type()
                self.minion.tune_in()
                if self.minion.restart:
                    raise SaltClientError('Proxy Minion could not connect to Master')
        except (KeyboardInterrupt, SaltSystemExit) as exc:
            self.action_log_info('Proxy Minion Stopping')
            if isinstance(exc, KeyboardInterrupt):
                log.warning('Exiting on Ctrl-c')
                self.shutdown()
            else:
                log.error(exc)
                self.shutdown(exc.code)
1032031
private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) {
        String host = System.getProperty(hostKey);
        if (host == null || host.isEmpty()) {
            return null;
        }

        int port = getSystemPropertyInt(portKey, defaultPort);
        return new Proxy(type, InetSocketAddress.createUnresolved(host, port));
    }
853024
def subscribe(self, handler, topic=None, options=None):
        
        def proxy_handler(*args, **kwargs):
            return self._callbacks_runner.put(partial(handler, *args, **kwargs))
        return self._async_session.subscribe(proxy_handler, topic=topic, options=options)
1276319
function initApiProxy() {
  if (build.verbose)
    console.log('Proxying paths...');
  lodash.forEach(build.proxyMap, function (proxyOpts, urlPath) {
    if (build.verbose)
      console.log('  - url: "' + urlPath + '"');
    app.use(urlPath, proxy(proxyOpts));
    // e.g. `app.use('/api', proxy({target: "http://localhost:4321/api", 
    // changeOrigin: true});`
  });
}
110793
function applyProxy(options, cb) {
  npmconf.load({}, function (er, conf) {
    var proxyUrl;

    if (!er) {
      proxyUrl = conf.get('https-proxy') ||
                 conf.get('proxy') ||
                 conf.get('http-proxy');
    }

    var env = process.env;

    options.proxy = proxyUrl ||
                    env.HTTPS_PROXY ||
                    env.https_proxy ||
                    env.HTTP_PROXY ||
                    env.http_proxy;

    cb(options);
  });
}
1083429
function proxyError(err) {
    errState = true;

    //
    // Emit an `error` event, allowing the application to use custom
    // error handling. The error handler should end the response.
    //
    if (self.emit('proxyError', err, req, res)) {
      return;
    }

    res.writeHead(500, { 'Content-Type': 'text/plain' });

    if (req.method !== 'HEAD') {
      //
      // This NODE_ENV=production behavior is mimics Express and
      // Connect.
      //
      if (process.env.NODE_ENV === 'production') {
        res.write('Internal Server Error');
      }
      else {
        res.write('An error has occurred: ' + JSON.stringify(err));
      }
    }

    try { res.end() }
    catch (ex) { console.error("res.end error: %s", ex.message) }
  }
339599
def _create_proxy(proxy_setting):
        """"""
        proxy = QNetworkProxy()
        proxy_scheme = proxy_setting['scheme']
        proxy_host = proxy_setting['host']
        proxy_port = proxy_setting['port']
        proxy_username = proxy_setting['username']
        proxy_password = proxy_setting['password']
        proxy_scheme_host = '{0}://{1}'.format(proxy_scheme, proxy_host)
        proxy.setType(QNetworkProxy.HttpProxy)

        if proxy_scheme_host:
            # proxy.setHostName(proxy_scheme_host)  # does not work with scheme
            proxy.setHostName(proxy_host)

        if proxy_port:
            proxy.setPort(proxy_port)

        if proxy_username:
            proxy.setUser(proxy_username)

        if proxy_password:
            proxy.setPassword(proxy_password)

        return proxy
242200
private Management getProxyChain(Management m)
            throws ModuleInitializationException {
        try {
            invocationHandlers = getInvocationHandlers();
            return (Management) ProxyFactory.getProxy(m, invocationHandlers);
        } catch (Exception e) {
            throw new ModuleInitializationException(e.getMessage(), getRole());
        }
    }
216522
public void start()	{
		if(logger.isDebugEnabled()) {
			logger.debug("start");
		}
		
		if(started) {
			throw new IllegalStateException("Proxy branch alredy started!");
		}
		if(canceled) {
			throw new IllegalStateException("Proxy branch was cancelled, you must create a new branch!");
		}
		if(timedOut) {
			throw new IllegalStateException("Proxy brnach has timed out!");
		}
		if(proxy.getAckReceived()) {
			throw new IllegalStateException("An ACK request has been received on this proxy. Can not start new branches.");
		}
		
		// Initialize these here for efficiency.
		if(logger.isDebugEnabled()) {
			logger.debug("start - calling updateTimer");
		}
		updateTimer(false, originalRequest.getSipApplicationSession(false));		
		
		SipURI recordRoute = null;
		
		// If the proxy is not adding record-route header, set it to null and it
		// will be ignored in the Proxying
		if(proxy.getRecordRoute() || this.getRecordRoute()) {
			if(recordRouteURI == null && recordRouteURIString == null) {
				recordRouteURIString = DEFAULT_RECORD_ROUTE_URI;
			}
			if(recordRouteURIString != null) {
				try {
					recordRouteURI = ((SipURI)proxy.getSipFactoryImpl().createURI(recordRouteURIString));
				} catch (ServletParseException e) {
					logger.error("A problem occured while setting the target URI while proxying a request " + recordRouteURIString, e);
				}
			}
			recordRoute = recordRouteURI;
		}
		addTransaction(originalRequest);

		URI destination = null;
                //app may have modified the branch request, so give it priority
                //fixes https://github.com/RestComm/sip-servlets/issues/131
                if (outgoingRequest.getRequestURI().equals(this.getProxy().getOriginalRequest().getRequestURI()))
                {
                    if(targetURI != null) {
                            try {
                                    destination = proxy.getSipFactoryImpl().createURI(targetURI);
                            } catch (ServletParseException e) {
                                    logger.error("A problem occured while setting the target URI while proxying a request " + targetURI, e);
                            }
                    }                    
                } else {
                    //the app has mofified the requestURI after branch creation..
                     destination = outgoingRequest.getRequestURI();
                }
		Request cloned = ProxyUtils.createProxiedRequest(
				outgoingRequest,
				this,
				destination,
				this.outboundInterface,
				recordRoute, 
				this.pathURI);
		//tells the application dispatcher to stop routing the original request
		//since it has been proxied
		originalRequest.setRoutingState(RoutingState.PROXIED);
		
		if(logger.isDebugEnabled()) {
			logger.debug("Proxy Branch 1xx Timeout set to " + proxyBranch1xxTimeout);
		}
		if(proxyBranch1xxTimeout > 0) {
			proxy1xxTimeoutTask = new ProxyBranchTimerTask(this, ResponseType.INFORMATIONAL, originalRequest.getSipApplicationSession(false));				
			proxy.getProxyTimerService().schedule(proxy1xxTimeoutTask, proxyBranch1xxTimeout * 1000L);
			proxyBranch1xxTimerStarted = true;
		}
		
		started = true;
		forwardRequest(cloned, false);		
	}
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
}
230280
def init(opts):
    '''
    
    '''
    proxy_dict = opts.get('proxy', {})
    opts['multiprocessing'] = proxy_dict.get('multiprocessing', False)
    netmiko_connection_args = proxy_dict.copy()
    netmiko_connection_args.pop('proxytype', None)
    netmiko_device['always_alive'] = netmiko_connection_args.pop('always_alive',
                                                                 opts.get('proxy_always_alive', True))
    try:
        connection = ConnectHandler(**netmiko_connection_args)
        netmiko_device['connection'] = connection
        netmiko_device['initialized'] = True
        netmiko_device['args'] = netmiko_connection_args
        netmiko_device['up'] = True
        if not netmiko_device['always_alive']:
            netmiko_device['connection'].disconnect()
    except NetMikoTimeoutException as t_err:
        log.error('Unable to setup the netmiko connection', exc_info=True)
    except NetMikoAuthenticationException as au_err:
        log.error('Unable to setup the netmiko connection', exc_info=True)
    return True
536494
public final ProxyHandler newProxyHandler() {
		InetSocketAddress proxyAddr = this.address.get();
		String username = this.username;
		String password = Objects.nonNull(username) && Objects.nonNull(this.password) ?
				this.password.apply(username) : null;

		switch (this.type) {
			case HTTP:
				return Objects.nonNull(username) && Objects.nonNull(password) ?
						new HttpProxyHandler(proxyAddr, username, password, this.httpHeaders.get()) :
						new HttpProxyHandler(proxyAddr, this.httpHeaders.get());
			case SOCKS4:
				return Objects.nonNull(username) ? new Socks4ProxyHandler(proxyAddr, username) :
						new Socks4ProxyHandler(proxyAddr);
			case SOCKS5:
				return Objects.nonNull(username) && Objects.nonNull(password) ?
						new Socks5ProxyHandler(proxyAddr, username, password) :
						new Socks5ProxyHandler(proxyAddr);
		}
		throw new IllegalArgumentException("Proxy type unsupported : " + this.type);
	}
207172
protected void registerForPostCommit(MultiMEProxyHandler proxyHandler,
                                       DestinationHandler destination, 
                                       PubSubOutputHandler handler,
                                       Neighbour neighbour)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "registerForPostCommit", 
        new Object[] { proxyHandler, destination, handler, neighbour });

    _proxyHandler = proxyHandler;
    _destination = destination;
    _handler = handler;
    _neighbour = neighbour;
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "registerForPostCommit");
  }
229685
synchronized void freeze() {
        if (frozen) {
            return;
        }
        if (userAgent == null) {
            setDefaultUserAgent();
        }
        serviceMap = new HashMap<String, ServiceEndpoint>();
        if (log.isDebugEnabled()) {
            StringBuilder buf = new StringBuilder();
            buf.append("Creating MwsConnection {");
            buf.append("applicationName:");
            buf.append(applicationName);
            buf.append(",applicationVersion:");
            buf.append(applicationVersion);
            buf.append(",awsAccessKeyId:");
            buf.append(awsAccessKeyId);
            buf.append(",uri:");
            buf.append(endpoint.toString());
            buf.append(",userAgent:");
            buf.append(userAgent);
            buf.append(",connectionTimeout:");
            buf.append(connectionTimeout);
            if (proxyHost != null && proxyPort != 0) {
                buf.append(",proxyUsername:");
                buf.append(proxyUsername);
                buf.append(",proxyHost:");
                buf.append(proxyHost);
                buf.append(",proxyPort:");
                buf.append(proxyPort);
            }
            buf.append("}");
            log.debug(buf);
        }

        BasicHttpParams httpParams = new BasicHttpParams();
        httpParams.setParameter(CoreProtocolPNames.USER_AGENT, userAgent);
        HttpConnectionParams
                .setConnectionTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, socketTimeout);
        HttpConnectionParams.setStaleCheckingEnabled(httpParams, true);
        HttpConnectionParams.setTcpNoDelay(httpParams, true);

        connectionManager = getConnectionManager();
        httpClient = new DefaultHttpClient(connectionManager, httpParams);
        httpContext = new BasicHttpContext();
        if (proxyHost != null && proxyPort != 0) {
            String scheme = MwsUtl.usesHttps(endpoint) ? "https" : "http";
            HttpHost hostConfiguration = new HttpHost(proxyHost, proxyPort, scheme);
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, hostConfiguration);

            if (proxyUsername != null && proxyPassword != null) {
                Credentials credentials = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
                CredentialsProvider cprovider = new BasicCredentialsProvider();
                cprovider.setCredentials(new AuthScope(proxyHost, proxyPort), credentials);
                httpContext.setAttribute(ClientContext.CREDS_PROVIDER, cprovider);
            }
        }
        headers = Collections.unmodifiableMap(headers);
        frozen = true;
    }
776973
def _make_serverproxy_handler(name, command, environment, timeout, absolute_url, port):
    
    # FIXME: Set 'name' properly
    class _Proxy(SuperviseAndProxyHandler):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.name = name
            self.proxy_base = name
            self.absolute_url = absolute_url
            self.requested_port = port

        @property
        def process_args(self):
            return {
                'port': self.port,
                'base_url': self.base_url,
            }

        def _render_template(self, value):
            args = self.process_args
            if type(value) is str:
                return value.format(**args)
            elif type(value) is list:
                return [self._render_template(v) for v in value]
            elif type(value) is dict:
                return {
                    self._render_template(k): self._render_template(v)
                    for k, v in value.items()
                }
            else:
                raise ValueError('Value of unrecognized type {}'.format(type(value)))

        def get_cmd(self):
            if callable(command):
                return self._render_template(call_with_asked_args(command, self.process_args))
            else:
                return self._render_template(command)

        def get_env(self):
            if callable(environment):
                return self._render_template(call_with_asked_args(environment, self.process_args))
            else:
                return self._render_template(environment)

        def get_timeout(self):
            return timeout

    return _Proxy
167095
private void createProxy(final Class<L> listenerInterface, final ClassLoader classLoader) {
        proxy = listenerInterface.cast(Proxy.newProxyInstance(classLoader,
                new Class[] { listenerInterface }, createInvocationHandler()));
    }