Attaches an agent (where this class belongs) to the current
VirtualMachine.

TODO: Can we detect if VirtualMachine is loaded by trying to load it
again.

@return True if the agent is successfully attached, false otherwise.
975171
public static boolean loadEkstaziAgent() {
        // TODO: need to synchronize globally, as we may end up running
        // initialization multiple times, which would lead to:
        // "libattach.so already loaded in another classloader".
        try {
            // Note that this class can be loaded by different classloaders, so
            // we cannot simply use static field to check if the class has been
            // initialized.
            if (System.getProperty(AGENT_LOADER_INIT) != null) {
                return true;
            }
            System.setProperty(AGENT_LOADER_INIT, "");

            URL agentJarURL = Types.extractJarURL(EkstaziAgent.class);
            return loadAgent(agentJarURL);
        } catch (Exception ex) {
            if (System.getProperty("java.version").startsWith("9")) {
                throw new RuntimeException("Running with Java 9 requires -Djdk.attach.allowAttachSelf=true");
            }
            return false;
        }
    }
23612
def attached_to_model(self):
        """"""
        try:
            if not bool(self.model):
                return False
        except AttributeError:
            return False
        else:
            try:
                return not bool(self.instance)
            except AttributeError:
                return True
529968
def add_agent(self, agent):
        """"""
        agent_id = self.add_node(agent.name)
        self.add_typing(agent_id, 'agent')
        # Handle bound conditions
        for bc in agent.bound_conditions:
            # Here we make the assumption that the binding site
            # is simply named after the binding partner
            if bc.is_bound:
                test_type = 'is_bnd'
            else:
                test_type = 'is_free'
            bound_name = bc.agent.name
            agent_bs = get_binding_site_name(bc.agent)
            test_name = '%s_bound_to_%s_test' % (agent_id, bound_name)
            agent_bs_id = self.add_node(agent_bs)
            test_id = self.add_node(test_name)
            self.add_edge(agent_bs_id, agent_id)
            self.add_edge(agent_bs_id, test_id)
            self.add_typing(agent_bs_id, 'locus')
            self.add_typing(test_id, test_type)

        for mod in agent.mods:
            mod_site_str = abbrevs[mod.mod_type]
            if mod.residue is not None:
                mod_site_str = mod.residue
            mod_pos_str = mod.position if mod.position is not None else ''
            mod_site = ('%s%s' % (mod_site_str, mod_pos_str))
            site_states = states[mod.mod_type]
            if mod.is_modified:
                val = site_states[1]
            else:
                val = site_states[0]
            mod_site_id = self.add_node(mod_site, {'val': val})
            self.add_edge(mod_site_id, agent_id)
            self.add_typing(mod_site_id, 'state')
        return agent_id
450486
def applies_to (self, useragent):
        
        if not useragent:
            return True
        useragent = useragent.lower()
        for agent in self.useragents:
            if agent == '*':
                # we have the catch-all agent
                return True
            if agent.lower() in useragent:
                return True
        return False
1215431
@Override
    @SuppressWarnings("deprecation")
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        binderHelper.bindIfNecessary();
        lifeCycleDispatcher.onAttach(host(), activity);
    }
213834
private function providesMiddleware() : bool
    {
        $controller = $this->getController();

        if ($controller && ($controller instanceof ProvidesControllerMiddleware)) {
            return true;
        }

        return false;
    }
206202
function enableAgent(name) {
        if (agents.hasOwnProperty(name) && !_enabledAgentNames.hasOwnProperty(name)) {
            _enabledAgentNames[name] = true;
        }
    }
716968
public <T> void register(AgentFactory<T> agentFactory) {
		agentFactoriesByAgentId.put(agentFactory.getAgentId(), agentFactory);
	}
1248037
public boolean addMember (FormationMember<T> member) {
		// Find out how many slots we have occupied
		int occupiedSlots = slotAssignments.size;

		// Check if the pattern supports one more slot
		if (pattern.supportsSlots(occupiedSlots + 1)) {
			// Add a new slot assignment
			slotAssignments.add(new SlotAssignment<T>(member, occupiedSlots));

			// Update the slot assignments and return success
			updateSlotAssignments();
			return true;
		}

		return false;
	}
