Entry point for the agent via -javaagent command line parameter

@param agentArgs
@param inst
329753
public static void premain(String agentArgs, Instrumentation inst) {
        /*
         * To work in OSGI environment we need to expose our packages to the
         * boot ClassLoader
         */
        try {
            String bootDelegation = System.getProperty(OSGI_BOOTDELEGATION_PROPERTY, "");
            if (!bootDelegation.equals("")) {
                bootDelegation += ",";
            }
            bootDelegation += BOOTDELEGATION_PACKAGES;
            System.setProperty(OSGI_BOOTDELEGATION_PROPERTY, bootDelegation);
        } catch (Exception e) {
        }
        
        /*
         * We need to keep the ASM jars off the bootclasspath so we will load
         * our ClassTransformer with our own classloader so that subsequent load
         * of ASM classes are from our packaged jars
         */
        try {
            /*
             * Determine the url to our jar lib folder
             */
            String jarUrl = (Agent.class.getResource("Agent.class").toString());

            int jarIndex = jarUrl.indexOf(JAR_URL);
            if (jarIndex == -1) {
                System.err
                        .println("Javametrics: Unable to start javaagent: Agent class not loaded from jar: " + jarUrl);
                return;
            }

            /*
             * Determine root url and name of our jar
             */
            String libUrl = jarUrl.substring(0, jarIndex);
            int jmIndex = libUrl.lastIndexOf(JAVAMETRICS);
            libUrl = jarUrl.substring(0, jmIndex);
            String jarName = jarUrl.substring(jmIndex, jarIndex + JAR_URL.length());
            URL[] urls = { new URL(libUrl + jarName), new URL(libUrl + ASM_JAR_URL),
                    new URL(libUrl + ASM_COMMONS_JAR_URL) };
            URLClassLoader ucl = new URLClassLoader(urls) {

                /*
                 * (non-Javadoc)
                 * 
                 * @see java.lang.ClassLoader#loadClass(java.lang.String)
                 * 
                 * Find class from our jars first before delegating to parent
                 */
                @Override
                public Class<?> loadClass(String name) throws ClassNotFoundException {
                    try {
                        return findClass(name);
                    } catch (ClassNotFoundException cnf) {
                    }
                    return super.loadClass(name);
                }
            };
            Class<?> cl = ucl.loadClass(CLASSTRANSFORMER_CLASS);

            // Register our class transformer
            inst.addTransformer((ClassFileTransformer) cl.newInstance());

        } catch (NoClassDefFoundError ncdfe) {
            System.err.println("Javametrics: Unable to start javaagent: " + ncdfe);
            ncdfe.printStackTrace();
        } catch (Exception e) {
            System.err.println("Javametrics: Unable to start javaagent: " + e);
            e.printStackTrace();
        }
    }
386301
public void setArgs(java.util.Collection<String> args) {
        if (args == null) {
            this.args = null;
            return;
        }

        this.args = new com.amazonaws.internal.SdkInternalList<String>(args);
    }
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
    }
890509
function RAgent(session, agentInfo) {
  events.EventEmitter.call(this)

  this.info         = utils.roCopy(agentInfo)
  this._session     = session
  this._requestCBs  = new SMap()
  this._subscrCBs   = new SMap()
  this._nextReqID   = utils.sequencer()
}
452039
@Override
    InputStream execute(String cmd, Object ... args) throws AgentLoadException, IOException {
        assert args.length <= 3;                // includes null

        // first check that we are still attached
        int door;
        synchronized (this) {
            if (fd == -1) {
                throw new IOException("Detached from target VM");
            }
            door = fd;
        }

        // enqueue the command via a door call
        int s = enqueue(door, cmd, args);
        assert s >= 0;                          // valid file descriptor

        // The door call returns a file descriptor (one end of a socket pair).
        // Create an input stream around it.
        SocketInputStream sis = new SocketInputStream(s);

        // Read the command completion status
        int completionStatus;
        try {
            completionStatus = readInt(sis);
        } catch (IOException ioe) {
            sis.close();
            throw ioe;
        }

        // If non-0 it means an error but we need to special-case the
        // "load" command to ensure that the right exception is thrown.
        if (completionStatus != 0) {
            sis.close();
            if (cmd.equals("load")) {
                throw new AgentLoadException("Failed to load agent library");
            } else {
                throw new IOException("Command failed in target VM");
            }
        }

        // Return the input stream so that the command output can be read
        return sis;
    }
