get only a existing file, dont create it

@param sc
@param strDir
@param defaultDir
@param configDir
@param type
@param config
@return existing file
434063
public static Resource getExistingResource(ServletContext sc, String strDir, String defaultDir, Resource configDir, short type, Config config) {
	// ARP

	strDir = replacePlaceholder(strDir, config);
	if (strDir != null && strDir.trim().length() > 0) {
	    Resource res = sc == null ? null : _getExistingFile(config.getResource(ResourceUtil.merge(ReqRspUtil.getRootPath(sc), strDir)), type);
	    if (res != null) return res;

	    res = _getExistingFile(config.getResource(strDir), type);
	    if (res != null) return res;
	}
	if (defaultDir == null) return null;
	return _getExistingFile(configDir.getRealResource(defaultDir), type);

    }
87048
private static Configuration createCfg(TemplateConfig config) {
		if (null == config) {
			config = new TemplateConfig();
		}

		final Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
		cfg.setLocalizedLookup(false);
		cfg.setDefaultEncoding(config.getCharset().toString());

		switch (config.getResourceMode()) {
		case CLASSPATH:
			cfg.setTemplateLoader(new ClassTemplateLoader(ClassUtil.getClassLoader(), config.getPath()));
			break;
		case FILE:
			try {
				cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(config.getPath())));
			} catch (IOException e) {
				throw new IORuntimeException(e);
			}
			break;
		case WEB_ROOT:
			 try {
				 cfg.setTemplateLoader(new FileTemplateLoader(FileUtil.file(FileUtil.getWebRoot(), config.getPath())));
			 } catch (IOException e) {
				 throw new IORuntimeException(e);
			 }
			break;
		case STRING:
			cfg.setTemplateLoader(new SimpleStringTemplateLoader());
			break;
		default:
			break;
		}
		
		return cfg;
	}
1341977
public static DataSource createDataSource(String source, String type, String config){
		DataSourceProvider dsp = dataSourceProviders.get(type);
		if (dsp == null){
			log.error("Unknown data source type for '" + source + "': " + type);
			return null;
		}
		
		DataSource ds = null;
		ds = dsp.createDataSource(source, config);
		if (ds != null){
			log.info("Data source created for: " + source);
		}else{
			log.error("Creation of data source failed for: " + source);
		}
		
		return ds;
	}
888985
public File downloadConfigDir(SolrZkClient zkClient, String configName, File dir)
  throws IOException, InterruptedException, KeeperException {
    Preconditions.checkArgument(dir.exists());
    Preconditions.checkArgument(dir.isDirectory());
    ZkConfigManager manager = new ZkConfigManager(zkClient);
    manager.downloadConfigDir(configName, dir.toPath());
    File confDir = new File(dir, "conf");
    if (!confDir.isDirectory()) {
      // create a temporary directory with "conf" subdir and mv the config in there.  This is
      // necessary because of CDH-11188; solrctl does not generate nor accept directories with e.g.
      // conf/solrconfig.xml which is necessary for proper solr operation.  This should work
      // even if solrctl changes.
      confDir = new File(Files.createTempDir().getAbsolutePath(), "conf");
      confDir.getParentFile().deleteOnExit();
      Files.move(dir, confDir);
      dir = confDir.getParentFile();
    }
    verifyConfigDir(confDir);
    return dir;
  }
1200318
def create_default_file(cls, data=None, mode=None):
        """"""
        filepath = cls.get_default_filepath()
        if not filepath:
            return False

        filename = os.path.basename(filepath)
        config = read_file(get_data_path(), filename)

        # Find and replace data in default config
        data = data or {}
        for k, v in six.iteritems(data):
            v = v or ""
            config = re.sub(
                r"^(%(key)s) =[ ]*$" % {"key": k},
                "%(key)s = %(value)s" % {"key": k, "value": v},
                config,
                flags=re.MULTILINE,
            )

        dirpath = os.path.dirname(filepath)
        if not os.path.exists(dirpath):
            os.makedirs(dirpath)
        with click.open_file(filepath, "w+") as f:
            f.write(config)

        if mode is not None:
            os.chmod(filepath, mode)

        return True