310384
public static synchronized Runnable performRuntimeAttachment() {
		if (runtimeAttached || !corePlugin.isStagemonitorActive() || !corePlugin.isAttachAgentAtRuntime()) {
			return NOOP_ON_SHUTDOWN_ACTION;
		}
		runtimeAttached = true;

		final List<ClassFileTransformer> classFileTransformers = new ArrayList<ClassFileTransformer>();
		final AutoEvictingCachingBinaryLocator binaryLocator = new AutoEvictingCachingBinaryLocator();
		if (assertNoDifferentStagemonitorVersionIsDeployedOnSameJvm() && initInstrumentation()) {
			final long start = System.currentTimeMillis();
			classFileTransformers.add(initByteBuddyClassFileTransformer(binaryLocator));
			if (corePlugin.isDebugInstrumentation()) {
				logger.info("Attached agents in {} ms", System.currentTimeMillis() - start);
			}
			TimedElementMatcherDecorator.logMetrics();
		}
		return new Runnable() {
			public void run() {
				for (ClassFileTransformer classFileTransformer : classFileTransformers) {
					instrumentation.removeTransformer(classFileTransformer);
				}
				// This ClassLoader is shutting down so don't try to retransform classes of it in the future
				hashCodesOfClassLoadersToIgnore.add(ClassUtils.getIdentityString(AgentAttacher.class.getClassLoader()));
				binaryLocator.close();
			}
		};
	}
448554
@Programmatic
    public boolean canAttach(
            final Object candidateToAttachTo) {
        final Class<? extends Paperclip> subtype = subtypeClassForElseNull(candidateToAttachTo);
        return subtype != null;
    }
129959
protected final void attach(Attachable widget) {
		if (user != null) {
			widget.addTo(user);
		} else {
			if (waitingForUser == null) waitingForUser = new LinkedList<Attachable>();
			waitingForUser.add(widget);
		}
	}
140991
public synchronized VirtualLinkAgent getVirtualLinkAgent() {
    if (this.virtualLinkAgent == null) {
      if (isService) {
        this.virtualLinkAgent =
            new VirtualLinkAgent(
                this.serviceName,
                this.projectId,
                this.sslEnabled,
                this.nfvoIp,
                this.nfvoPort,
                this.version,
                this.serviceKey);
      } else {
        this.virtualLinkAgent =
            new VirtualLinkAgent(
                this.username,
                this.password,
                this.projectId,
                this.sslEnabled,
                this.nfvoIp,
                this.nfvoPort,
                this.version);
      }
    }
    return this.virtualLinkAgent;
  }
394001
public boolean hasRunOnMachine(String trackerHost, String trackerName) {
    return this.activeTasks.values().contains(trackerName) || 
      hasFailedOnMachine(trackerHost);
  }
1246409
protected static synchronized boolean isPresent() {
        if (m_Present == null) {
            try {
                SizeOfAgent.fullSizeOf(new Integer(1));
                m_Present = true;
            } catch (Throwable t) {
                m_Present = false;
            }
        }

        return m_Present;
    }
1270640
@Override
    public boolean applyAction(Model m) {
        Mapping map = m.getMapping();
        return map.isRunning(vm) &&
                map.getVMLocation(vm).equals(src) &&
                map.addSleepingVM(vm, dst);
    }
744011
@Override
	public boolean isMachineRunning( TargetHandlerParameters parameters, String machineId )
	throws TargetException {

		this.logger.fine( "Verifying the in-memory agent for " + machineId + " is running." );
		Map<String,String> targetProperties = preventNull( parameters.getTargetProperties());

		// No agent factory => no iPojo instance => not running
		boolean result = false;
		if( this.standardAgentFactory != null )
			result = this.standardAgentFactory.getInstancesNames().contains( machineId );

		// On restoration, in-memory agents will ALL have disappeared.
		// So, it makes sense to recreate them if they do not exist anymore.
		// To determine whether we should restore them or no, we look for the model in the manager.
		if( ! result && ! simulatePlugins( targetProperties )) {

			Map.Entry<String,String> ctx = parseMachineId( machineId );
			ManagedApplication ma = this.manager.applicationMngr().findManagedApplicationByName( ctx.getValue());
			Instance scopedInstance = InstanceHelpers.findInstanceByPath( ma.getApplication(), ctx.getKey());

			// Is it supposed to be running?
			if( scopedInstance.getStatus() != InstanceStatus.NOT_DEPLOYED ) {
				this.logger.fine( "In-memory agent for " + machineId + " is supposed to be running but is not. It will be restored." );
				Map<String,String> messagingConfiguration = this.manager.messagingMngr().getMessagingClient().getConfiguration();
				Factory factory = findIPojoFactory( parameters );
				createIPojo( targetProperties, messagingConfiguration, machineId, ctx.getKey(), ctx.getValue(), this.manager.getDomain(), factory );
				result = true;
				// The agent will restore its model by asking it to the DM.
			}
		}

		return result;
	}