Attach ServiceInstance to the Session.

When create a new session, it need to attach the session again.

@param instanceTokens
the instance list.
@param cb
the callback.
@param context
the context object.
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);
    }
1017294
private StartInstancesResponseType startInstances(final Set<String> instanceIDs) {
        StartInstancesResponseType ret = new StartInstancesResponseType();
        ret.setRequestId(UUID.randomUUID().toString());
        InstanceStateChangeSetType changeSet = new InstanceStateChangeSetType();
        changeSet.getItem().addAll(mockEc2Controller.startInstances(instanceIDs));
        ret.setInstancesSet(changeSet);
        return ret;

    }
542697
@Override
    public final SessionDestroyedListener addingService(ServiceReference<SessionDestroyedListener> serviceReference) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Listener [" + serviceReference + "] has been added.");
        }

        final SessionDestroyedListener listener = context.getService(serviceReference);
        handler.addListener(listener);

        return listener;
    }
551293
public static void bind(ApplicationContext context) {
        Object old = contextMap.putIfAbsent(getContextClassLoader(), context);
        if (old != null) {
            throw new IllegalStateException(
                "There is already a ApplicationContext associated with the context ClassLoader of the current thread!");
        }
    }
153410
private void deployInstances(List<InstanceContext> instances, final Handler<AsyncResult<Void>> doneHandler) {
    final CountingCompletionHandler<Void> counter = new CountingCompletionHandler<Void>(instances.size()).setHandler(doneHandler);
    for (final InstanceContext instance : instances) {
      // Before deploying the instance, check if the instance is already deployed in
      // the network's cluster.
      deploymentIDs.get(instance.address(), new Handler<AsyncResult<String>>() {
        @Override
        public void handle(AsyncResult<String> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else if (result.result() == null) {
            // If no deployment ID has been assigned to the instance then that means it hasn't
            // yet been deployed. Deploy the instance.
            deployInstance(instance, counter);
          } else {
            // Even if the instance is already deployed, update its context in the cluster.
            // It's possible that the instance's connections could have changed with the update.
            data.put(instance.address(), Contexts.serialize(instance).encode(), new Handler<AsyncResult<String>>() {
              @Override
              public void handle(AsyncResult<String> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  counter.succeed();
                }
              }
            });
          }
        }
      });
    }
  }
335967
@Override
    public void start(BundleContext context) {

        initialContextFactories = initServiceTracker(context, InitialContextFactory.class, ServiceTrackerCustomizers.ICF_CACHE);
        objectFactories = initServiceTracker(context, ObjectFactory.class, ServiceTrackerCustomizers.URL_FACTORY_CACHE);
        icfBuilders = initServiceTracker(context, InitialContextFactoryBuilder.class, ServiceTrackerCustomizers.LAZY);
        urlObjectFactoryFinders = initServiceTracker(context, URLObjectFactoryFinder.class, ServiceTrackerCustomizers.LAZY);
        environmentAugmentors = initServiceTracker(context, EnvironmentAugmentation.class, null);
        environmentUnaugmentors = initServiceTracker(context, EnvironmentUnaugmentation.class, null);

        try {
            OSGiInitialContextFactoryBuilder builder = new OSGiInitialContextFactoryBuilder();
            setField(InitialContextFactoryBuilder.class, builder, true);
            icfBuilder = builder;
        } catch (IllegalStateException e) {
            // Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
            // don't want to see stack traces at info level when everything it working as expected.
            LOGGER.info(Utils.MESSAGES.getMessage("unable.to.set.static.ICFB.already.exists", getClassName(InitialContextFactoryBuilder.class)));
            LOGGER.debug(Utils.MESSAGES.getMessage("unable.to.set.static.ICFB.already.exists", getClassName(InitialContextFactoryBuilder.class)), e);
        }

        try {
            OSGiObjectFactoryBuilder builder = new OSGiObjectFactoryBuilder(context);
            setField(ObjectFactoryBuilder.class, builder, true);
            ofBuilder = builder;
        } catch (IllegalStateException e) {
            // Log the problem at info level, but only log the exception at debug level, as in many cases this is not a real issue and people
            // don't want to see stack traces at info level when everything it working as expected.
            LOGGER.info(Utils.MESSAGES.getMessage("unable.to.set.static.OFB.already.exists", getClassName(ObjectFactoryBuilder.class)));
            LOGGER.debug(Utils.MESSAGES.getMessage("unable.to.set.static.OFB.already.exists", getClassName(ObjectFactoryBuilder.class)), e);
        }

        context.registerService(JNDIProviderAdmin.class.getName(),
                                new ProviderAdminServiceFactory(context),
                                null);

        context.registerService(InitialContextFactoryBuilder.class.getName(),
                                new JREInitialContextFactoryBuilder(),
                                null);

        context.registerService(JNDIContextManager.class.getName(),
                                new ContextManagerServiceFactory(),
                                null);

        context.registerService(AugmenterInvoker.class.getName(),
                                AugmenterInvokerImpl.getInstance(),
                                null);

        //Start the bundletracker that clears out the cache. (only interested in stopping events)
        // bt = new BundleTracker(context, Bundle.STOPPING, new ServiceTrackerCustomizers.CacheBundleTrackerCustomizer());
        // bt.open();
    }
