Inject an agent if we're on a sun-esque JVM.
194035
@Override public void init(ProcessingEnvironment procEnv) {
		super.init(procEnv);
		String className = procEnv.getClass().getName();
		if (className.startsWith("org.eclipse.jdt.")) {
			errorToShow = "This version of disableCheckedExceptions is not compatible with eclipse. javac only; sorry.";
			procEnv.getMessager().printMessage(Kind.WARNING, errorToShow);
		} else if (!procEnv.getClass().getName().equals("com.sun.tools.javac.processing.JavacProcessingEnvironment")) {
			procEnv.getMessager().printMessage(Kind.WARNING, "You aren't using a compiler based around javac v1.6, so disableCheckedExceptions will not work.\n" +
					"Your processor class is: " + className);
		} else {
			new LiveInjector().inject(ClassRootFinder.findClassRootOfClass(DisableCheckedExceptionsAgent.class));
		}
	}
385480
public void run() throws MojoExecutionException {
    try {
      runMojo
          .getAppEngineFactory()
          .devServerRunSync()
          .run(configBuilder.buildRunConfiguration(processServices(), processProjectId()));
    } catch (AppEngineException ex) {
      throw new MojoExecutionException("Failed to run devappserver", ex);
    }
  }
720797
protected void setup()
    {
        try 
        {
            logger.info("Hostname: {}", InetAddress.getLocalHost().getHostName());
        }
        catch (UnknownHostException e1)
        {
            logger.info("Could not resolve local host");
        }

        long now = System.currentTimeMillis();
        if (now < EARLIEST_LAUNCH_DATE)
        {
            logger.error("current machine time is {}, but that is seemingly incorrect. exiting now.", new Date(now));
            System.exit(3);
        }

        // log warnings for different kinds of sub-optimal JVMs.  tldr use 64-bit Oracle >= 1.6u32
        if (!DatabaseDescriptor.hasLargeAddressSpace())
            logger.info("32bit JVM detected.  It is recommended to run Cassandra on a 64bit JVM for better performance.");
        String javaVersion = System.getProperty("java.version");
        String javaVmName = System.getProperty("java.vm.name");
        logger.info("JVM vendor/version: {}/{}", javaVmName, javaVersion);
        if (javaVmName.contains("OpenJDK"))
        {
            // There is essentially no QA done on OpenJDK builds, and
            // clusters running OpenJDK have seen many heap and load issues.
            logger.warn("OpenJDK is not recommended. Please upgrade to the newest Oracle Java release");
        }
        else if (!javaVmName.contains("HotSpot"))
        {
            logger.warn("Non-Oracle JVM detected.  Some features, such as immediate unmap of compacted SSTables, may not work as intended");
        }
     /*   else
        {
            String[] java_version = javaVersion.split("_");
            String java_major = java_version[0];
            int java_minor;
            try
            {
                java_minor = (java_version.length > 1) ? Integer.parseInt(java_version[1]) : 0;
            }
            catch (NumberFormatException e)
            {
                // have only seen this with java7 so far but no doubt there are other ways to break this
                logger.info("Unable to parse java version {}", Arrays.toString(java_version));
                java_minor = 32;
            }
        }
     */
        logger.info("Heap size: {}/{}", Runtime.getRuntime().totalMemory(), Runtime.getRuntime().maxMemory());
        for(MemoryPoolMXBean pool: ManagementFactory.getMemoryPoolMXBeans())
            logger.info("{} {}: {}", pool.getName(), pool.getType(), pool.getPeakUsage());
        logger.info("Classpath: {}", System.getProperty("java.class.path"));

        // Fail-fast if JNA is not available or failing to initialize properly
        // except with -Dcassandra.boot_without_jna=true. See CASSANDRA-6575.
        if (!CLibrary.jnaAvailable())
        {
            boolean jnaRequired = !Boolean.getBoolean("cassandra.boot_without_jna");

            if (jnaRequired)
            {
                logger.error("JNA failing to initialize properly. Use -Dcassandra.boot_without_jna=true to bootstrap even so.");
                System.exit(3);
            }
        }

        CLibrary.tryMlockall();

        maybeInitJmx();

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler()
        {
            public void uncaughtException(Thread t, Throwable e)
            {
                StorageMetrics.exceptions.inc();
                logger.error("Exception in thread {}", t, e);
                Tracing.trace("Exception in thread {}", t, e);
                for (Throwable e2 = e; e2 != null; e2 = e2.getCause())
                {
                    JVMStabilityInspector.inspectThrowable(e2);

                    if (e2 instanceof FSError)
                    {
                        if (e2 != e) // make sure FSError gets logged exactly once.
                            logger.error("Exception in thread {}", t, e2);
                        FileUtils.handleFSError((FSError) e2);
                    }

                    if (e2 instanceof CorruptSSTableException)
                    {
                        if (e2 != e)
                            logger.error("Exception in thread " + t, e2);
                        FileUtils.handleCorruptSSTable((CorruptSSTableException) e2);
                    }
                }
            }
        });

        // check all directories(data, commitlog, saved cache) for existence and permission
        Iterable<String> dirs = Iterables.concat(Arrays.asList(DatabaseDescriptor.getAllDataFileLocations()),
                                                 Arrays.asList(DatabaseDescriptor.getCommitLogLocation(),
                                                               DatabaseDescriptor.getSavedCachesLocation()));
        for (String dataDir : dirs)
        {
            logger.debug("Checking directory {}", dataDir);
            File dir = new File(dataDir);

            // check that directories exist.
            if (!dir.exists())
            {
                logger.error("Directory {} doesn't exist", dataDir);
                // if they don't, failing their creation, stop cassandra.
                if (!dir.mkdirs())
                {
                    logger.error("Has no permission to create {} directory", dataDir);
                    System.exit(3);
                }
            }
            // if directories exist verify their permissions
            if (!Directories.verifyFullPermissions(dir, dataDir))
            {
                // if permissions aren't sufficient, stop cassandra.
                System.exit(3);
            }
        }

        if (CacheService.instance == null) // should never happen
            throw new RuntimeException("Failed to initialize Cache Service.");

        // check the system keyspace to keep user from shooting self in foot by changing partitioner, cluster name, etc.
        // we do a one-off scrub of the system keyspace first; we can't load the list of the rest of the keyspaces,
        // until system keyspace is opened.
        for (CFMetaData cfm : Schema.instance.getKeyspaceMetaData(Keyspace.SYSTEM_KS).values())
            ColumnFamilyStore.scrubDataDirectories(cfm);
        try
        {
            SystemKeyspace.checkHealth();
        }
        catch (ConfigurationException e)
        {
            logger.error("Fatal exception during initialization", e);
            System.exit(100);
        }

        // load keyspace descriptions.
        DatabaseDescriptor.loadSchemas();

        // clean up compaction leftovers
        Map<Pair<String, String>, Map<Integer, UUID>> unfinishedCompactions = SystemKeyspace.getUnfinishedCompactions();
        for (Pair<String, String> kscf : unfinishedCompactions.keySet())
        {
            CFMetaData cfm = Schema.instance.getCFMetaData(kscf.left, kscf.right);
            // CFMetaData can be null if CF is already dropped
            if (cfm != null)
                ColumnFamilyStore.removeUnfinishedCompactionLeftovers(cfm, unfinishedCompactions.get(kscf));
        }
        SystemKeyspace.discardCompactionsInProgress();

        // clean up debris in the rest of the keyspaces
        for (String keyspaceName : Schema.instance.getKeyspaces())
        {
            // Skip system as we've already cleaned it
            if (keyspaceName.equals(Keyspace.SYSTEM_KS))
                continue;

            for (CFMetaData cfm : Schema.instance.getKeyspaceMetaData(keyspaceName).values())
                ColumnFamilyStore.scrubDataDirectories(cfm);
        }

        Keyspace.setInitialized();
        // initialize keyspaces
        for (String keyspaceName : Schema.instance.getKeyspaces())
        {
            if (logger.isDebugEnabled())
                logger.debug("opening keyspace {}", keyspaceName);
            // disable auto compaction until commit log replay ends
            for (ColumnFamilyStore cfs : Keyspace.open(keyspaceName).getColumnFamilyStores())
            {
                for (ColumnFamilyStore store : cfs.concatWithIndexes())
                {
                    store.disableAutoCompaction();
                }
            }
        }

        if (CacheService.instance.keyCache.size() > 0)
            logger.info("completed pre-loading ({} keys) key cache.", CacheService.instance.keyCache.size());

        if (CacheService.instance.rowCache.size() > 0)
            logger.info("completed pre-loading ({} keys) row cache.", CacheService.instance.rowCache.size());

        try
        {
            GCInspector.register();
        }
        catch (Throwable t)
        {
            JVMStabilityInspector.inspectThrowable(t);
            logger.warn("Unable to start GCInspector (currently only supported on the Sun JVM)");
        }

        // replay the log if necessary
        try
        {
            CommitLog.instance.recover();
        }
        catch (IOException e)
        {
            throw new RuntimeException(e);
        }

        // enable auto compaction
        for (Keyspace keyspace : Keyspace.all())
        {
            for (ColumnFamilyStore cfs : keyspace.getColumnFamilyStores())
            {
                for (final ColumnFamilyStore store : cfs.concatWithIndexes())
                {
                    if (store.getCompactionStrategy().shouldBeEnabled())
                        store.enableAutoCompaction();
                }
            }
        }
        // start compactions in five minutes (if no flushes have occurred by then to do so)
        Runnable runnable = new Runnable()
        {
            public void run()
            {
                for (Keyspace keyspaceName : Keyspace.all())
                {
                    for (ColumnFamilyStore cf : keyspaceName.getColumnFamilyStores())
                    {
                        for (ColumnFamilyStore store : cf.concatWithIndexes())
                            CompactionManager.instance.submitBackground(store);
                    }
                }
            }
        };
        ScheduledExecutors.optionalTasks.schedule(runnable, 5, TimeUnit.MINUTES);

        SystemKeyspace.finishStartup();

        // start server internals
        StorageService.instance.registerDaemon(this);
        try
        {
            StorageService.instance.initServer();
        }
        catch (ConfigurationException e)
        {
            logger.error("Fatal configuration error", e);
            System.err.println(e.getMessage() + "\nFatal configuration error; unable to start server.  See log for stacktrace.");
            System.exit(1);
        }

        Mx4jTool.maybeLoad();

        // Metrics
        String metricsReporterConfigFile = System.getProperty("cassandra.metricsReporterConfigFile");
        if (metricsReporterConfigFile != null)
        {
            logger.info("Trying to load metrics-reporter-config from file: {}", metricsReporterConfigFile);
            try
            {
                String reportFileLocation = CassandraDaemon.class.getClassLoader().getResource(metricsReporterConfigFile).getFile();
                ReporterConfig.loadFromFile(reportFileLocation).enableAll();
            }
            catch (Exception e)
            {
                logger.warn("Failed to load metrics-reporter-config, metric sinks will not be activated", e);
            }
        }

        if (!FBUtilities.getBroadcastAddress().equals(InetAddress.getLoopbackAddress()))
            waitForGossipToSettle();

        // schedule periodic dumps of table size estimates into SystemKeyspace.SIZE_ESTIMATES_CF
        // set cassandra.size_recorder_interval to 0 to disable
        int sizeRecorderInterval = Integer.getInteger("cassandra.size_recorder_interval", 5 * 60);
        if (sizeRecorderInterval > 0)
            ScheduledExecutors.optionalTasks.scheduleWithFixedDelay(SizeEstimatesRecorder.instance, 30, sizeRecorderInterval, TimeUnit.SECONDS);

        // Thrift
        InetAddress rpcAddr = DatabaseDescriptor.getRpcAddress();
        int rpcPort = DatabaseDescriptor.getRpcPort();
        int listenBacklog = DatabaseDescriptor.getRpcListenBacklog();
        thriftServer = new ThriftServer(rpcAddr, rpcPort, listenBacklog);

        // Native transport
        InetAddress nativeAddr = DatabaseDescriptor.getRpcAddress();
        int nativePort = DatabaseDescriptor.getNativeTransportPort();
        nativeServer = new org.apache.cassandra.transport.Server(nativeAddr, nativePort);
    }
