Java Code Examples for java.nio.file.Files#isRegularFile()

The following examples show how to use java.nio.file.Files#isRegularFile() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: org.openntf.domino   File: Logging.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks the existence of the configuration file in IBM_TECHNICAL_SUPPORT/org.openntf.domino.logging.logconfig.properties in Domino
 * data directory.
 *
 * @return configuration file as an instance of a File or null if the file does not exist.
 */
private Path logCfgFilePrecheck() {
	if (_logConfigPropFile == null) {
		_logConfigPropFile = Factory.getDataPath() + "/IBM_TECHNICAL_SUPPORT/org.openntf.domino.logging.logconfig.properties";
	}
	Path ret = Paths.get(_logConfigPropFile);
	String errMsg = null;
	if (!Files.exists(ret)) {
		errMsg = "not found";
	} else if (!Files.isRegularFile(ret)) {
		errMsg = "isn't a normal file";
	}
	if (errMsg == null) {
		return ret;
	}
	System.err.println("Logging.logCfgFilePrecheck: File '" + _logConfigPropFile + "' " + errMsg);
	return null;
}
 
Example 2
Source Project: jbang   File: Settings.java    License: MIT License 6 votes vote down vote up
public static TrustedSources getTrustedSources() {
	if (trustedSources == null) {
		Path trustedSourcesFile = getTrustedSourcesFile();
		if (Files.isRegularFile(trustedSourcesFile)) {
			try {
				trustedSources = TrustedSources.load(trustedSourcesFile);
			} catch (IOException e) {
				Util.warnMsg("Could not read " + trustedSourcesFile);
				trustedSources = new TrustedSources(new String[0]);
			}
		} else {
			trustedSources = new TrustedSources(new String[0]);
		}
	}
	return trustedSources;
}
 
Example 3
public static void main(String[] args) throws IOException {

        if (args.length != 1) {
            System.err.println("Usage AddPackagesAttribute exploded-java-home");
            System.exit(-1);
        }

        String home = args[0];
        Path dir = Paths.get(home, "modules");

        ModuleFinder finder = ModuleFinder.of(dir);

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
            for (Path entry : stream) {
                Path mi = entry.resolve("module-info.class");
                if (Files.isRegularFile(mi)) {
                    String mn = entry.getFileName().toString();
                    Optional<ModuleReference> omref = finder.find(mn);
                    if (omref.isPresent()) {
                        Set<String> packages = omref.get().descriptor().packages();
                        addPackagesAttribute(mi, packages);
                    }
                }
            }
        }
    }
 
Example 4
Source Project: ForgeHax   File: BookBot.java    License: MIT License 5 votes vote down vote up
private BookWriter loadFile() throws RuntimeException {
  if (file.get().isEmpty()) {
    throw new RuntimeException("No file name set");
  }
  
  Path data = getFileManager().getBaseResolve(file.get());
  
  if (!Files.exists(data)) {
    throw new RuntimeException("File not found");
  }
  if (!Files.isRegularFile(data)) {
    throw new RuntimeException("Not a file type");
  }
  
  String text;
  try {
    text = new String(Files.readAllBytes(data), StandardCharsets.UTF_8);
  } catch (IOException e) {
    throw new RuntimeException("Failed to read file");
  }
  
  String name = data.getFileName().toString();
  if (name.endsWith(".txt") || name.endsWith(".book")) {
    return new BookWriter(this, name.endsWith(".txt") ? parseText(text, prettify.get()) : text);
  } else {
    throw new RuntimeException("File is not a .txt or .book type");
  }
}
 
Example 5
Source Project: L2jOrg   File: XmlReader.java    License: GNU General Public License v3.0 5 votes vote down vote up
private Schema loadSchema()  {
    try {
        var schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        var path = getSchemaFilePath();
        if(nonNull(path) && Files.isRegularFile(path)) {
            return schemaFactory.newSchema(path.toFile());
        } else {
            LOGGER.warn("Schema Validation disabled, the path {} is not a file", path);
        }
    } catch (SAXException e) {
        LOGGER.error(e.getLocalizedMessage(), e);
    }
    return null;
}
 
Example 6
Source Project: container   File: FileSystemFile.java    License: Apache License 2.0 5 votes vote down vote up
public FileSystemFile(Path actualPath) {
    super(actualPath.toString());
    if (!Files.isRegularFile(actualPath)) {
        throw new IllegalArgumentException();
    }
    this.actualPath = actualPath;
}
 