109126
public static synchronized MCAAuthorizationManager createInstance(Context context) {
        if (instance == null) {
            instance = new MCAAuthorizationManager(context.getApplicationContext());

            instance.bluemixRegionSuffix = BMSClient.getInstance().getBluemixRegionSuffix();
            instance.tenantId = BMSClient.getInstance().getBluemixAppGUID();

            AuthorizationRequest.setup();
        }
        return instance;
    }
324300
protected void createInterceptorsAndInstance(CallbackContextHelper contextHelper) throws InvocationTargetException {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "createInterceptorsAndInstance : " + contextHelper);

        BeanMetaData bmd = home.beanMetaData;
        ManagedObjectFactory<?> managedObjectFactory = bmd.ivEnterpriseBeanFactory;
        if (managedObjectFactory != null) {
            try {
                ivEjbManagedObjectContext = managedObjectFactory.createContext();
            } catch (ManagedObjectException e) {
                throw ExceptionUtil.EJBException("AroundConstruct interceptors for the " + bmd.enterpriseBeanName +
                                                 " bean in the " + bmd._moduleMetaData.ivName +
                                                 " module in the " + bmd._moduleMetaData.ivAppName +
                                                 " application resulted in an exception being thrown from the ManagedObjectFactory.createContext() method", e);
            }
        }

        InterceptorMetaData imd = bmd.ivInterceptorMetaData;
        if (imd != null && !bmd.managedObjectManagesInjectionAndInterceptors) {
            createInterceptors(imd);
            if (bmd.ivCallbackKind == CallbackKind.InvocationContext) {
                InterceptorProxy[] aroundConstructProxies = imd.ivAroundConstructInterceptors;
                if (aroundConstructProxies != null) {
                    InvocationContextImpl<?> context = callAroundConstructInterceptors(aroundConstructProxies, contextHelper);
                    // If InvocationContext.proceed() was not called, the bean's
                    // constructor was never called and ivEjbInstance will be null.
                    if (ivEjbInstance == null) {
                        // If the interceptor swallowed an exception from
                        // proceed(), we re-throw it now to give a better
                        // error message than a generic "failed to create".
                        if (context.ivAroundConstructException != null) {
                            Throwable t = context.ivAroundConstructException.getCause();
                            if (t == null) {
                                // Don't lose the application exception if it doesn't happen to be nested
                                t = context.ivAroundConstructException;
                            }
                            throw ExceptionUtil.EJBException("AroundConstruct interceptors for the " + bmd.enterpriseBeanName +
                                                             " bean in the " + bmd._moduleMetaData.ivName +
                                                             " module in the " + bmd._moduleMetaData.ivAppName +
                                                             " application resulted in an exception being thrown from the constructor of the " +
                                                             bmd.enterpriseBeanClassName + " class.", t);
                        }

                        // Otherwise, the interceptor must not have called proceed().
                        throw new EJBException("AroundConstruct interceptors for the " + bmd.enterpriseBeanName +
                                               " bean in the " + bmd._moduleMetaData.ivName +
                                               " module in the " + bmd._moduleMetaData.ivAppName +
                                               " application did not call InvocationContext.proceed()");
                    }
                }
            }
        }

        // If no @AroundConstructor interceptor, create the instance now.
        if (ivEjbInstance == null) {
            createInstance();
        }
        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "createInterceptorsAndInstance");
    }
1065571
public void setInstanceGroupTypes(java.util.Collection<String> instanceGroupTypes) {
        if (instanceGroupTypes == null) {
            this.instanceGroupTypes = null;
            return;
        }

        this.instanceGroupTypes = new com.amazonaws.internal.SdkInternalList<String>(instanceGroupTypes);
    }