848240
function agentCreated(session, err, agent) {
  if (err) throw err

  // save our agent as a global (for `emit()` below)
  Agent = agent

  console.log("agent created: " + JS(agent.info))

  console.log("waiting for echo requests")
  agent.receive("echo", echoRequest)
}
586378
def execute(self):
    

    jvm_resolve_subsystem = JvmResolveSubsystem.global_instance()
    if jvm_resolve_subsystem.get_options().resolver != 'coursier':
      return

    # executor = self.create_java_executor()
    classpath_products = self.context.products.get_data('compile_classpath',
                                                        init_func=ClasspathProducts.init_func(
                                                          self.get_options().pants_workdir))
    executor = self.create_java_executor()
    self.resolve(self.context.targets(), classpath_products, sources=False, javadoc=False, executor=executor)
581823
def inject_mode(arg_namespace):
    """"""

    try:
        injector.inject_into_files(arg_namespace.scheme, arg_namespace.file)
    except (IndexError, FileNotFoundError,
            PermissionError, IsADirectoryError) as exception:
        if isinstance(exception, IndexError):
            print('"{}" has no valid injection marker lines.'.format(
                exception.args[0]))
        if isinstance(exception, FileNotFoundError):
            print('Lacking resource "{}" to complete operation.'.format(
                exception.filename))
        if isinstance(exception, PermissionError):
            print('No write permission for current working directory.')
        if isinstance(exception, IsADirectoryError):
            print('"{}" is a directory. Provide a *.yaml scheme file instead.'
                  .format(exception.filename))
