/*
(non-Javadoc)

@see javax.websocket.WebSocketContainer#connectToServer(javax.websocket.Endpoint, javax.websocket.ClientEndpointConfig, java.net.URI)
778607
@Override
    public Session connectToServer(Endpoint endpoint, ClientEndpointConfig endpointConfig, URI path) throws DeploymentException, IOException {

        if (endpoint == null || path == null) {
            throw new IllegalArgumentException();
        }
        ClientConnector x = new ClientConnector();
        return x.connectClass(endpoint, path, endpointConfig, this);
    }
589157
public static URI toUri(String endpoint, ClientConfiguration config) {

        if (config == null) {
            throw new IllegalArgumentException("ClientConfiguration cannot be null");
        }
        return toUri(endpoint, config.getProtocol());
    }
221653
public void setServiceEndPointUrl(String url) {
		ServiceDefTarget endpoint = (ServiceDefTarget) service;
		endpoint.setServiceEntryPoint(url);
	}
95513
public static CompletableFuture<EndpointDescription[]> getEndpoints(String endpointUrl) {
        UaTcpStackClientConfig config = UaTcpStackClientConfig.builder()
                .setEndpointUrl(endpointUrl)
                .build();

        UaTcpStackClient client = new UaTcpStackClient(config);

        GetEndpointsRequest request = new GetEndpointsRequest(
                new RequestHeader(null, DateTime.now(), uint(1), uint(0), null, uint(5000), null),
                endpointUrl, null, new String[]{Stack.UA_TCP_BINARY_TRANSPORT_URI});

        return client.<GetEndpointsResponse>sendRequest(request)
                .whenComplete((r, ex) -> client.disconnect())
                .thenApply(GetEndpointsResponse::getEndpoints);
    }
1081161
public static Endpoint determineEndpointForRequest(final RequestAbstractType authnRequest,
                                                       final SamlRegisteredServiceServiceProviderMetadataFacade adaptor,
                                                       final String binding) {
        var endpoint = (Endpoint) null;
        if (authnRequest instanceof LogoutRequest) {
            endpoint = adaptor.getSingleLogoutService(binding);
        } else {
            val endpointReq = getAssertionConsumerServiceFromRequest(authnRequest, binding);
            endpoint = endpointReq == null
                ? adaptor.getAssertionConsumerService(binding)
                : endpointReq;
        }

        if (endpoint == null || StringUtils.isBlank(endpoint.getBinding())) {
            throw new SamlException("Assertion consumer service does not define a binding");
        }
        val location = StringUtils.isBlank(endpoint.getResponseLocation()) ? endpoint.getLocation() : endpoint.getResponseLocation();
        if (StringUtils.isBlank(location)) {
            throw new SamlException("Assertion consumer service does not define a target location");
        }
        return endpoint;
    }
813733
public ProviderAuthenticationResult handleRedirectToServer(HttpServletRequest req, HttpServletResponse res, ConvergedClientConfig clientConfig) {
        String authorizationEndpoint = clientConfig.getAuthorizationEndpointUrl();

        if (!checkHttpsRequirement(clientConfig, authorizationEndpoint)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", authorizationEndpoint);
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        if (clientConfig.createSession()) {
            try {
                req.getSession(true);
            } catch (Exception e) {
                // ignore it. Session exists
            }
        }

        String strRandom = OidcUtil.generateRandom(OidcUtil.RANDOM_LENGTH);
        String timestamp = OidcUtil.getTimeStamp();
        String state = timestamp + strRandom;
        if (!req.getMethod().equalsIgnoreCase("GET") && req.getParameter("oidc_client") != null) {
            state = state + req.getParameter("oidc_client");
        }
        String cookieValue = HashUtils.createStateCookieValue(clientConfig, state);
        String cookieName = ClientConstants.WAS_OIDC_STATE_KEY + HashUtils.getStrHashCode(state);
        boolean isHttpsRequest = req.getScheme().toLowerCase().contains("https");
        int cookieLifeTime = (int) clientConfig.getAuthenticationTimeLimitInSeconds();
        Cookie cookie = OidcClientUtil.createCookie(cookieName, cookieValue, cookieLifeTime, req);
        if (clientConfig.isHttpsRequired() == true && isHttpsRequest) {
            cookie.setSecure(true);
        }
        res.addCookie(cookie);

        String redirect_url = setRedirectUrlIfNotDefined(req, clientConfig);
        if (!checkHttpsRequirement(clientConfig, redirect_url)) {
            Tr.error(tc, "OIDC_CLIENT_URL_PROTOCOL_NOT_HTTPS", redirect_url);
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        }

        String acr_values = req.getParameter("acr_values");

        String authzEndPointUrlWithQuery = null;
        try {
            boolean openidScopeMissing = !clientConfig.isSocial() && !isOpenIDScopeSpecified(clientConfig); // some social media use nonstandard scope
            boolean scopeMissing = clientConfig.getScope() == null || clientConfig.getScope().length() == 0;
            if (openidScopeMissing || scopeMissing) {
                Tr.error(tc, "OIDC_CLIENT_REQUEST_MISSING_OPENID_SCOPE",
                        clientConfig.getClientId(), clientConfig.getScope()); // CWWKS1713E
                return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
            }

            authzEndPointUrlWithQuery = buildAuthorizationUrlWithQuery(req, (OidcClientRequest) req.getAttribute(ClientConstants.ATTRIB_OIDC_CLIENT_REQUEST), state, clientConfig, redirect_url, acr_values);

            // preserve post param.
            WebAppSecurityConfig webAppSecConfig = WebAppSecurityCollaboratorImpl.getGlobalWebAppSecurityConfig();
            PostParameterHelper pph = new PostParameterHelper(webAppSecConfig);
            pph.save(req, res);
            // Redirect to OP
            // If clientSideRedirect is true (default is true) then do the
            // redirect.  If the user agent doesn't support javascript then config can set this to false.
            if (clientConfig.isClientSideRedirect()) {
                String domain = OidcClientUtil.getSsoDomain(req);
                doClientSideRedirect(res, authzEndPointUrlWithQuery, state, domain);
            } else {
                String urlCookieName = ClientConstants.WAS_REQ_URL_OIDC + HashUtils.getStrHashCode(state);
                Cookie c = OidcClientUtil.createCookie(urlCookieName, getReqURL(req), cookieLifeTime, req);
                if (clientConfig.isHttpsRequired() == true && isHttpsRequest) {
                    cookie.setSecure(true);
                }
                res.addCookie(c);
            }

        } catch (UnsupportedEncodingException e) {
            Tr.error(tc, "OIDC_CLIENT_AUTHORIZE_ERR", new Object[] { clientConfig.getClientId(), e.getLocalizedMessage(), ClientConstants.CHARSET });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);
        } catch (IOException ioe) {
            Tr.error(tc, "OIDC_CLIENT_AUTHORIZE_ERR", new Object[] { clientConfig.getClientId(), ioe.getLocalizedMessage(), ClientConstants.CHARSET });
            return new ProviderAuthenticationResult(AuthResult.SEND_401, HttpServletResponse.SC_UNAUTHORIZED);

        }

        return new ProviderAuthenticationResult(AuthResult.REDIRECT_TO_PROVIDER, HttpServletResponse.SC_OK, null, null, null, authzEndPointUrlWithQuery);
    }
1297863
@Override
    public Session connectToServer(Object clazz, URI path) throws DeploymentException, IOException {

        if (clazz == null || path == null) {
            throw new IllegalArgumentException();
        }
        ClientConnector x = new ClientConnector();
        return x.connectAnnotatedClass(clazz, path, this);
    }
362146
public void connect() throws IOException, DeploymentException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        container.connectToServer(this, wssUri);
        log.debug("client connected to the server: {}", wssUri);
    }
635326
public CompletableFuture<ClientConnection> connectAsync(URI uri) {
        return this.connectAsync(null, uri, com.networknt.client.Http2Client.WORKER, com.networknt.client.Http2Client.SSL, com.networknt.client.Http2Client.BUFFER_POOL,
                OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
    }
639150
private HttpURLConnection getConnectionOnce(String uri, String postJson, String token) throws IOException {

		URL url = new URL(uri);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();

		if (timeout > 0) {
			conn.setReadTimeout(timeout);
			conn.setConnectTimeout(timeout);
		}

		if (postJson != null && postJson.equals("{}"))
			postJson = null;

		if (postJson != null) {
			conn.setDoOutput(true); // Triggers POST.
		}
		conn.setRequestProperty("Content-Type", "application/json; charset=" + UTF8.name());
		conn.setRequestProperty("User-Agent", "WePay Java SDK");

		if (token != null) {
			conn.setRequestProperty("Authorization", "Bearer " + token);
		}

		if (postJson != null) {
			OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), UTF8);
			writer.write(postJson);
			writer.close();
		}

		return conn;
	}
923178
private CitrusWebSocketHandler getWebSocketClientHandler(String url) {
        CitrusWebSocketHandler handler = new CitrusWebSocketHandler();

        if (webSocketHttpHeaders == null) {
            webSocketHttpHeaders = new WebSocketHttpHeaders();
            webSocketHttpHeaders.setSecWebSocketExtensions(Collections.singletonList(new StandardToWebSocketExtensionAdapter(new JsrExtension(new PerMessageDeflateExtension().getName()))));
        }

        ListenableFuture<WebSocketSession> future = client.doHandshake(handler, webSocketHttpHeaders, UriComponentsBuilder.fromUriString(url).buildAndExpand().encode().toUri());
        try {
            future.get();
        } catch (Exception e) {
            String errMsg = String.format("Failed to connect to Web Socket server - '%s'", url);
            LOG.error(errMsg);
            throw new CitrusRuntimeException(errMsg);
        }
        return handler;
    }
578529
public static HttpServer startServer(URI listenerURI, SSLContextConfigurator sslContextConfigurator) throws IOException {
    
    String scheme = listenerURI.getScheme();
    
    if (scheme.equals("http"))
      return startUnsecureServer(listenerURI);
    else
      return startSecureServer(listenerURI, sslContextConfigurator); 
    
  }
903596
void connect(SocketAddress socketAddress, boolean useSSL) {
        ChannelFactory channelFactory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(),
            Executors.newCachedThreadPool());

        ChannelPipeline clientPipeline = NettyChannelPipeline.newPipeline(connection);
        SslHandler sslHandler = null;

        if (useSSL) {
            sslHandler = getClientSSLHandler();
            clientPipeline.addFirst("ssl", sslHandler);
        }

        bootstrap = new ClientBootstrap(channelFactory);
        bootstrap.setOption("tcpNoDelay", true);
        bootstrap.setPipeline(clientPipeline);

        /*
         * The connection future and the connection itself aren't perfectly
         * synchronized so we have to wait for both to acknowledge that the
         * connection has been made
         */
        final CountDownLatch connectedLatch = new CountDownLatch(1);
        ConnectionStateListener connectedListener = new ConnectionStateListener() {
            @Override
            public void onConnectionConnected() {
                connectedLatch.countDown();
            }

            @Override
            public void onConnectionClosing() {
            }

            @Override
            public void onConnectionClosed() {
            }
        };

        connection.addConnectionStateListener(connectedListener);

        try {
            /* Perform connection */
            ChannelFuture future = bootstrap.connect(socketAddress);

            log.debug("connecting");

            future.await();

            if (future.isSuccess()) {
                /* This await should be very brief */
                connectedLatch.await();

                log.debug("connected successfully");

                if (useSSL) {
                    doSSLHandshake(sslHandler);
                }

                connected = true;
            } else {
                log.debug("connection failed");
                throw new ConnectionException(future.getCause());
            }
        } catch (InterruptedException e) {
            throw new ConnectionException("Interrupted while connecting");
        } finally {
            connection.removeConnectionStateListener(connectedListener);
        }
    }
