Callback fired when client wants to attach session.
495216
def onHello(self, realm, details):
        
        log.msg("onHello: {} {}".format(realm, details))

        self._pending_auth = None

        if details.authmethods:
            for authmethod in details.authmethods:
                if authmethod == u"wampcra":

                    ## lookup user in user DB
                    salt, key, role, uid = yield self.factory.userdb.get(details.authid)
                    log.msg("salt, key, role: {} {} {} {}".format(salt, key, role, uid))

                    ## if user found ..
                    if key:

                        log.msg("found key")

                        ## setup pending auth
                        self._pending_auth = PendingAuth(key, details.pending_session,
                            details.authid, role, authmethod, u"userdb", uid)

                        log.msg("setting challenge")
                        ## send challenge to client
                        extra = {
                            u'challenge': self._pending_auth.challenge
                        }

                        ## when using salted passwords, provide the client with
                        ## the salt and then PBKDF2 parameters used
                        if salt:
                            extra[u'salt'] = salt
                            extra[u'iterations'] = 1000
                            extra[u'keylen'] = 32

                        defer.returnValue(types.Challenge(u'wampcra', extra))

        ## deny client
        defer.returnValue(types.Deny())
311364
function(callback){
			if(!this.id){
				return process.nextTick(function(){
					callback(new Error("Invalid session ID"));
				});
			}
			options.client.expire(options.keyspace + this.id, options.maxAge, callback);
		}
1195333
private void callbackSucceed() {
        if (mGranted != null) {
            List<String> permissionList = asList(mPermissions);
            try {
                mGranted.onAction(permissionList);
            } catch (Exception e) {
                Log.e("AndPermission", "Please check the onGranted() method body for bugs.", e);
                if (mDenied != null) {
                    mDenied.onAction(permissionList);
                }
            }
        }
    }
838163
function(callback){
			if(!this.id){
				return process.nextTick(function(){
					callback(new Error("Invalid session ID"));
				});
			}
			options.client.del(options.keyspace + this.id, callback);
		}
1002064
public void attachSession(List<ServiceInstanceToken> instanceTokens){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.AttachSession);

        String sessionId = connection.getSessionId();
        AttachSessionProtocol protocol = new AttachSessionProtocol(instanceTokens, sessionId);
        connection.submitRequest(header, protocol, null);

    }
574612
void triggerSessionRequested(Jingle initJin) {

        JingleSessionRequestListener[] jingleSessionRequestListeners;

        // Make a synchronized copy of the listenerJingles
        synchronized (this.jingleSessionRequestListeners) {
            jingleSessionRequestListeners = new JingleSessionRequestListener[this.jingleSessionRequestListeners.size()];
            this.jingleSessionRequestListeners.toArray(jingleSessionRequestListeners);
        }

        // ... and let them know of the event
        JingleSessionRequest request = new JingleSessionRequest(this, initJin);
        for (int i = 0; i < jingleSessionRequestListeners.length; i++) {
            jingleSessionRequestListeners[i].sessionRequested(request);
        }
    }
1298185
function (changes, cb) {
        var self = this;

        this._log('info', 'Initiating incoming session');

        this.state = 'pending';

        this.pc.isInitiator = false;

        var desc = changes.contents[0].application;


        this.receiver = new FileTransfer.Receiver({hash: desc.offer.hash.algo});
        this.receiver.on('progress', function (received, size) {
            self._log('info', 'Receive progress ' + received + '/' + size);
        });
        this.receiver.on('receivedFile', function (file) {
            self.receivedFile = file;
            self.maybeReceivedFile();
        });
        this.receiver.metadata = desc.offer;

        changes.contents[0].application = {
            applicationType: 'datachannel'
        };

        this.pc.handleOffer({
            type: 'offer',
            jingle: changes
        }, function (err) {
            if (err) {
                self._log('error', 'Could not create WebRTC answer');
                return cb({condition: 'general-error'});
            }
            cb();
        });
    }