Example 7
@Override
public void execute(final Template.Fragment frag, final Writer out) throws IOException {

    final String relativeFileName = AsciidocDocumentationCodegen.sanitize(frag.execute());
    final Path filePathToInclude = Paths.get(basePath, relativeFileName).toAbsolutePath();

    String includeStatement = "include::{" + attributePathReference + "}" + escapeCurlyBrackets(relativeFileName) + "[opts=optional]";
    if (Files.isRegularFile(filePathToInclude)) {
        LOGGER.debug("including " + ++includeCount + ". file into markup from: " + filePathToInclude.toString());
        out.write("\n" + includeStatement + "\n");
    } else {
        LOGGER.debug(++notFoundCount + ". file not found, skip include for: " + filePathToInclude.toString());
        out.write("\n// markup not found, no " + includeStatement + "\n");
    }
}
 
Example 8
Source Project: lucene-solr   File: AnalyzerProfile.java    License: Apache License 2.0 5 votes vote down vote up
private static void init() {
  String dirName = "analysis-data";
  String propName = "analysis.properties";

  // Try the system property:-Danalysis.data.dir=/path/to/analysis-data
  ANALYSIS_DATA_DIR = System.getProperty("analysis.data.dir", "");
  if (ANALYSIS_DATA_DIR.length() != 0)
    return;

  Path[] candidateFiles = new Path[] {
      Paths.get(dirName),
      Paths.get("lib").resolve(dirName),
      Paths.get(propName),
      Paths.get("lib").resolve(propName)
  };
  for (Path file : candidateFiles) {
    if (Files.exists(file)) {
      if (Files.isDirectory(file)) {
        ANALYSIS_DATA_DIR = file.toAbsolutePath().toString();
      } else if (Files.isRegularFile(file) && getAnalysisDataDir(file).length() != 0) {
        ANALYSIS_DATA_DIR = getAnalysisDataDir(file).toString();
      }
      break;
    }
  }

  if (ANALYSIS_DATA_DIR.length() == 0) {
    // Dictionary directory cannot be found.
    throw new RuntimeException("WARNING: Can not find lexical dictionary directory!"
     + " This will cause unpredictable exceptions in your application!"
     + " Please refer to the manual to download the dictionaries.");
  }

}
 
Example 9
Source Project: j2cl   File: J2clCommandLineRunner.java    License: Apache License 2.0 5 votes vote down vote up
private static Path getDirOutput(String output, Problems problems) {
  Path outputPath = Paths.get(output);
  if (Files.isRegularFile(outputPath)) {
    problems.fatal(FatalError.OUTPUT_LOCATION, outputPath);
  }
  return outputPath;
}
 
Example 10
@Override
  protected void execute(Event e) {
Path p = Paths.get(path.getSingle(e));
if (Files.isRegularFile(p)) {
	try {
		lastLoaded = Bukkit.loadServerIcon(p.toFile());
	} catch (NullPointerException | IllegalArgumentException ignored) {
	} catch (Exception ex) {
		Skript.exception(ex);
	}
}
  }
 
Example 11
Source Project: thorntail   File: Swarm.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isFatJar() throws IOException {
    URL location = Swarm.class.getProtectionDomain().getCodeSource().getLocation();
    Path root = null;
    if (location.getProtocol().equals("file")) {
        try {
            root = Paths.get(location.toURI());
        } catch (URISyntaxException e) {
            throw new IOException(e);
        }
    } else if (location.toExternalForm().startsWith("jar:file:")) {
        return true;
    }

    if (Files.isRegularFile(root)) {
        try (JarFile jar = JarFiles.create(root.toFile())) {
            ZipEntry propsEntry = jar.getEntry("META-INF/wildfly-swarm.properties");
            if (propsEntry != null) {
                try (InputStream in = jar.getInputStream(propsEntry)) {
                    Properties props = new Properties();
                    props.load(in);
                    if (props.containsKey(BootstrapProperties.APP_ARTIFACT)) {
                        System.setProperty(BootstrapProperties.APP_ARTIFACT,
                                           props.getProperty(BootstrapProperties.APP_ARTIFACT));
                    }

                    Set<String> names = props.stringPropertyNames();
                    for (String name : names) {
                        String value = props.getProperty(name);
                        if (System.getProperty(name) == null) {
                            System.setProperty(name, value);
                        }
                    }
                }
                return true;
            }
        }
    }

    return false;
}
 
Example 12
DependencyClasspathEntry createCPEntry(Path location) {
  DependencyClasspathEntry entry = null;
  if (Files.isDirectory(location)) {
    entry = ClasspathDirectory.create(location);
  } else if (Files.isRegularFile(location)) {
    try {
      entry = ClasspathJar.create(location);
    } catch (IOException e) {
      // not a zip/jar, ignore
    }
  }
  return entry;
}
 