874187
private void setConnectTimeout(HttpURLConnection connection) {
        try {
            Map<String, String> endpointProperties = this.api.getEndpointProperties();
            if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$
                int connectTimeoutMs = new Integer(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$
                connection.setConnectTimeout(connectTimeoutMs);
            }
        } catch (Throwable t) {
        }
    }
45813
function Client(endpointUrl, sourceId) {
		this.restClient = new restClient.Client();

		this.endpointUrl = endpointUrl;

		if (this.endpointUrl) {
			// Remove the trailing slash if necessary
			if (this.endpointUrl.indexOf('/', this.endpointUrl.length - 1) !== -1) {
				this.endpointUrl = this.endpointUrl.substr(0, this.endpointUrl.length - 2);
			}

			// Add the default version if not present
			// TODO: The client should take care of the version in a better way
			if (this.endpointUrl.indexOf('/v1', this.endpointUrl.length - 3) === -1) {
				this.endpointUrl = this.endpointUrl + '/v1';
			}
		}

		if (sourceId !== undefined) {
			this.sourceId = sourceId;
		}
	}
206040
@Override
	public WebsocketSender uri(String uri) {
		return new WebsocketFinalizer(cachedConfiguration.bootstrap(b -> HttpClientConfiguration.uri(b, uri)));
	}