440487
public static void applyUserAgent(String agent) {
    LOGGER.info("Applying agent: " + agent);
    System.setProperty("http.agent", agent);
    System.setProperty("https.agent", agent);
  }
797070
public static boolean loadAgent(URL agentJarURL) throws Exception {
        File toolsJarFile = findToolsJar();
        Class<?> vmClass = null;

        if (toolsJarFile == null || !toolsJarFile.exists()) {
            // likely Java 9+ (when tools.jar is not available).  Java
            // 9 also requires that
            // -Djvm.options=jdk.attach.allowAttachSelf=true is set.
            vmClass = ClassLoader.getSystemClassLoader().loadClass("com.sun.tools.attach.VirtualMachine");
        } else {
            vmClass = loadVirtualMachine(toolsJarFile);
        }

        if (vmClass == null) {
            return false;
        }

        attachAgent(vmClass, agentJarURL);
        return true;
    }
789914
def inject_experiment():
    """"""
    exp = Experiment(session)
    return dict(experiment=exp, env=os.environ)
322519
def _ivy_jvm_options(self, repo):
    """"""
    # Get authentication for the publish repo if needed.
    if not repo.get('auth'):
      # No need to copy here, as this list isn't modified by the caller.
      return self._jvm_options

    # Create a copy of the options, so that the modification is appropriately transient.
    jvm_options = copy(self._jvm_options)
    user = repo.get('username')
    password = repo.get('password')
    if user and password:
      jvm_options.append('-Dlogin={}'.format(user))
      jvm_options.append('-Dpassword={}'.format(password))
    else:
      raise TaskError('Unable to publish to {}. {}'
                      .format(repo.get('resolver'), repo.get('help', '')))
    return jvm_options
