The premain method to be implemented by java agents to provide an entry point for the instrumentation.

@param agentArgs arguments passed to the agent.
@param instrumentation the Instrumentation.
546008
public static void premain(final String agentArgs, final Instrumentation instrumentation) {
    System.out.println("Initialiting Appmon4jAgent");

    Appmon4JAgentConfiguration configuration = null;
    try {
      configuration = Appmon4JAgentConfiguration.load(agentArgs);
    } catch (Exception e) {
      System.err.println("failed to load appmon4j agent configuration from " + agentArgs + ".");
      e.printStackTrace();
    }

    if (configuration != null) {
      new Appmon4JAgent(configuration, instrumentation);
    } else {
      System.err.println("appmon4j Agent: Unable to start up. No valid configuration found. Will do nothing. ");
    }
  }
242347
public static void initApplication(String... args) {
		if (args.length < 1) {
			System.err.println("Please specify an Application as argument");
			System.exit(-1);
		}
		setInstance(createApplicationByClassName(args[0]));
	}
629354
@Override ImmutableSet<String> getExtraCommandLineArgs() {
    String agentJar = options.get(ALLOCATION_AGENT_JAR_OPTION);
    if (Strings.isNullOrEmpty(agentJar)) {
      try {
        Optional<File> instrumentJar = findAllocationInstrumentJarOnClasspath();
        // TODO(gak): bundle up the allocation jar and unpack it if it's not on the classpath
        if (instrumentJar.isPresent()) {
          agentJar = instrumentJar.get().getAbsolutePath();
        }
      } catch (IOException e) {
        logger.log(SEVERE,
            "An exception occurred trying to locate the allocation agent jar on the classpath", e);
      }
    }
    if (Strings.isNullOrEmpty(agentJar) || !new File(agentJar).exists()) {
      throw new IllegalStateException("Can't find required allocationinstrumenter agent jar");
    }
    // Add microbenchmark args to minimize differences in the output
    return new ImmutableSet.Builder<String>()
        .addAll(super.getExtraCommandLineArgs())
        // we just run in interpreted mode to ensure that intrinsics don't break the instrumentation
        .add("-Xint")
        .add("-javaagent:" + agentJar)
        // Some environments rename files and use symlinks to improve resource caching,
        // if the agent jar path is actually a symlink it will prevent the agent from finding itself
        // and adding itself to the bootclasspath, so we do it manually here.
        .add("-Xbootclasspath/a:" + agentJar)
        .build();
  }
767249
public void setAgents(java.util.Collection<AgentListEntry> agents) {
        if (agents == null) {
            this.agents = null;
            return;
        }

        this.agents = new java.util.ArrayList<AgentListEntry>(agents);
    }
926463
void handleAgentsEvent(AgentsEvent event)
    {
        AsteriskAgentImpl agent = new AsteriskAgentImpl(server,
                event.getName(), "Agent/" + event.getAgent(), AgentState.valueOf(event.getStatus()));
        logger.info("Adding agent " + agent.getName() + "(" + agent.getAgentId() + ")");

        addAgent(agent);
    }
933976
public static void premain(String args, Instrumentation instrumentation) {
        if (!PreMainUtil.isBeta() && !PreMainUtil.isEnableAgentPropertySet()) {
            // if it's not beta, do nothing.
            // this implementation should be changed when this will be in the production code.
            return;
        }
        ObjectInputStreamTransformer transform = null;
        if (ObjectInputStreamClassInjector.injectionNeeded()) {
            // Install the transformer to modify ObjectInputStream.
            if (PreMainUtil.isDebugEnabled()) {
                System.out.println("Using class file transformer to modify ObjectInputStream.");
            }
            transform = new ObjectInputStreamTransformer();
            instrumentation.addTransformer(transform);
        }
        try {
            initialiseObjectInputStream();    
        } finally {
            // Uninstall the class transformer.
            if (transform != null) {
                if (PreMainUtil.isDebugEnabled()) {
                    System.out.println("Removing class file transformer.");
                }
                instrumentation.removeTransformer(transform);
            }
        }
        
        AccessController.doPrivileged(new PrivilegedAction<String>() {
            public String run() {
                return System.setProperty(PreMainUtil.KEY_SERIALFILTER_AGENT_ACTIVE, "true");
            }
        });
    }