1274070
@Override
    public void onApplicationEvent(HttpSessionDestroyedEvent event) {
        final HttpSession session = ((HttpSessionDestroyedEvent) event).getSession();
        @SuppressWarnings("unchecked")
        final Map<String, PortletSession> portletSessions =
                (Map<String, PortletSession>) session.getAttribute(PORTLET_SESSIONS_MAP);
        if (portletSessions == null) {
            return;
        }

        /*
         * Since (at least) Tomcat 7.0.47, this method has the potential to
         * generate a StackOverflowError because PortletSession.invalidate()
         * will trigger another HttpSessionDestroyedEvent, which means this
         * method will be called again.  I don't know if this behavior is a bug
         * in Tomcat or Spring, if this behavior is entirely proper, or if the
         * reality somewhere in between.
         *
         * For the present, let's put a token in the HttpSession (which is
         * available from the event object) as soon as we start invalidating it.
         * We'll then ignore sessions that already have this token.
         */
        if (session.getAttribute(ALREADY_INVALIDATING_SESSION_ATTRIBUTE) != null) {
            // We're already invalidating;  don't do it again
            return;
        }
        session.setAttribute(ALREADY_INVALIDATING_SESSION_ATTRIBUTE, Boolean.TRUE);

        for (final Map.Entry<String, PortletSession> portletSessionEntry :
                portletSessions.entrySet()) {
            final String contextPath = portletSessionEntry.getKey();
            final PortletSession portletSession = portletSessionEntry.getValue();
            try {
                portletSession.invalidate();
            } catch (IllegalStateException e) {
                this.logger.info(
                        "PortletSession with id '"
                                + portletSession.getId()
                                + "' for context '"
                                + contextPath
                                + "' has already been invalidated.");
            } catch (Exception e) {
                this.logger.warn(
                        "Failed to invalidate PortletSession with id '"
                                + portletSession.getId()
                                + "' for context '"
                                + contextPath
                                + "'",
                        e);
            }
        }
    }
386835
function Session(req, data) {
  Object.defineProperty(this, 'req', { value: req });
  Object.defineProperty(this, 'id', { value: req.sessionID });

  if (typeof data === 'object' && data !== null) {
    // merge data into this, ignoring prototype properties
    for (var prop in data) {
      if (!(prop in this)) {
        this[prop] = data[prop]
      }
    }
  }
}
40177
@EventThread
    protected void finishResumeSession ()
    {
        // if we have no client object for whatever reason; we're hosed, shut ourselves down
        if (_clobj == null) {
            log.info("Missing client object for resuming session " + this + ".");
            endSession();
            return;
        }

        // make extra sure we have no lingering subscriptions
        clearSubscrips(false);

        // Update our client secret with the new auth request
        _clobj.getLocal(ClientLocal.class).secret = getSecret();

        // let derived classes do any session resuming
        sessionWillResume();

        // send off a bootstrap notification immediately as we've already got our client object
        sendBootstrap();

        // resend the throttle update if non-default
        if (_messagesPerSec != Client.DEFAULT_MSGS_PER_SECOND) {
            sendThrottleUpdate();
        }

        log.info("Session resumed " + this + ".");
    }
787791
def on_connect(client):
    """"""
    client.nick(client.user.nick)
    client.userinfo(client.user.username, client.user.realname)
386098
function createSession (callback) {
      var path, sessionCreate;

      _log(me.setting);
      path = me.setting.apiroot + '/session/create.json?apiKey=' + me.setting.apikey;
      _log(path);

      sessionCreate = http.request({
        port: me.setting.port,
        host: me.setting.host,
        method: 'POST',
        path: path
      });

      sessionCreate.on('response', function (response) {
        var data = '';

        _log('STATUS: ' + response.statusCode);
        _log('HEADERS: ' + JSON.stringify(response.headers));

        if (200 !== response.statusCode) {
          callback(response.statusCode);
          return;
        }

        response.on('data', function (chunk) {
          data += chunk;
        });

        response.on('end', function() {
          var sessionInfo = JSON.parse(data);
          _log('SID OK: ' + sessionInfo.sid);

          callback(response.statusCode, sessionInfo);
        });
      });

      sessionCreate.on('error', function(err) {
        console.error(err);
      });

      sessionCreate.end();
    }
