/*
(non-Javadoc)

@see javax.websocket.Endpoint#onOpen(javax.websocket.Session, javax.websocket.EndpointConfig)
516765
@Override
    public void onClose(Session session, CloseReason closeReason) {
        if (onClose != null) {
            Object args[] = new Object[onClose.getMethod().getParameterTypes().length];
            MethodData methodData = onClose.getMethodData();
            //check if method has optional Session parameter
            int sessionIndex = methodData.getSessionIndex();
            if (sessionIndex >= 0) {
                args[sessionIndex] = session;
            }
            //check if method has optional closeReason parameter
            int reasonIndex = methodData.getCloseReasonIndex();
            if (reasonIndex >= 0) {
                args[reasonIndex] = closeReason;
            }
            if (shouldProcessPath) {
                try {
                    //substitute values for @PathParam values for this method.
                    onClose.processPathParameters(this, args);
                } catch (DecodeException e) {
                    /*
                     * JSR 356 @PathParam section
                     * "If the container cannot decode the path segment appropriately to the annotated path parameter, then the container must raise an DecodeException to the error
                     * handling method of the websocket containing the path segment. [WSC-4.3-6]"
                     * Section
                     * 4.
                     * 5:"If the method itself throws an error, the implementation must pass this error to the onError() method of the endpoint together with the session [WSC-4.5-3]"
                     */
                    this.onError(session, e);
                    return;
                }
            }

            try {
                if (appInstance == null) {
                    if (tc.isDebugEnabled()) {
                        Tr.debug(tc, "application instance is null in onClose");
                    }
                    return;
                }

                onClose.getMethod().invoke(appInstance, args);

            } catch (IllegalAccessException e) {
                //JSR 356 Section 4.5:  "If the method itself throws an error, the implementation
                //must pass this error to the onError() method of the endpoint together with the session [WSC-4.5-3]"
                this.onError(session, e);
            } catch (IllegalArgumentException e) {
                this.onError(session, e);
            } catch (InvocationTargetException e) {
                this.onError(session, e);
            }
        } else { //onClose method is not defined, hence log the problem in trace
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "onClose() is called on Endpoint class: " + sepClass + " which does not have onClose method defined");
            }
        }
    }
774092
@Override
    public synchronized void onOpen() {
        super.onOpen();

        if (phoneStateListener == null) {
            Handler mainHandler = new Handler(context.getMainLooper());
            mainHandler.post(new Runnable() {
                @Override
                public void run() {
                    phoneStateListener = new PhoneStateListener() {

                        @Override
                        public void onCellInfoChanged(List<CellInfo> cellInfo) {
                            if (cellInfo != null && !cellInfo.isEmpty()) {
                                onCellsChanged(cellInfo);
                            } else if (supportsCellInfoChanged) {
                                supportsCellInfoChanged = false;
                                onSignalStrengthsChanged(null);
                            }
                        }

                        @Override
                        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
                            if (!supportsCellInfoChanged) {
                                fallbackScan();
                            }
                        }
                    };
                    registerPhoneStateListener();
                }
            });
        } else {
            registerPhoneStateListener();
        }
    }
578749
@Override
  public void onOpen(final WebSocket webSocket, Response response) {
    callback.onConnected();
    this.socket = webSocket;
    if (!this.socket.send(buildStartMessage(this.options))) {
      callback.onError(new IOException("WebSocket unavailable"));
    } else {
      new Thread(TEXT_TO_WEB_SOCKET) {
        @Override
        public void run() {
          sendText();
          if (socketOpen && !socket.send(buildStopMessage())) {
            LOG.log(Level.SEVERE, "Stop message discarded because WebSocket is unavailable");
          }
        }
      };
    }
  }
694649
protected void setSessionValue(final HttpServletRequest request, final String key,
      final Object value) {
    request.getSession(true).setAttribute(key, value);
  }
409553
private void addEndpoint(String addr, Own endpoint, Pipe pipe)
    {
        //  Activate the session. Make it a child of this socket.
        launchChild(endpoint);
        endpoints.insert(addr, new EndpointPipe(endpoint, pipe));
    }
478385
public void onOpen(WebSocketSession session) {
        WsonrpcRemotes.addRemote(session, wsonrpcControl.getConfig());
        fireOpen(session);
    }
1351297
public void connect(URI endpoint) {
        if (endpoint.equals(this.getEndpoint()) && isListening) {
            return;
        }

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(0, TimeUnit.MILLISECONDS)
                .build();
        Request request = new Request.Builder()
                .url(endpoint.toString())
                .build();
        client.newWebSocket(request, this);
        client.dispatcher().executorService().shutdown();

        setEndpoint(endpoint);
    }
