Initialize the "fileWatcher" domain.
The fileWatcher domain handles watching and un-watching directories.
3243
function init(domainManager) {
    if (!domainManager.hasDomain("fileWatcher")) {
        domainManager.registerDomain("fileWatcher", {major: 0, minor: 1});
    }

    domainManager.registerCommand(
        "fileWatcher",
        "watchPath",
        watcherManager.watchPath,
        false,
        "Start watching a file or directory",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the file or directory to watch"
        }, {
            name: "ignored",
            type: "array",
            description: "list of path to ignore"
        }]
    );
    domainManager.registerCommand(
        "fileWatcher",
        "unwatchPath",
        watcherManager.unwatchPath,
        false,
        "Stop watching a single file or a directory and it's descendants",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the file or directory to unwatch"
        }]
    );
    domainManager.registerCommand(
        "fileWatcher",
        "unwatchAll",
        watcherManager.unwatchAll,
        false,
        "Stop watching all files and directories"
    );
    domainManager.registerEvent(
        "fileWatcher",
        "change",
        [
            {name: "event", type: "string"},
            {name: "parentDirPath", type: "string"},
            {name: "entryName", type: "string"},
            {name: "statsObj", type: "object"}
        ]
    );

    watcherManager.setDomainManager(domainManager);
    watcherManager.setWatcherImpl(watcherImpl);

}
350289
function initFileLogger(filepath) {
  currentFilePath = filepath || currentFilePath;

  var logDir = path.dirname(currentFilePath);
  appenders.push(logToFile);
  if(!fs.existsSync(logDir)) fs.mkdirSync(logDir);
}
1357287
private void createMonitoringFile() {
        String monitoringDirName = getMonitoringDirName();
        monitoringDir = new File(monitoringDirName);

        File monitoringFile = new File(monitoringDir, gatewayId);
        IoUtil.deleteIfExists(monitoringFile);
        monitorFileWriter.initialize(monitoringFile);
    }
575400
private File updateMonitoredDirectory(String newMonitoredFolder) {

        File oldDir = monitoredDirectory.get();
        File newDir = new File(newMonitoredFolder);

        // If it is relative, resolve against server dir
        if (!!!newDir.isAbsolute()) {
            newMonitoredFolder = locationService.resolveString(WsLocationConstants.SYMBOL_SERVER_CONFIG_DIR + newMonitoredFolder);
            newDir = new File(newMonitoredFolder);
        }

        if (!!!newDir.equals(oldDir)) {
            if (monitoredDirectory.compareAndSet(oldDir, newDir)) {
                for (ServiceReg<FileMonitor> mon : _monitors.values()) {
                    mon.unregister();
                }
                _monitors.clear();

                if (!!!newDir.exists()) {
                    createdMonitoredDir.set(newDir.mkdirs());
                }
            } else {
                oldDir = null;
            }
        } else {
            oldDir = null;
        }

        return oldDir;
    }
1032367
private void initializeLookupCaches()
    {
        for (RuleProvider provider : providers)
        {
            Class<? extends RuleProvider> unproxiedClass = unwrapType(provider.getClass());
            classToProviderMap.put(unproxiedClass, provider);
            idToProviderMap.put(provider.getMetadata().getID(), provider);
        }
    }
1021941
public void initResourceDir (String resourceDir)
    {
        // if none was specified, check the resource_dir system property
        if (resourceDir == null) {
            try {
                resourceDir = System.getProperty("resource_dir");
            } catch (SecurityException se) {
                // no problem
            }
        }

        // if we found no resource directory, don't use one
        if (resourceDir == null) {
            return;
        }

        // make sure there's a trailing slash
        if (!resourceDir.endsWith(File.separator)) {
            resourceDir += File.separator;
        }
        _rdir = new File(resourceDir);
    }
626097
protected void monitorDir(String directory,IOFileFilter filter) throws Exception
	{
		FileAlterationObserver observer=new FileAlterationObserver(directory,filter);
		observer.initialize();
		observer.addListener(fileListener);
		observers.add(observer);
	}