558494
public void addUserAgent(String userAgent) {
    if (userAgent.equals("*")) {
      anyAgent = true;
    } else {
      this.userAgents.add(userAgent);
    }
  }
675692
public static synchronized void configure(final String options,
			final Instrumentation instrumentation) throws Exception {

		if (SigarAgent.instrumentation != null) {
			logger.severe("Duplicate agent setup attempt.");
			return;
		}

		SigarAgent.options = options;
		SigarAgent.instrumentation = instrumentation;

		logger.info("Sigar loader options: " + options);

		final File folder = new File(SigarProvisioner.discoverLocation(options));

		SigarProvisioner.provision(folder);

	}
413816
public static void premain(String args) {
        if (args == null) {
            args = "config=config.yaml";
        }

        try {
            start(args.split(","));
        } catch (Exception e) {
            System.err.println("Hawkular Java Agent failed at startup");
            e.printStackTrace(System.err);
        }
    }
32654
@Override
    public void createAgent(String agent_name, String path) {
        logger.fine("Creating agent " + agent_name + " in Main Container");
        Object reference = new Object();
        Object empty[] = new Object[1];
        empty[0] = reference;
        try {
            AgentController agentController = mainContainer.createNewAgent(
                    agent_name, path, empty);
            this.createdAgents.put(agent_name, agentController);
            agentController.start();
            logger.fine("Agent " + agent_name
                    + " created and started in Main Container");
            try {
                Thread.sleep(MILLIS_TO_WAIT_FOR_AGENT_STARTING);
            } catch (InterruptedException e) {
                logger.warning("It was not possible to wait for agent starting... Maybe, the agent is not completely started yet.");
            }
        } catch (StaleProxyException e) {
            logger.warning("Exception creating or starting agent in MainContainer... "
                    + e);
        }
        // Register the agent
    }
625885
private static void loadAgent(Config config, Log log, String agentJar, Class<?> vmClass) {
	try {

	    // addAttach(config,log);

	    // first obtain the PID of the currently-running process
	    // ### this relies on the undocumented convention of the
	    // RuntimeMXBean's
	    // ### name starting with the PID, but there appears to be no other
	    // ### way to obtain the current process' id, which we need for
	    // ### the attach process
	    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
	    String pid = runtime.getName();
	    if (pid.indexOf("@") != -1) pid = pid.substring(0, pid.indexOf("@"));
	    log.info("Instrumentation", "pid:" + pid);
	    // JDK1.6: now attach to the current VM so we can deploy a new agent
	    // ### this is a Sun JVM specific feature; other JVMs may offer
	    // ### this feature, but in an implementation-dependent way
	    Object vm = vmClass.getMethod("attach", new Class<?>[] { String.class }).invoke(null, new Object[] { pid });
	    // now deploy the actual agent, which will wind up calling
	    // agentmain()
	    vmClass.getMethod("loadAgent", new Class[] { String.class }).invoke(vm, new Object[] { agentJar });
	    vmClass.getMethod("detach", new Class[] {}).invoke(vm, new Object[] {});
	}
	catch (Throwable t) {
	    ExceptionUtil.rethrowIfNecessary(t);
	    // Log the message from the exception. Don't log the entire
	    // stack as this is expected when running on a JDK that doesn't
	    // support the Attach API.
	    log.log(Log.LEVEL_INFO, "Instrumentation", t);

	}
    }
1301059
@PostConstruct
    void init(TracingRunnableInstrumenter instrumenter) {
        if (instrumenter != null) {
            Func1<Action0, Action0> existing = RxJavaHooks.getOnScheduleAction();
            if (existing != null && !(existing instanceof InstrumentScheduleAction)) {
                RxJavaHooks.setOnScheduleAction(action0 ->
                        new InstrumentScheduleAction(instrumenter).call(existing.call(action0))
                );
            } else {
                RxJavaHooks.setOnScheduleAction(new InstrumentScheduleAction(instrumenter));
            }
        }
    }