772159
public static function get(string $type): AbstractWriter
    {
        if (!\array_key_exists($type, static::$invokableClasses)) {
            throw new InvalidArgumentException('Unsupported config file type: '.$type);
        }

        return new static::$invokableClasses[$type];
    }
201782
public static <T> CsvWriterDSL<T> from(Type type) {

        ClassMeta<T> classMeta = ReflectionService.newInstance().getClassMeta(type);

        CellWriter cellWriter = CsvCellWriter.DEFAULT_WRITER;

        CsvWriterBuilder<T> builder = CsvWriterBuilder
                .newBuilder(classMeta, cellWriter);

        MapperConfig<CsvColumnKey, ?> mapperConfig = MapperConfig.<CsvColumnKey, CsvRow>fieldMapperConfig();
        try {
            String[] headers = defaultHeaders(classMeta);
            for(String header : headers) {
                builder.addColumn(header);
            }
            ContextualSourceFieldMapperImpl<T, Appendable> mapper = builder.mapper();

            return new DefaultCsvWriterDSL<T>(
                    CsvWriter.<T>toColumnDefinitions(headers),
                    cellWriter,
                    mapper,
                    classMeta,
                    mapperConfig, false);
        } catch (UnsupportedOperationException e) {
            return new NoColumnCsvWriterDSL<T>(
                    cellWriter,
                    classMeta,
                    mapperConfig, false);
        }
    }
1348669
def get_storage_config_file(self):
        
        if self.alternative_config_dir:
            file = os.path.join(self.alternative_config_dir, self.STORAGE_CONFIG_FILE)
            if os.path.isfile(file):
                return file

            file = os.path.join(self.alternative_config_dir, self.STORAGE_JSON_CONFIG_FILE)
            if os.path.isfile(file):
                return file

        file = os.path.join(self.default_config_dir, self.STORAGE_CONFIG_FILE)
        if os.path.isfile(file):
            return file

        file = os.path.join(self.default_config_dir, self.STORAGE_JSON_CONFIG_FILE)
        if os.path.isfile(file):
            return file

        raise ControllerConfigurationException('Storage configuration file not found')
946949
private File getFileFromConfigDirectory(String file, File def) {
        File f = new File(configDirectory, file);
        if (configDirectory != null && f.exists()) {
            return f;
        }
        if (def != null && def.exists()) {
            return def;
        }
        return null;
    }
1025094
INodeFileUnderConstruction addFile(String path,
                String[] names,
                byte[][] components,
                INode[] inodes,
                PermissionStatus permissions,
                short replication,
                long preferredBlockSize,
                String clientName,
                String clientMachine,
                DatanodeDescriptor clientNode,
                long generationStamp,
                long accessTime)
                throws IOException {
    waitForReady();

    // Always do an implicit mkdirs for parent directory tree.
    long modTime = FSNamesystem.now();
    if (inodes[inodes.length-2] == null) { // non-existent directory
      if (!mkdirs(names[names.length-1],
          names, components, inodes, inodes.length-1,
          permissions, true, modTime)) {
        return null;
      }
    } else if (!inodes[inodes.length-2].isDirectory()) {
      NameNode.stateChangeLog.info("DIR* FSDirectory.addFile: "
          + "failed to add " + path + " as its parent is not a directory");
      throw new FileNotFoundException("Parent path is not a directory: " + path);
    }
    
    if (accessTime == -1){
    	accessTime = modTime;
    }
    INodeFileUnderConstruction newNode = new INodeFileUnderConstruction(
                                 allocateNewInodeId(),
                                 permissions,replication,
                                 preferredBlockSize, modTime, accessTime, clientName, 
                                 clientMachine, clientNode);
    newNode.setLocalName(components[inodes.length-1]);
    writeLock();
    try {
      newNode = addChild(inodes, inodes.length-1, newNode, -1, false);
    } finally {
      writeUnlock();
    }
    if (newNode == null) {
      NameNode.stateChangeLog.info("DIR* FSDirectory.addFile: "
                                   +"failed to add "+path
                                   +" to the file system");
      return null;
    }
    // add create file record to log, record new generation stamp
    fsImage.getEditLog().logOpenFile(path, newNode);

    if (NameNode.stateChangeLog.isDebugEnabled()) {
      NameNode.stateChangeLog.debug("DIR* FSDirectory.addFile: "
                                    +path+" is added to the file system");
    }
    
    return newNode;
  }