996879
function getWatcher(dir) {
    return function (event, fileName) {
        if (event === "rename") {
            verifyWatches();
            if (fileName) {
                if (!fs.existsSync(dir + fileName)) { return; }
                var dirStat;
                try {
                    dirStat = fs.statSync(dir + fileName);
                } catch (err) {
                    // This means the File disappeared out from under me...
                    return;
                }
                if (dirStat.isDirectory()) {
                    if (!watchingFolders[dir + fileName]) {
                        console.log("Adding new directory to watch: ", dir + fileName);
                        setupWatchers(dir + fileName);
                    }
                    return;
                }
            } else {
                checkForChangedFolders(dir);
            }
            return;
        }

        if (!fileName) {
            fileName = checkForChangedFiles(dir);
            if (fileName) {
                checkCache(fileName);
            }
        }
        else {
            if (isWatching(fileName)) {
                if (!fs.existsSync(dir + fileName)) {
                    return;
                }

                var stat;
                try {
                    stat = fs.statSync(dir + fileName);
                }
                catch (e) {
                    // This means the file disappeared between exists and stat...
                    return;
                }
                if (stat.size === 0) { return; }
                if (timeStamps[dir + fileName] === undefined || timeStamps[dir + fileName] !== stat.mtime.getTime()) {
                    //console.log("Found 2: ", event, dir+fileName, stat.mtime.getTime(), stat.mtime, stat.ctime.getTime(), stat.size);
                    timeStamps[dir + fileName] = stat.mtime.getTime();
                    checkCache(dir + fileName);
                }

            }

        }
    };
}
122679
function watchFilter(fileName) {
  var watchDirectory = this.watchDirectory,//this is array if multiple --watchDirectory options given, treat as array always
      result = true;

  if (!Array.isArray(watchDirectory)) {
    watchDirectory = [watchDirectory];
  }

  watchDirectory.forEach(function(directory) {
    var relFileName = path.relative(directory, fileName),
        length = this.watchIgnorePatterns.length,
        testName,
        i;

    if (this.watchIgnoreDotFiles && path.basename(fileName)[0] === '.') {
      result = false;
    }

    for (i = 0; i < length; i++) {
      if (this.watchIgnorePatterns[i].length > 0) {
        testName = (this.watchIgnorePatterns[i].charAt(0) !== '/') ? relFileName : fileName;
        if (minimatch(testName, this.watchIgnorePatterns[i], { matchBase: directory })) {
          result = false;
        }
      }
    }
  }.bind(this));

  return result;
}
158351
function initialize() {
    switch (this.type) {
      case 'ga':
        ga('create', this.key, this.domain);
        ga('send', 'pageview');
      break;

      case 'segment':
      default:
        window.analytics.load(this.key);
        window.analytics.page();
      break;
    }
  }
675503
@PostConstruct
    public synchronized void initialize() {
        final FwWebDirection direction = assistWebDirection();
        final DoubleSubmitResourceProvider provider = direction.assistDoubleSubmitResourceProvider();
        allowsVerifyTokenBeforeValidation = provider != null && provider.allowsVerifyTokenBeforeValidation();
        showBootLogging();
    }