Example 13
Source Project: hottub   File: PathHandler.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static boolean isJarFile(Path path) {
    if (Files.isRegularFile(path)) {
        String name = path.toString();
        return Utils.endsWithIgnoreCase(name, ".zip")
                || Utils.endsWithIgnoreCase(name, ".jar");
    }
    return false;
}
 
Example 14
Source Project: mnemonic   File: MneDurableInputSession.java    License: Apache License 2.0 5 votes vote down vote up
public void initialize(Path[] paths, String prefix) {
  List<String> fpathlist = new ArrayList<String>();
  for (Path p : paths) {
    if (!Files.isRegularFile(Paths.get(p.toString()), LinkOption.NOFOLLOW_LINKS)) {
      throw new UnsupportedOperationException();
    }
    fpathlist.add(p.toString());
  }
  m_fp_iter = fpathlist.iterator();
  readConfig(prefix);
}
 
Example 15
Source Project: hottub   File: Main.java    License: GNU General Public License v2.0 4 votes vote down vote up
boolean isTidyFile(Path p) {
    return Files.isRegularFile(p) && p.getFileName().toString().endsWith(".tidy");
}
 
Example 16
/** Return true is file identifies a file. */
public boolean isFile() {
    return Files.isRegularFile(file);
}
 
Example 17
/** Return true is file identifies a file. */
public boolean isFile() {
    return Files.isRegularFile(file);
}
 
Example 18
Source Project: buck   File: JavaTest.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Callable<TestResults> interpretTestResults(
    ExecutionContext context,
    SourcePathResolverAdapter pathResolver,
    boolean isUsingTestSelectors) {
  ImmutableSet<String> contacts = getContacts();
  return () -> {
    // It is possible that this rule was not responsible for running any tests because all tests
    // were run by its deps. In this case, return an empty TestResults.
    Set<String> testClassNames = getClassNamesForSources(pathResolver);
    if (testClassNames.isEmpty()) {
      return TestResults.of(
          getBuildTarget(),
          ImmutableList.of(),
          contacts,
          labels.stream().map(Object::toString).collect(ImmutableSet.toImmutableSet()));
    }

    List<TestCaseSummary> summaries = Lists.newArrayListWithCapacity(testClassNames.size());
    for (String testClass : testClassNames) {
      String testSelectorSuffix = "";
      if (isUsingTestSelectors) {
        testSelectorSuffix += ".test_selectors";
      }
      String path = String.format("%s%s.xml", testClass, testSelectorSuffix);
      Path testResultFile =
          getProjectFilesystem()
              .getPathForRelativePath(getPathToTestOutputDirectory().resolve(path));
      if (!isUsingTestSelectors && !Files.isRegularFile(testResultFile)) {
        String message;
        for (JUnitStep junit : Objects.requireNonNull(junits)) {
          if (junit.hasTimedOut()) {
            message = "test timed out before generating results file";
          } else {
            message = "test exited before generating results file";
          }
          summaries.add(
              getTestClassFailedSummary(testClass, message, testRuleTimeoutMs.orElse(0L)));
        }
        // Not having a test result file at all (which only happens when we are using test
        // selectors) is interpreted as meaning a test didn't run at all, so we'll completely
        // ignore it.  This is another result of the fact that JUnit is the only thing that can
        // definitively say whether or not a class should be run.  It's not possible, for example,
        // to filter testClassNames here at the buck end.
      } else if (Files.isRegularFile(testResultFile)) {
        summaries.add(XmlTestResultParser.parse(testResultFile));
      }
    }

    return TestResults.builder()
        .setBuildTarget(getBuildTarget())
        .setTestCases(summaries)
        .setContacts(contacts)
        .setLabels(labels.stream().map(Object::toString).collect(ImmutableSet.toImmutableSet()))
        .addTestLogPaths(getProjectFilesystem().resolve(pathToTestLogs))
        .build();
  };
}
 
Example 19
private static boolean isFileOk(Path path) {
    return Files.isRegularFile(path) && Files.isReadable(path);
}
 
Example 20
Source Project: es6draft   File: SharedFunctions.java    License: MIT License 3 votes vote down vote up
/**
 * Reads a file and evalutes its content.
 * 
 * @param cx
 *            the execution context
 * @param fileName
 *            the file name
 * @param path
 *            the file path
 * @throws ParserException
 *             if the source contains any syntax errors
 * @throws CompilationException
 *             if the parsed source cannot be compiled
 */
static void loadScript(ExecutionContext cx, Path fileName, Path path) throws ParserException, CompilationException {
    if (!Files.isRegularFile(path)) {
        throw new ScriptException(String.format("can't open '%s'", fileName.toString()));
    }
    try {
        ScriptLoading.eval(cx.getRealm(), fileName, path);
    } catch (IOException e) {
        throw Errors.newError(cx, Objects.toString(e.getMessage(), ""));
    }
}