48738
protected void registerWebSocketEndpoint(Binding<?> binding) {//}, ServerEndpoint serverEndpoint) {

    Object instance = binding.getProvider().get();
    Class<?> instanceClass = instance.getClass();
    ServerEndpoint serverEndpoint = instanceClass.getAnnotation(ServerEndpoint.class);
    if (serverEndpoint != null) {
      try {
        // register with the servlet container such that the Guice created singleton instance
        // is the instance that is used (and not an instance created per request etc)
        log.debug("registering ServerEndpoint [{}] with servlet container", instanceClass);
        BasicWebSocketConfigurator configurator = new BasicWebSocketConfigurator(instance);
        serverContainer.addEndpoint(new BasicWebSocketEndpointConfig(instanceClass, serverEndpoint, configurator));

      } catch (Exception e) {
        log.error("Error registering WebSocket Singleton " + instance + " with the servlet container", e);
      }
    }
  }
641701
protected void configureEndpointAccess(final HttpSecurity httpSecurity,
                                           final ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry requests,
                                           final ActuatorEndpointProperties.EndpointAccessLevel access,
                                           final ActuatorEndpointProperties properties,
                                           final EndpointRequest.EndpointRequestMatcher endpoint) throws Exception {
        switch (access) {
            case AUTHORITY:
                configureEndpointAccessByAuthority(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case ROLE:
                configureEndpointAccessByRole(requests, properties, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case AUTHENTICATED:
                configureEndpointAccessAuthenticated(requests, endpoint);
                configureEndpointAccessByFormLogin(requests);
                break;
            case IP_ADDRESS:
                configureEndpointAccessByIpAddress(requests, properties, endpoint);
                break;
            case PERMIT:
                configureEndpointAccessPermitAll(requests, endpoint);
                break;
            case ANONYMOUS:
                configureEndpointAccessAnonymously(requests, endpoint);
                break;
            case DENY:
            default:
                configureEndpointAccessToDenyAll(requests, endpoint);
                break;
        }
    }
599383
@Override
    public void alertISOpen() {
        if (TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINE)) {  
            logger.logp(Level.FINE, CLASS_NAME,"alertISOpen()", "");
        }
        if (WCCustomProperties.CHECK_REQUEST_OBJECT_IN_USE){
            checkRequestObjectInUse();
        }
        _srtRequestHelper._InputStreamClosed=false;
        this.releaseInputStream();
        this.releaseReader();
    }
1305637
public void sessionAttributeAccessed(ISession session, Object key, Object value) {
        // ArrayList sessionStateObservers = null;

        /*
         * Check to see if there is a non-empty list of sessionStateObservers.
         */
        if (_sessionStateObservers == null || _sessionStateObservers.size() < 1) {
            return;
        }

        // synchronized(_sessionStateObservers) {
        // _sessionStateObservers = (ArrayList)_sessionStateObservers.clone();
        // }

        ISessionStateObserver sessionStateObserver = null;
        for (int i = 0; i < _sessionStateObservers.size(); i++) {
            sessionStateObserver = (ISessionStateObserver) _sessionStateObservers.get(i);
            sessionStateObserver.sessionAttributeAccessed(session, key, value);
        }

    }
234228
public void openSession(SocketAddress endpoint) {
        synchronized (lock) {
            // Submit a reconnect task for this address if one is not already present
            if (!pendingConnections.containsKey(endpoint)) {
                final ReconnectTask task = new ReconnectTask(endpoint);
                pendingConnections.put(endpoint, task);
                this.reconnectExecutor.submit(task);
            }
        }
    }
514559
function Endpoint(log, role, settings, filters) {
  Duplex.call(this);

  // * Initializing logging infrastructure
  this._log = log.child({ component: 'endpoint', e: this });

  // * First part of the handshake process: sending and receiving the client connection header
  //   prelude.
  assert((role === 'CLIENT') || role === 'SERVER');
  if (role === 'CLIENT') {
    this._writePrelude();
  } else {
    this._readPrelude();
  }

  // * Initialization of component. This includes the second part of the handshake process:
  //   sending the first SETTINGS frame. This is done by the connection class right after
  //   initialization.
  this._initializeDataFlow(role, settings, filters || {});

  // * Initialization of management code.
  this._initializeManagement();

  // * Initializing error handling.
  this._initializeErrorHandling();
}
1056025
private void setAttributesFromApiEndpointProperties(Api api, ApimanHttpConnectorOptions options) {
        try {
            Map<String, String> endpointProperties = api.getEndpointProperties();
            if (endpointProperties.containsKey("timeouts.read")) { //$NON-NLS-1$
                int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.read")); //$NON-NLS-1$
                options.setRequestTimeout(connectTimeoutMs);
            }
            if (endpointProperties.containsKey("timeouts.connect")) { //$NON-NLS-1$
                int connectTimeoutMs = Integer.parseInt(endpointProperties.get("timeouts.connect")); //$NON-NLS-1$
                options.setConnectionTimeout(connectTimeoutMs);
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException(e);
        }
    }
1267049
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
        logger.debug("WebSocket closed: {}, Close Status: {}", session, status.toString());
    }
473093
private static void configureEngine(SSLEngine engine, FlowType type, SSLLinkConfig config, SSLConnectionLink connLink) {
        // Update the engine with the latest config parameters.
        engine.setEnabledCipherSuites(config.getEnabledCipherSuites(engine));

        //Set the configured protocol on the SSLEngine
        String protocol = config.getSSLProtocol();
        if (protocol != null) {
            engine.setEnabledProtocols(new String[] { protocol });
        }

        if (type == FlowType.INBOUND) {
            engine.setUseClientMode(false);
            boolean flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION);
            // When on z/OS, need to check the MutualAuthCBINDCheck property
            // to force client authentication
            //TODO: z/os
            //            if (PlatformHelperFactory.getPlatformHelper().isZOS() &&
            //            	 UserRegistryConfig.TYPE_LOCAL_OS.equals(SecurityObjectLocator.getSecurityConfig().getActiveUserRegistry().getType()))
            //            {
            //            	Boolean cbindCheckEnabled = Boolean.FALSE;
            //
            //            	//get the endpoint name off of the thread
            //                Map connectionInfo = JSSEHelper.getInstance().getInboundConnectionInfo();
            //                if (connectionInfo != null) {
            //                    String endpointName = (String) connectionInfo.get(Constants.CONNECTION_INFO_ENDPOINT_NAME);
            //                    //only enforce cbind check on web requests
            //                    if (endpointName != null && endpointName.startsWith("HTTP")) {
            //                    	if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //                            Tr.debug(tc, "The endpoint, " + endpointName + ", is web and we are on z/OS. Proceeding to get the mutualAuthCbindCheck property.");
            //                        }
            //		                try {
            //		                    // Get cbind check flag using reflection
            //		                    final String className = "com.ibm.ws.security.zOS.NativeConfiguration";
            //		                    final Class<?> zNativeConfigClass = Class.forName(className);
            //		                    final Method getConfigMethod = zNativeConfigClass.getMethod("getConfig", (java.lang.Class[]) null);
            //		                    final Object configInstance = getConfigMethod.invoke((java.lang.Class[]) null, (java.lang.Object[]) null);
            //		                    final Method cbindCheckMethod = zNativeConfigClass.getMethod("isMutualAuthCBINDCheckEnabled", (java.lang.Class[]) null);
            //		                    cbindCheckEnabled = (Boolean) cbindCheckMethod.invoke(configInstance, (java.lang.Object[]) null);
            //		                } catch (Exception e) {
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            //		                        Tr.debug(tc, "No class, object, or method found for CBIND check", new Object[] {e});
            //		                    FFDCFilter.processException(e, CLASS_NAME, "1237");
            //		                }
            //		                if (cbindCheckEnabled.booleanValue()) {
            //		                    flag = cbindCheckEnabled.booleanValue();
            //		                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            //		                        Tr.debug(tc, "The mutualAuthCBINDCheck is true, so hard-coded setNeedClientAuth to true.");}
            //		                }
            //		            }
            //                }
            //            }

            engine.setNeedClientAuth(flag);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Client auth needed is " + engine.getNeedClientAuth());
            }
            if (!flag) {
                // Client auth set to false, check client auth supported
                flag = config.getBooleanProperty(Constants.SSLPROP_CLIENT_AUTHENTICATION_SUPPORTED);
                engine.setWantClientAuth(flag);
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Client auth supported is " + engine.getWantClientAuth());
                }
            }
            // enable ALPN support if this is for an inbound connection
            AlpnSupportUtils.registerAlpnSupport(connLink, engine);

        } else {
            // Update engine with client side specific config parameters.
            engine.setUseClientMode(true);
        }

        try {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Calling beginHandshake on engine");
            }
            engine.beginHandshake();
        } catch (SSLException se) {
            // no FFDC required
            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(tc, "Error while starting handshake; " + se);
            }
        }
    }
1082478
@Override
    public boolean isWsocRequest(ServletRequest request) throws ServletException {
        ServletContext context = request.getServletContext();
        Object wsocContainer = null;
        if (context != null) {
            wsocContainer = context.getAttribute(WebSocketContainerManager.SERVER_CONTAINER_ATTRIBUTE);
        }

        if (wsocContainer != null) {
            //check if this is a IBM's implementation of WebSocketContainer. If this is a tomcat or some other server's WebSocket
            //implementation of WebSocketContainer then, this is not a valid WebSocket request for us and Web Container should not call
            //WsocHandler.handleRequest() subsequently.
            if (!isValidContainer(wsocContainer)) {
                return false;
            }
        } else { //not a WebSocket request if ServerContainer attribute is missing.
            return false;
        }

        //call setNoMoreAddEndPoints only once per webapp
        if (!noMoreAddsCalled) {
            ((ServerContainerExt) wsocContainer).setNoMoreAddEndpointsAllowed();
            noMoreAddsCalled = true;
        }

        return checkWebSocketRequest(request, wsocContainer);
    }