1190477
public void registerEndpoint(RegisterEndpointRequest arg0) {
        String endpointURL = arg0.getEndpointURL();
        QName serviceName = QName.valueOf(arg0.getServiceName());
        if (LOG.isLoggable(Level.FINE)) {
            LOG.fine("Registering endpoint " + endpointURL + " for service "
                    + serviceName + "...");
        }
        try {
            initLocator();
            BindingType bindingType = arg0.getBinding() == null ? BindingType.OTHER : BindingType
                    .valueOf(arg0.getBinding().value());
            TransportType transportType = arg0.getTransport() == null ? TransportType.OTHER
                    : TransportType.valueOf(arg0.getTransport().value());
            SLPropertiesImpl slProps = null;
            if (!arg0.getEntryType().isEmpty()) {
                slProps = new SLPropertiesImpl();
                List<EntryType> entries = arg0.getEntryType();
                for (EntryType entry : entries) {
                    slProps.addProperty(entry.getKey(), entry.getValue());
                }
            }
            Endpoint simpleEndpoint =
                new SimpleEndpoint(serviceName, endpointURL, bindingType, transportType, slProps);
            locatorClient.register(simpleEndpoint, true);
        } catch (ServiceLocatorException e) {
            // throw new ServiceLocatorFault(e.getMessage(), e);
            throw new WebApplicationException(Response
                    .status(Status.INTERNAL_SERVER_ERROR)
                    .entity(e.getMessage()).build());
        } catch (InterruptedException e) {
            // throw new InterruptedExceptionFault(e.getMessage(), e);
            throw new WebApplicationException(Response
                    .status(Status.INTERNAL_SERVER_ERROR)
                    .entity(e.getMessage()).build());
        }
    }