694950
public static void main(String[] args) {
        try {
            if (args.length == 1 && args[0].endsWith(".properties")) {
                Properties properties = loadProperties(args[0]);
                new StanBench(properties).run();
            } else {
                new StanBench(args).run();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(-1);
        }
        System.exit(0);
    }
1187248
public static void main(String[] args) {

        final InputStream initialInput = new Base64InputStream(System.in);
        final PrintStream initialError = System.err;

        // Make sure our original stdio is properly captured.
        try {
            Class.forName(ConsoleHandler.class.getName(), true, ConsoleHandler.class.getClassLoader());
        } catch (Throwable ignored) {
        }

        // Install JBoss Stdio to avoid any nasty crosstalk.
        StdioContext.install();
        final StdioContext context = StdioContext.create(
            new NullInputStream(),
            new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stdout"), Level.INFO),
            new LoggingOutputStream(org.jboss.logmanager.Logger.getLogger("stderr"), Level.ERROR)
        );
        StdioContext.setStdioContextSelector(new SimpleStdioContextSelector(context));

        final byte[] asAuthBytes = new byte[ProcessController.AUTH_BYTES_ENCODED_LENGTH];
        try {
            StreamUtils.readFully(initialInput, asAuthBytes);
        } catch (IOException e) {
            e.printStackTrace();
            SystemExiter.abort(ExitCodes.FAILED);
            throw new IllegalStateException(); // not reached
        }

        final MarshallerFactory factory = Marshalling.getMarshallerFactory("river", DomainServerMain.class.getClassLoader());
        final Unmarshaller unmarshaller;
        final ByteInput byteInput;
        final AsyncFuture<ServiceContainer> containerFuture;
        try {
            Module.registerURLStreamHandlerFactoryModule(Module.getBootModuleLoader().loadModule(ModuleIdentifier.create("org.jboss.vfs")));
            final MarshallingConfiguration configuration = new MarshallingConfiguration();
            configuration.setVersion(2);
            configuration.setClassResolver(new SimpleClassResolver(DomainServerMain.class.getClassLoader()));
            unmarshaller = factory.createUnmarshaller(configuration);
            byteInput = Marshalling.createByteInput(initialInput);
            unmarshaller.start(byteInput);
            final ServerTask task = unmarshaller.readObject(ServerTask.class);
            unmarshaller.finish();
            containerFuture = task.run(Arrays.<ServiceActivator>asList(new ServiceActivator() {
                @Override
                public void activate(final ServiceActivatorContext serviceActivatorContext) {
                    // TODO activate host controller client service
                }
            }));
        } catch (Throwable t) {
            t.printStackTrace(initialError);
            SystemExiter.abort(ExitCodes.FAILED);
            throw new IllegalStateException(); // not reached
        }

        Throwable caught = null;
        for (;;) {
            try {
                final String scheme = StreamUtils.readUTFZBytes(initialInput);
//                String scheme = "remote";
                final String hostName = StreamUtils.readUTFZBytes(initialInput);
                final int port = StreamUtils.readInt(initialInput);
                final boolean managementSubsystemEndpoint = StreamUtils.readBoolean(initialInput);
                final byte[] authBytes = new byte[ProcessController.AUTH_BYTES_ENCODED_LENGTH];
                StreamUtils.readFully(initialInput, authBytes);
                final String authKey = new String(authBytes, Charset.forName("US-ASCII"));
                URI hostControllerUri = new URI(scheme, null, NetworkUtils.formatPossibleIpv6Address(hostName), port, null, null, null);
                // Get the host-controller server client
                final ServiceContainer container = containerFuture.get();
                if (!container.isShutdown()) {
                    // otherwise, ServiceNotFoundException or IllegalStateException is thrown because HostControllerClient is stopped
                    final HostControllerClient client = getRequiredService(container,
                            HostControllerConnectionService.SERVICE_NAME, HostControllerClient.class);
                    // Reconnect to the host-controller
                    client.reconnect(hostControllerUri, authKey, managementSubsystemEndpoint);
                }

            } catch (InterruptedIOException e) {
                Thread.interrupted();
                // ignore
            } catch (EOFException e) {
                // this means it's time to exit
                break;
            } catch (Throwable t) {
                t.printStackTrace();
                caught = t;
                break;
            }
        }

        // Once the input stream is cut off, shut down
        // We may be attempting a graceful shutdown, in which case we need to wait
        final ServiceContainer container;
        try {
            container = containerFuture.get();
            ServiceController<?> controller = container.getService(GracefulShutdownService.SERVICE_NAME);
            if(controller != null) {
                ((GracefulShutdownService)controller.getValue()).awaitSuspend();
            }
        } catch (InterruptedException ie) {
            // ignore this and exit
        } catch (Throwable  t) {
            t.printStackTrace();
        } finally {
            if (caught == null) {
                SystemExiter.logAndExit(ServerLogger.ROOT_LOGGER::shuttingDownInResponseToProcessControllerSignal, ExitCodes.NORMAL);
            } else {
                SystemExiter.abort(ExitCodes.FAILED);
            }
        }
        throw new IllegalStateException(); // not reached
    }
99331
public static void main(final String[] args) throws InjectionException, IOException {

    final JavaConfigurationBuilder driverConfigBuilder = TANG.newConfigurationBuilder(STATIC_DRIVER_CONFIG);

    new CommandLine(driverConfigBuilder)
        .registerShortNameOfClass(Command.class)
        .registerShortNameOfClass(NumEvaluators.class)
        .registerShortNameOfClass(RuntimeName.class)
        .processCommandLine(args);

    final Configuration driverConfig = driverConfigBuilder.build();

    final Injector injector = TANG.newInjector(driverConfig);

    final int numEvaluators = injector.getNamedInstance(NumEvaluators.class);
    final String runtimeName = injector.getNamedInstance(RuntimeName.class);
    final String command = injector.getNamedInstance(Command.class);

    LOG.log(Level.INFO, "REEF distributed shell: {0} evaluators on {1} runtime :: {2}",
        new Object[] {numEvaluators, runtimeName, command});

    final Configuration runtimeConfig;

    switch (runtimeName) {
    case "local":
      runtimeConfig = LocalRuntimeConfiguration.CONF
          .set(LocalRuntimeConfiguration.MAX_NUMBER_OF_EVALUATORS, numEvaluators)
          .build();
      break;
    case "yarn":
      runtimeConfig = YarnClientConfiguration.CONF.build();
      break;
    default:
      LOG.log(Level.SEVERE, "Unknown runtime: {0}", runtimeName);
      throw new IllegalArgumentException("Unknown runtime: " + runtimeName);
    }

    final LauncherStatus status = DriverLauncher.getLauncher(runtimeConfig).run(driverConfig, JOB_TIMEOUT);

    LOG.log(Level.INFO, "REEF job completed: {0}", status);
  }
708395
public void processArguments(String[] args) throws IOException {
        List<File> classFiles = new ArrayList<File>();
        List<File> jarFiles = new ArrayList<File>();
        String[] fileArgs = null;

        for (int i = 0; i < args.length; i++) {
            if (args[i].equalsIgnoreCase("--config")) {
                configFileParser = new TraceConfigFileParser(new File(args[++i]));
                configFileParser.parse();
                InstrumentationOptions options = configFileParser.getInstrumentationOptions();
                if (options.getAddFFDC()) {
                    setInstrumentWithFFDC(true);
                }
                setTraceType(options.getTraceType());
                setInstrumentationOptions(options);
            } else if (args[i].equalsIgnoreCase("--debug") || args[i].equals("-d")) {
                setDebug(true);
            } else if (args[i].equalsIgnoreCase("--tr")) {
                setTraceType(TraceType.TR);
            } else if (args[i].equalsIgnoreCase("--websphere")) {
                setTraceType(TraceType.TR);
            } else if (args[i].equalsIgnoreCase("--java-logging")) {
                setTraceType(TraceType.JAVA_LOGGING);
            } else if (args[i].equalsIgnoreCase("--jsr47")) {
                setTraceType(TraceType.JAVA_LOGGING);
            } else if (args[i].equalsIgnoreCase("--none")) {
                setTraceType(TraceType.NONE);
            } else if (args[i].equalsIgnoreCase("--no-trace")) {
                setTraceType(TraceType.NONE);
            } else if (args[i].equalsIgnoreCase("--ffdc")) {
                setInstrumentWithFFDC(true);
            } else if (args[i].equalsIgnoreCase("--compute-frames")) {
                setComputeFrames(true);
            } else {
                fileArgs = new String[args.length - i];
                System.arraycopy(args, i, fileArgs, 0, fileArgs.length);
                break;
            }
        }

        if (fileArgs == null || fileArgs.length == 0) {
            throw new IllegalArgumentException("Empty file lists are illegal");
        }

        for (int i = 0; i < fileArgs.length; i++) {
            File f = new File(fileArgs[i]);
            if (!f.exists()) {
                throw new IllegalArgumentException(f + " does not exist");
            } else if (f.isDirectory()) {
                classFiles.addAll(getClassFiles(f, null));
            } else if (f.getName().endsWith(".class")) {
                classFiles.add(f);
            } else if (f.getName().endsWith(".jar")) {
                jarFiles.add(f);
            } else if (f.getName().endsWith(".zip")) {
                jarFiles.add(f);
            } else {
                System.err.println(f + " is an unexpected file type; ignoring");
            }
        }

        setClassFiles(classFiles);
        setJarFiles(jarFiles);
    }
350045
public static void main(String[] arg) {

        System.getProperties().put("sun.java2d.noddraw", "true");

        // (ulrivo): read all arguments from the command line
        String  lowerArg;
        String  urlid        = null;
        String  rcFile       = null;
        boolean autoConnect  = false;
        boolean urlidConnect = false;

        bMustExit = true;

        for (int i = 0; i < arg.length; i++) {
            lowerArg = arg[i].toLowerCase();

            if (lowerArg.startsWith("--")) {
                lowerArg = lowerArg.substring(1);
            }

            i++;

            if (i == arg.length) {
                showUsage();

                return;
            }

            if (lowerArg.equals("-driver")) {
                defDriver   = arg[i];
                autoConnect = true;
            } else if (lowerArg.equals("-url")) {
                defURL      = arg[i];
                autoConnect = true;
            } else if (lowerArg.equals("-user")) {
                defUser     = arg[i];
                autoConnect = true;
            } else if (lowerArg.equals("-password")) {
                defPassword = arg[i];
                autoConnect = true;
            } else if (lowerArg.equals("-urlid")) {
                urlid        = arg[i];
                urlidConnect = true;
            } else if (lowerArg.equals("-rcfile")) {
                rcFile       = arg[i];
                urlidConnect = true;
            } else if (lowerArg.equals("-dir")) {
                defDirectory = arg[i];
            } else if (lowerArg.equals("-script")) {
                defScript = arg[i];
            } else if (lowerArg.equals("-noexit")) {
                bMustExit = false;

                i--;
            } else if (lowerArg.equals("-help")) {
                showUsage();

                return;
            } else {
                /* Syntax ERRORS should either throw or exit with non-0 status.
                 * In our case, it may be unsafe to exit, so we throw.
                 * (I.e. should provide easy way for caller to programmatically
                 * determine that there was an invocation problem).
                 */
                throw new IllegalArgumentException(
                    "Try:  java... " + DatabaseManagerSwing.class.getName()
                    + " --help");

                // No reason to localize, since the main syntax message is
                // not localized.
            }
        }

        DatabaseManager m = new DatabaseManager();

        m.main();

        Connection c = null;

        try {
            if (autoConnect && urlidConnect) {
                throw new IllegalArgumentException(
                    "You may not specify both (urlid) AND (url/user/password).");
            }

            if (autoConnect) {
                c = ConnectionDialog.createConnection(defDriver, defURL,
                                                      defUser, defPassword);
            } else if (urlidConnect) {
                if (urlid == null) {
                    throw new IllegalArgumentException(
                        "You must specify an 'urlid' to use an RC file");
                }

                autoConnect = true;

                if (rcFile == null) {
                    rcFile = DEFAULT_RCFILE;
                }

                c = new RCData(new File(rcFile), urlid).getConnection(null,
                               System.getProperty("sqlfile.charset"),
                               System.getProperty("javax.net.ssl.trustStore"));
            } else {
                c = ConnectionDialog.createConnection(m.fMain, "Connect");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (c == null) {
            return;
        }

        m.connect(c);
    }
447756
public static void createAgent (
        ClientObject target, int arg1)
    {
        sendNotification(
            target, BureauDecoder.RECEIVER_CODE, BureauDecoder.CREATE_AGENT,
            new Object[] { Integer.valueOf(arg1) });
    }
1113973
def start_agent(agent, recp, desc, allocation_id=None, *args, **kwargs):
    '''
    
    '''
    f = fiber.Fiber()
    f.add_callback(agent.initiate_protocol, IRecipient(recp), desc,
                   allocation_id, *args, **kwargs)
    f.add_callback(StartAgentRequester.notify_finish)
    f.succeed(StartAgentRequester)
    return f
592430
public void init(String[] args)
    {
        BaseApplet applet = null;
        if (!gbStandAlone)
            applet = this;
        if (m_application == null)
        {
            Map<String,Object> properties = null;
            if (args != null)
            {
                properties = new Hashtable<String,Object>();
                Util.parseArgs(properties, args);
            }
            m_application = new ThinApplication(null, properties, applet);      // Start the session for this user
        }
        m_application.addTask(this, null);                    // Add this session to the list
        
        m_recordOwnerCollection = new RecordOwnerCollection(this);

        try   {	// Add browser connection if running as an applet
            Class.forName("netscape.javascript.JSObject"); // Test if this exists
            Map<String,Object> mapInitialCommand = new HashMap<String,Object>();
            String strInitialCommand = this.getInitialCommand(true);
            if ((strInitialCommand != null) && (strInitialCommand.length() > 0))
            	Util.parseArgs(mapInitialCommand, strInitialCommand);
            BrowserManager bm = new BrowserManager(this, mapInitialCommand);	// This will throw an exception if there is a no browser
            this.setBrowserManager(bm);
        } catch (Exception ex)  { // Ignore if no browser
        }
        if (m_application.getProperty("hash") != null)
        {	// Special case - html hash params get added (and override) initial params
            Map<String,Object> properties = this.getProperties();
            if (properties == null)
            	properties = new Hashtable<String,Object>();
        	Util.parseArgs(properties, m_application.getProperty("hash"));
        	this.setProperties(properties);
        }
        m_parent = this.addBackground(this);
        this.addSubPanels(m_parent, Constants.DONT_PUSH_TO_BROWSER);    // Add any sub-panels now

        this.setupLookAndFeel(null);
        
        if (this.getBrowserManager() != null)
        	if ((this.getClass().getName().indexOf(".thin.") != -1) || (this.getClass().getName().indexOf(".Thin") != -1))
        		this.repaint();		// HACK - On thin if this is in an applet window, the paint sequence displays the overlays backward
    }
977454
public void run(final String[] args) throws CLIToolException {
        PropertyConfigurator.configure(Constants.getLog4jPropertiesFile().getAbsolutePath());
        CommandLine cli = parseArgs(args);
        validateOptions(cli,args);
        go();
    }
625499
private void initMode(Map<String, String> agentConfig) {
        String mode = agentConfig.get("mode");
        if (mode != null && !mode.equals("start") && !mode.equals("stop")) {
            throw new IllegalArgumentException("Invalid running mode '" + mode + "'. Must be either 'start' or 'stop'");
        }
        isStopMode = "stop".equals(mode);
    }
623597
public static void main(final String[] args) throws BindException, InjectionException {

    final Tang tang = Tang.Factory.getTang();

    final JavaConfigurationBuilder cb = tang.newConfigurationBuilder();

    try{
      new CommandLine(cb)
          .registerShortNameOfClass(NodeListFilePath.class)
          .registerShortNameOfClass(SshPortNum.class)
          .processCommandLine(args);
    } catch(final IOException ex) {
      LOG.log(Level.SEVERE, "Missing parameter 'nodelist' or wrong parameter input.");
      throw new RuntimeException("Missing parameter 'nodelist' or wrong parameter input: ", ex);
    }

    final Injector injector = tang.newInjector(cb.build());

    final String nodeListFilePath = injector.getNamedInstance(NodeListFilePath.class);
    final int sshPortNum = injector.getNamedInstance(SshPortNum.class);

    final Configuration runtimeConf = getRuntimeConfiguration(nodeListFilePath, sshPortNum);
    final Configuration driverConf = getDriverConfiguration();

    final LauncherStatus status = DriverLauncher
        .getLauncher(runtimeConf)
        .run(driverConf, JOB_TIMEOUT);
    LOG.log(Level.INFO, "REEF job completed: {0}", status);
  }
770761
public static void main(String[] args) {
    ProcessEntryPoint entryPoint = ProcessEntryPoint.createForArguments(args);
    Props props = entryPoint.getProps();
    new CeProcessLogging().configure(props);
    CeServer server = new CeServer(
      new ComputeEngineImpl(props, new ComputeEngineContainerImpl()),
      new MinimumViableSystem());
    entryPoint.launch(server);
  }