938754
function init(domainManager) {
    if (!domainManager.hasDomain("extensionManager")) {
        domainManager.registerDomain("extensionManager", {major: 0, minor: 1});
    }
    domainManager.registerCommand(
        "extensionManager",
        "validate",
        validate,
        true,
        "Verifies that the contents of the given ZIP file are a valid Brackets extension package",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the extension package"
        }, {
            name: "options",
            type: "{requirePackageJSON: ?boolean}",
            description: "options to control the behavior of the validator"
        }],
        [{
            name: "errors",
            type: "string|Array.<string>",
            description: "download error, if any; first string is error code (one of Errors.*); subsequent strings are additional info"
        }, {
            name: "metadata",
            type: "{name: string, version: string}",
            description: "all package.json metadata (null if there's no package.json)"
        }]
    );
    domainManager.registerCommand(
        "extensionManager",
        "install",
        _cmdInstall,
        true,
        "Installs the given Brackets extension if it is valid (runs validation command automatically)",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the extension package"
        }, {
            name: "destinationDirectory",
            type: "string",
            description: "absolute filesystem path where this extension should be installed"
        }, {
            name: "options",
            type: "{disabledDirectory: !string, apiVersion: !string, nameHint: ?string, systemExtensionDirectory: !string, proxy: ?string}",
            description: "installation options: disabledDirectory should be set so that extensions can be installed disabled."
        }],
        [{
            name: "errors",
            type: "string|Array.<string>",
            description: "download error, if any; first string is error code (one of Errors.*); subsequent strings are additional info"
        }, {
            name: "metadata",
            type: "{name: string, version: string}",
            description: "all package.json metadata (null if there's no package.json)"
        }, {
            name: "disabledReason",
            type: "string",
            description: "reason this extension was installed disabled (one of Errors.*), none if it was enabled"
        }, {
            name: "installationStatus",
            type: "string",
            description: "Current status of the installation (an extension can be valid but not installed because it's an update"
        }, {
            name: "installedTo",
            type: "string",
            description: "absolute path where the extension was installed to"
        }, {
            name: "commonPrefix",
            type: "string",
            description: "top level directory in the package zip which contains all of the files"
        }]
    );
    domainManager.registerCommand(
        "extensionManager",
        "update",
        _cmdUpdate,
        true,
        "Updates the given Brackets extension (for which install was generally previously attemped). Brackets must be quit after this.",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the extension package"
        }, {
            name: "destinationDirectory",
            type: "string",
            description: "absolute filesystem path where this extension should be installed"
        }, {
            name: "options",
            type: "{disabledDirectory: !string, apiVersion: !string, nameHint: ?string, systemExtensionDirectory: !string}",
            description: "installation options: disabledDirectory should be set so that extensions can be installed disabled."
        }],
        [{
            name: "errors",
            type: "string|Array.<string>",
            description: "download error, if any; first string is error code (one of Errors.*); subsequent strings are additional info"
        }, {
            name: "metadata",
            type: "{name: string, version: string}",
            description: "all package.json metadata (null if there's no package.json)"
        }, {
            name: "disabledReason",
            type: "string",
            description: "reason this extension was installed disabled (one of Errors.*), none if it was enabled"
        }, {
            name: "installationStatus",
            type: "string",
            description: "Current status of the installation (an extension can be valid but not installed because it's an update"
        }, {
            name: "installedTo",
            type: "string",
            description: "absolute path where the extension was installed to"
        }, {
            name: "commonPrefix",
            type: "string",
            description: "top level directory in the package zip which contains all of the files"
        }]
    );
    domainManager.registerCommand(
        "extensionManager",
        "remove",
        _cmdRemove,
        true,
        "Removes the Brackets extension at the given path.",
        [{
            name: "path",
            type: "string",
            description: "absolute filesystem path of the installed extension folder"
        }],
        {}
    );
    domainManager.registerCommand(
        "extensionManager",
        "downloadFile",
        _cmdDownloadFile,
        true,
        "Downloads the file at the given URL, saving it to a temp location. Callback receives path to the downloaded file.",
        [{
            name: "downloadId",
            type: "string",
            description: "Unique identifier for this download 'session'"
        }, {
            name: "url",
            type: "string",
            description: "URL to download from"
        }, {
            name: "proxy",
            type: "string",
            description: "optional proxy URL"
        }],
        {
            type: "string",
            description: "Local path to the downloaded file"
        }
    );
    domainManager.registerCommand(
        "extensionManager",
        "abortDownload",
        _cmdAbortDownload,
        false,
        "Aborts any pending download with the given id. Ignored if no download pending (may be already complete).",
        [{
            name: "downloadId",
            type: "string",
            description: "Unique identifier for this download 'session', previously pased to downloadFile"
        }],
        {
            type: "boolean",
            description: "True if the download was pending and able to be canceled; false otherwise"
        }
    );
}
1144817
public void addWatchDirectory(File dir, List<String> fileExtensions) {
    	List<String> fileExtensionsWithoutDot = new ArrayList<String>(fileExtensions.size());
    	for(String fileExtension : fileExtensions){
    		fileExtensionsWithoutDot.add(removeStartingDotIfPresent(fileExtension));
    	}
    	directoryWatcherDelegate.addWatchDirectory(dir, fileExtensions);
    }