197099
public void attachSession(List<ServiceInstanceToken> instanceTokens, final AttachSessionCallback cb, Object context){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.AttachSession);

        String sessionId = connection.getSessionId();
        AttachSessionProtocol protocol = new AttachSessionProtocol(instanceTokens, sessionId);
        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                Map<ServiceInstanceToken, ItemResult> items = ((AttachSessionResponse)response).getAttachingResult();
                cb.call(result, items, error, ctx);
            }

        };

        connection.submitCallbackRequest(header, protocol, pcb, context);
    }
304633
def wrap_session_request(wrapped, instance, args, kwargs):
    """"""
    method = kwargs.get('method') or args[0]
    url = kwargs.get('url') or args[1]

    blacklist_hostnames = execution_context.get_opencensus_attr(
        'blacklist_hostnames')
    parsed_url = urlparse(url)
    if parsed_url.port is None:
        dest_url = parsed_url.hostname
    else:
        dest_url = '{}:{}'.format(parsed_url.hostname, parsed_url.port)
    if utils.disable_tracing_hostname(dest_url, blacklist_hostnames):
        return wrapped(*args, **kwargs)

    _tracer = execution_context.get_opencensus_tracer()
    _span = _tracer.start_span()

    _span.name = '[requests]{}'.format(method)
    _span.span_kind = span_module.SpanKind.CLIENT

    try:
        tracer_headers = _tracer.propagator.to_headers(
            _tracer.span_context)
        kwargs.setdefault('headers', {}).update(
            tracer_headers)
    except Exception:  # pragma: NO COVER
        pass

    # Add the requests url to attributes
    _tracer.add_attribute_to_current_span(HTTP_URL, url)

    result = wrapped(*args, **kwargs)

    # Add the status code to attributes
    _tracer.add_attribute_to_current_span(
        HTTP_STATUS_CODE, str(result.status_code))

    _tracer.end_span()
    return result
569997
@OnOpen
    public void uiClientSessionOpen(Session session) {
        log.infoWsSessionOpened(session.getId(), endpoint);
        wsEndpoints.getUiClientSessions().addSession(session.getId(), session);
        WelcomeResponse welcomeResponse = new WelcomeResponse();
        // FIXME we should not send the true sessionIds to clients to prevent spoofing.
        welcomeResponse.setSessionId(session.getId());
        try {
            new WebSocketHelper().sendBasicMessageSync(session, welcomeResponse);
        } catch (IOException e) {
            log.warnf(e, "Could not send [%s] to UI client session [%s].", WelcomeResponse.class.getName(),
                    session.getId());
        }
    }
1259246
public void fireSessionCreated(IoSession session) {
        boolean firstSession = false;
        if (session.getService() instanceof IoConnector) {
            synchronized (managedSessions) {
                firstSession = managedSessions.isEmpty();
            }
        }

        // If already registered, ignore.
        if (managedSessions.putIfAbsent(session.getId(), session) != null) {
            return;
        }

        // If the first connector session, fire a virtual service activation event.
        if (firstSession) {
            fireServiceActivated();
        }

        // Fire session events.
        IoFilterChain filterChain = session.getFilterChain(); 
        filterChain.fireSessionCreated();
        filterChain.fireSessionOpened();

        int managedSessionCount = managedSessions.size();
        if (managedSessionCount > largestManagedSessionCount) {
            largestManagedSessionCount = managedSessionCount;
        }
        cumulativeManagedSessionCount ++;

        // Fire listener events.
        for (IoServiceListener l : listeners) {
            try {
                l.sessionCreated(session);
            } catch (Throwable e) {
                ExceptionMonitor.getInstance().exceptionCaught(e);
            }
        }
    }
117017
def session(self) -> SessionT:
        ''''''
        session = self._session_class()(
            connection_pool=self._connection_pool,
        )
        self.event_dispatcher.notify(self.ClientEvent.new_session, session)
        return session