230314
function execute() {
  var context = getDefaultContext();
  var compiledOutput = fs.readFileSync(this.outputPath)

  vm.runInContext(compiledOutput, context, this.outputPath);

  var module = extractModule(this.moduleName, context);

  this.compiledModule = context.Elm.fullscreen(module, this.defaults);
}
1005420
public void execute() throws MojoExecutionException, MojoFailureException {
        if(preverifyPath == null) {
            getLog().debug("skip native preverification");
            return;
        }
        
        getLog().debug("start native preverification");

        final File preverifyCmd= getAbsolutePreverifyCommand();
        
        StreamConsumer stdoutLogger= new LogWriter(false);
        StreamConsumer stderrLogger= new LogWriter(true);
        
        String classPath = getClassPath(getProject());
        AbstractConfiguration[] configurations= (AbstractConfiguration[]) getPluginContext().get(ConfiguratorMojo.GENERATED_CONFIGURATIONS_KEY);
        
        for(AbstractConfiguration configuration : configurations) {
            if(!(configuration instanceof NodeConfiguration)) {
                continue;
            }
            
            String classifier= configuration.className.substring(configuration.className.lastIndexOf('.') + 1);
            File oldJar= checkJarFile(classifier);
            
            if(keepJars) {
                try {
                    FileUtils.copyFile(oldJar, getJarFile(classifier + "-before_preverify"));
                } catch (IOException ioe) {
                    getLog().warn("could not keep old jar '" + oldJar.getAbsolutePath() + "'", ioe);
                }
            }
            
            getLog().info("Preverifying jar: " + FileNameUtil.getAbsolutPath(oldJar));
            
            Commandline commandLine= new Commandline(preverifyCmd.getPath() + " -classpath " + classPath + " -d " + FileNameUtil.getAbsolutPath(oldJar.getParentFile()) + " " + FileNameUtil.getAbsolutPath(oldJar));
            getLog().debug(commandLine.toString());
            
            try {
                if(CommandLineUtils.executeCommandLine(commandLine, stdoutLogger, stderrLogger) != 0) {
                    throw new MojoExecutionException("Preverification failed. Please read the log for details.");
                }
            } catch (CommandLineException cle) {
                throw new MojoExecutionException("could not execute preverify command", cle);
            }
        }

        getLog().debug("finished preverification");
    }