16011
protected void agentCreated (ClientObject client, int agentId)
    {
        FoundAgent found = resolve(client, agentId, "agentCreated");
        if (found == null) {
            return;
        }

        log.info("Agent creation confirmed", "agent", found.agent.which());

        if (found.state == AgentState.STARTED) {
            found.bureau.agentStates.put(found.agent, AgentState.RUNNING);
            found.agent.setClientOid(client.getOid());

        } else if (found.state == AgentState.STILL_BORN) {
            // TODO: have a timeout for this in case the client is misbehaving or hung
            BureauSender.destroyAgent(found.bureau.clientObj, agentId);
            found.bureau.agentStates.put(found.agent, AgentState.DESTROYED);

        } else if (found.state == AgentState.PENDING ||
            found.state == AgentState.RUNNING ||
            found.state == AgentState.DESTROYED) {
            log.warning("Ignoring confirmation of creation of an agent in an unexpected state",
                        "state", found.state, "agent", found.agent.which());
        }

        found.bureau.summarize();
    }
1276018
@Override
    public void loadAgent(String agent, String options)
        throws AgentLoadException, AgentInitializationException, IOException
    {
        String args = agent;
        if (options != null) {
            args = args + "=" + options;
        }
        try {
            loadAgentLibrary("instrument", args);
        } catch (AgentLoadException x) {
            throw new InternalError("instrument library is missing in target VM");
        } catch (AgentInitializationException x) {
            /*
             * Translate interesting errors into the right exception and
             * message (FIXME: create a better interface to the instrument
             * implementation so this isn't necessary)
             */
            int rc = x.returnValue();
            switch (rc) {
                case JNI_ENOMEM:
                    throw new AgentLoadException("Insuffient memory");
                case ATTACH_ERROR_BADJAR:
                    throw new AgentLoadException("Agent JAR not found or no Agent-Class attribute");
                case ATTACH_ERROR_NOTONCP:
                    throw new AgentLoadException("Unable to add JAR file to system class path");
                case ATTACH_ERROR_STARTFAIL:
                    throw new AgentInitializationException("Agent JAR loaded but agent failed to initialize");
                default :
                    throw new AgentLoadException("Failed to load agent - unknown reason: " + rc);
            }
        }
    }
933657
@Override
  protected void setArgs(IndexSchema schema, Map<String, String> args) {
    followIndexAnalyzer = args.get(FOLLOW_INDEX_ANALYZER);
    defaultConfiguration = args.get(DEFAULT_CONFIGURATION);
    configurationFromField = args.get(CONFIGURATION_FROM_FIELD);
    setNumberOfTokens = args.get(SET_NUMBER_OF_TOKENS);
    setNumberOfPositions = args.get(SET_NUMBER_OF_POSITIONS);
    setSize = args.get(SET_SIZE);
    setError = args.get(SET_ERROR);
    setPrefix = args.get(SET_PREFIX);
    setPrefixNumbers = args.get(SET_PREFIX_NUMBERS);
    if (followIndexAnalyzer == null) {
      throw new RuntimeException("No " + FOLLOW_INDEX_ANALYZER
          + " for fieldType " + this.getTypeName());
    }
    args.remove(FOLLOW_INDEX_ANALYZER);
    args.remove(DEFAULT_CONFIGURATION);
    args.remove(CONFIGURATION_FROM_FIELD);
    args.remove(SET_NUMBER_OF_TOKENS);
    args.remove(SET_NUMBER_OF_POSITIONS);
    args.remove(SET_SIZE);
    args.remove(SET_ERROR);
    args.remove(SET_PREFIX);
    args.remove(SET_PREFIX_NUMBERS);
    super.setArgs(schema, args);
  }
123822
public static void main(String[] args) throws Exception {
    if (args.length > 1 || (args.length == 1 && !"-v".equals(args[0]))) {
      System.out.println("USAGE: TransactionServiceClient [-v]");
    }

    boolean verbose = false;
    if (args.length == 1 && "-v".equals(args[0])) {
      verbose = true;
    }
    doMain(verbose, new ConfigurationFactory().get());
  }
335679
@Override
  public void init(IndexSchema schema, Map<String, String> args) {
    args.put(PARSER_IMPL, MtasPreAnalyzedParser.class.getName());
    super.init(schema, args);
  }