51026
private void doMain() throws Exception {
		// Start the process
		this.start();

		while (true) {
			// look for some terminator
			// attempt to read off queue
			// process message
			// TODO : Make something here, maybe watch for files?
			try {
				Thread.sleep(5);
			} catch (Exception e) {
				log.info("shutting down", e);
				break;
			}
		}

		this.unregisterMBeans();
	}
1289381
def run_watcher(self):
        
        # Create observer
        observer = Observer()

        # Start observer
        observer.start()

        # Dict that maps file path to `watch object`
        watche_obj_map = {}

        # Run change check in a loop
        while not self._watcher_to_stop:
            # Get current watch paths
            old_watch_path_s = set(watche_obj_map)

            # Get new watch paths
            new_watch_path_s = self._find_watch_paths()

            # For each new watch path
            for new_watch_path in new_watch_path_s:
                # Remove from the old watch paths if exists
                old_watch_path_s.discard(new_watch_path)

                # If the new watch path was not watched
                if new_watch_path not in watche_obj_map:
                    try:
                        # Schedule a watch
                        watch_obj = observer.schedule(
                            # 2KGRW
                            # `FileSystemEventHandler` instance
                            self,
                            # File path to watch
                            new_watch_path,
                            # Whether recursive
                            recursive=True,
                        )

                        # Store the watch obj
                        watche_obj_map[new_watch_path] = watch_obj

                    # If have error
                    except OSError:
                        # Set the watch object be None
                        watche_obj_map[new_watch_path] = None

            # For each old watch path that is not in the new watch paths
            for old_watch_path in old_watch_path_s:
                # Get watch object
                watch_obj = watche_obj_map.pop(old_watch_path, None)

                # If have watch object
                if watch_obj is not None:
                    # Unschedule the watch
                    observer.unschedule(watch_obj)

            # Store new watch paths
            self._watch_paths = new_watch_path_s

            # Sleep before next check
            time.sleep(self._interval)
40426
public static boolean init(JobHistoryObserver jobTracker, JobConf conf,
             String hostname, long jobTrackerStartTime){
    try {
      LOG_DIR = conf.get("hadoop.job.history.location" ,
        "file:///" + new File(
        System.getProperty("hadoop.log.dir", "/tmp")).getAbsolutePath()
        + File.separator + "history");
      JOBTRACKER_UNIQUE_STRING = hostname + "_" + 
                                    String.valueOf(jobTrackerStartTime) + "_";
      jobtrackerHostname = hostname;
      Path logDir = new Path(LOG_DIR);
      LOGDIR_FS = logDir.getFileSystem(conf);
      if (!LOGDIR_FS.exists(logDir)){
        if (!LOGDIR_FS.mkdirs(logDir, new FsPermission(HISTORY_DIR_PERMISSION))) {
          throw new IOException("Mkdirs failed to create " + logDir.toString());
        }
      }
      conf.set("hadoop.job.history.location", LOG_DIR);
      disableHistory = false;
      // set the job history block size (default is 3MB)
      jobHistoryBlockSize = 
        conf.getLong("mapred.jobtracker.job.history.block.size", 
                     3 * 1024 * 1024);
      jtConf = conf;

      // initialize the file manager
      fileManager = new JobHistoryFilesManager(conf, jobTracker, logDir);
    } catch(IOException e) {
        LOG.error("Failed to initialize JobHistory log file", e); 
        disableHistory = true;
    }
    fileManager.startIOExecutor();
    return !(disableHistory);
  }
1013074
public DirectoryWatcher newWatcher(String dir) throws IOException {
    return newWatcher(Paths.get(dir), null);
  }