57360
@Override
    public boolean applyAction(Model m) {
        Mapping map = m.getMapping();
        if (map.isOnline(node) &&
                map.isRunning(vm) &&
                map.getVMLocation(vm).equals(node)) {
            map.addReadyVM(vm);
            return true;
        }
        return false;
    }
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);

	}
    }
1366074
function injectBefore(replServer, method, beforeFn) {
  var _orig = replServer[method];
  replServer[method] = function() {
    var args = Array.prototype.slice.call(arguments);
    var callback = args.pop();
    beforeFn.apply(null, args.concat(function(err, res) {
      if (err || res) {
        callback(err, res);
      } else {
        _orig.apply(replServer, args.concat(callback));
      }
    }));
  };
  return replServer;
}
1121707
def switch_or_run(cmd, venv_name=None):
    """"""
    if cmd:
        return _run(venv_name, cmd)
    inenv = InenvManager()
    if not os.getenv(INENV_ENV_VAR):
        activator_warn(inenv)
        return
    else:
        venv = inenv.get_prepped_venv(venv_name)
        inenv.clear_extra_source_file()
        inenv.write_extra_source_file("source {}".format(venv.activate_shell_file))
        inenv.write_extra_source_file(override_envars_and_deactivate(inenv.get_envvars(venv_name)))
        if autojump_enabled():
            directory = inenv.guess_contents_dir(venv_name)
            inenv.write_extra_source_file('cd {}'.format(directory))
            click.secho("Jumping to {}".format(directory), fg='green')
        sys.exit(EVAL_EXIT_CODE)
1227644
def set(self, key, value):
        """"""
        # Try to set self._jconf first if JVM is created, set self._conf if JVM is not created yet.
        if self._jconf is not None:
            self._jconf.set(key, unicode(value))
        else:
            self._conf[key] = unicode(value)
        return self