1069134
public static <T> T readObjectFromFile(String path, Class<T> type, SparkContext sc) throws IOException {
        FileSystem fileSystem = FileSystem.get(sc.hadoopConfiguration());
        try (ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(fileSystem.open(new Path(path))))) {
            Object o;
            try {
                o = ois.readObject();
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }

            return (T) o;
        }
    }
623714
private FileFilter createConfigFilesFilter() {
        SiteConfig config = site.getConfig();
        boolean useDefaultConfigFiles = config.useDefaultConfigFiles();
        if (useDefaultConfigFiles) {
            log.debug("Using default config files.");
            return SiteConfigImpl.DEFAULT_CONFIG_FILES_FILTER;
        } else {//custom config files
            final File[] configFiles = config.getConfigFiles();
            return new FileFilter() {
                @Override
                public boolean accept(File file) {
                    for (File configFile : configFiles) {
                        if (configFile.equals(file)) {
                            return true;
                        }
                    }
                    return false;
                }
            };
        }
    }
441819
protected File getFileRoot(Class type) {
        String path = getGroupsRootPath() + type.getName();
        File f = new File(path);
        return (f.exists()) ? f : null;
    }
1164741
public function getNewFile($type = null)
    {
        $class = $this->getFileModelName($type);
        /** @var ModelFile $file */
        $file = new $class();
        $file->setModel($this);
        $file->setFilesystem($this->getFilesystemDisk());
        return $file;
    }
785276
@Nonnull
  public static FileIOError createDir (@Nonnull final File aDir)
  {
    ValueEnforcer.notNull (aDir, "Directory");

    // Does the directory already exist?
    if (aDir.exists ())
      return EFileIOErrorCode.TARGET_ALREADY_EXISTS.getAsIOError (EFileIOOperation.CREATE_DIR, aDir);

    // Is the parent directory writable?
    final File aParentDir = aDir.getParentFile ();
    if (aParentDir != null && aParentDir.exists () && !aParentDir.canWrite ())
      return EFileIOErrorCode.SOURCE_PARENT_NOT_WRITABLE.getAsIOError (EFileIOOperation.CREATE_DIR, aDir);

    try
    {
      final EFileIOErrorCode eError = aDir.mkdir () ? EFileIOErrorCode.NO_ERROR : EFileIOErrorCode.OPERATION_FAILED;
      return eError.getAsIOError (EFileIOOperation.CREATE_DIR, aDir);
    }
    catch (final SecurityException ex)
    {
      return EFileIOErrorCode.getSecurityAsIOError (EFileIOOperation.CREATE_DIR, ex);
    }
  }
440516
def get_default_config_file(rootdir=None):
    """"""
    if rootdir is None:
        return DEFAULT_CONFIG_FILE

    for path in CONFIG_FILES:
        path = os.path.join(rootdir, path)
        if os.path.isfile(path) and os.access(path, os.R_OK):
            return path
1371892
function getDir (config, name) {
    var base = config.base
    // get list of directories for name
    var dirs = config.dir[name]
    // make sure dirs is array
    if (!Array.isArray(dirs)) {
        dirs = dirs
    }
    // default dir is app base + dir name
    var defaultDir = base+'/'+name
    // if default dir exists then add it
    try {
        // will throw error if dir does not exists
        fs.statSync(defaultDir)
        // add default dir
        dirs.push(defaultDir)
    }
    // ignore errors
    catch (err) {}
    // get only the directories that exist
    config.dir[name] = _.filter(dirs, dir => {
        // if dir is relative then get abs from base
        if (!path.isAbsolute(dir)) {
            // get abs path from base and dir
            dir = base+'/'+dir
        }
        // stat dir
        try {
            var stat = fs.statSync(dir)
        }
        // throw error
        catch (err) {
            throw new Error(name+' dir error: '+err.message)
        }
        // debug
        debug('get dir %s: %s', name, stat ? dir : 'error')
        // return dir if exists or undefined
        return stat ? true : false
    })
    // return directories
    return config.dir[name]
}