1065194
public void setSbbContext(SbbContext sbbContext) {
		this.sbbContext = (SbbContextExt) sbbContext;
		if (tracer == null) {
			tracer = sbbContext.getTracer(XDMClientChildSbb.class
					.getSimpleName());
		}
		try {
			Context context = (Context) new InitialContext()
					.lookup("java:comp/env");
			xcapClientSbbInterface = (XCAPClientResourceAdaptorSbbInterface) context
					.lookup("slee/resources/xcapclient/2.0/sbbrainterface");
			xcapClientACIF = (XCAPClientActivityContextInterfaceFactory) context
					.lookup("slee/resources/xcapclient/2.0/acif");
		} catch (NamingException e) {
			tracer.severe("Can't set sbb context.", e);
		}
	}
714132
static void releaseContext(SeaGlassContext context) {
        synchronized (contextMap) {
            List instances = (List) contextMap.get(context.getClass());

            if (instances == null) {
                instances = new ArrayList(5);
                contextMap.put(context.getClass(), instances);
            }

            instances.add(context);
        }
    }
1177203
public void setInstancesToProtect(java.util.Collection<String> instancesToProtect) {
        if (instancesToProtect == null) {
            this.instancesToProtect = null;
            return;
        }

        this.instancesToProtect = new com.amazonaws.internal.SdkInternalList<String>(instancesToProtect);
    }
1082147
public void setStoppingInstances(java.util.Collection<InstanceStateChange> stoppingInstances) {
        if (stoppingInstances == null) {
            this.stoppingInstances = null;
            return;
        }

        this.stoppingInstances = new com.amazonaws.internal.SdkInternalList<InstanceStateChange>(stoppingInstances);
    }
59788
public void queryService(List<StringCommand> commands, final QueryServiceCallback cb, Object context){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.QueryService);

        List<QueryCommand> cs = new ArrayList<QueryCommand>();
        for(StringCommand c : commands){
            cs.add(c.getStringCommand());
        }

        QueryServiceProtocol p = new QueryServiceProtocol(cs);

        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                List<ModelServiceInstance> rsp = null;
                if(response != null){
                    rsp = ((QueryServiceResponse) response).getInstances();
                }
                cb.call(result, rsp, error, ctx);
            }

        };

        connection.submitCallbackRequest(header, p, pcb, context);
    }
598005
private void deployInstance(final InstanceContext instance, final CountingCompletionHandler<Void> counter) {
    // First we need to select a node from the component's deployment group
    // to which to deploy the component.
    // If the component doesn't specify a group then deploy to any node in the cluster.
    if (instance.component().group() != null) {
      cluster.getGroup(instance.component().group(), new Handler<AsyncResult<Group>>() {
        @Override
        public void handle(AsyncResult<Group> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else {
            result.result().selectNode(instance.address(), new Handler<AsyncResult<Node>>() {
              @Override
              public void handle(AsyncResult<Node> result) {
                if (result.failed()) {
                  counter.fail(result.cause());
                } else {
                  deployInstance(result.result(), instance, counter);
                }
              }
            });
          }
        }
      });
    } else {
      cluster.selectNode(instance.address(), new Handler<AsyncResult<Node>>() {
        @Override
        public void handle(AsyncResult<Node> result) {
          if (result.failed()) {
            counter.fail(result.cause());
          } else {
            deployInstance(result.result(), instance, counter);
          }
        }
      });
    }
  }
294266
public void getService(String serviceName, final GetServiceCallback cb, Object context){
        ProtocolHeader header = new ProtocolHeader();
        header.setType(ProtocolType.GetService);

        GetServiceProtocol p = new GetServiceProtocol(serviceName);
        p.setWatcher(false);

        ProtocolCallback pcb = new ProtocolCallback(){

            @Override
            public void call(boolean result, Response response,
                    ErrorCode error, Object ctx) {
                ModelService rsp = null;
                if(response != null){
                    rsp = ((GetServiceResponse) response).getService();
                }
                cb.call(result, rsp, error, ctx);
            }

        };

        connection.submitCallbackRequest(header, p,  pcb, context);
    }
387694
public HttpSessionTokensSet getHttpSessionTokensSetForContext(Context context){
		//TODO: Proper implementation. Hack for now
		for (Entry<String, HttpSessionTokensSet> e : this.sessionTokens.entrySet()) {
			String siteName = e.getKey();
			siteName = "http://" + siteName;
			if (context.isInContext(siteName))
				return e.getValue();
		}
		return null;
	}