use of java.nio.file.Files in project fess by codelibs.
the class AdminMaintenanceAction method writeLogFiles.
protected void writeLogFiles(final ZipOutputStream zos, final String id) {
final String logFilePath = systemHelper.getLogFilePath();
if (StringUtil.isNotBlank(logFilePath)) {
final Path logDirPath = Paths.get(logFilePath);
try (Stream<Path> stream = Files.list(logDirPath)) {
stream.filter(entry -> isLogFilename(entry.getFileName().toString())).forEach(filePath -> {
final ZipEntry entry = new ZipEntry(id + "/" + filePath.getFileName().toString());
try {
zos.putNextEntry(entry);
final long len = Files.copy(filePath, zos);
if (logger.isDebugEnabled()) {
logger.debug("{}: {}", filePath.getFileName(), len);
}
} catch (final IOException e) {
logger.warn("Failed to access {}", filePath, e);
}
});
} catch (final Exception e) {
logger.warn("Failed to access log files.", e);
}
}
}
use of java.nio.file.Files in project beam by apache.
the class LocalFileSystem method matchOne.
private MatchResult matchOne(String baseDir, String spec) {
if (spec.toLowerCase().startsWith("file:")) {
spec = spec.substring("file:".length());
}
if (SystemUtils.IS_OS_WINDOWS) {
List<String> prefixes = Arrays.asList("///", "/");
for (String prefix : prefixes) {
if (spec.toLowerCase().startsWith(prefix)) {
spec = spec.substring(prefix.length());
}
}
}
// BEAM-6213: Windows breaks on Paths.get(spec).toFile() with a glob because
// it considers it an invalid file system pattern. We should use
// new File(spec) to avoid such validation.
// See https://bugs.openjdk.java.net/browse/JDK-8197918
// However, new File(parent, child) resolves absolute `child` in a system-dependent
// way that is generally incorrect, for example new File($PWD, "/tmp/foo") resolves
// to $PWD/tmp/foo on many systems, unlike Paths.get($PWD).resolve("/tmp/foo") which
// correctly resolves to "/tmp/foo". We add just this one piece of logic here, without
// switching to Paths which could require a rewrite of this module to support
// both Windows and correct file resolution.
// The root cause is that globs are not files but we are using file manipulation libraries
// to work with them.
final File specAsFile = new File(spec);
final File absoluteFile = specAsFile.isAbsolute() ? specAsFile : new File(baseDir, spec);
if (absoluteFile.exists()) {
return MatchResult.create(Status.OK, ImmutableList.of(toMetadata(absoluteFile)));
}
File parent = getSpecNonGlobPrefixParentFile(absoluteFile.getAbsolutePath());
if (!parent.exists()) {
return MatchResult.create(Status.NOT_FOUND, Collections.emptyList());
}
// Method getAbsolutePath() on Windows platform may return something like
// "c:\temp\file.txt". FileSystem.getPathMatcher() call below will treat
// '\' (backslash) as an escape character, instead of a directory
// separator. Replacing backslash with double-backslash solves the problem.
// We perform the replacement on all platforms, even those that allow
// backslash as a part of the filename, because Globs.toRegexPattern will
// eat one backslash.
String pathToMatch = absoluteFile.getAbsolutePath().replaceAll(Matcher.quoteReplacement("\\"), Matcher.quoteReplacement("\\\\"));
final PathMatcher matcher = java.nio.file.FileSystems.getDefault().getPathMatcher("glob:" + pathToMatch);
// TODO: Avoid iterating all files: https://issues.apache.org/jira/browse/BEAM-1309
Iterable<File> files = fileTraverser().depthFirstPreOrder(parent);
Iterable<File> matchedFiles = StreamSupport.stream(files.spliterator(), false).filter(Predicates.and(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.Files.isFile(), input -> matcher.matches(input.toPath()))::apply).collect(Collectors.toList());
List<Metadata> result = Lists.newLinkedList();
for (File match : matchedFiles) {
result.add(toMetadata(match));
}
if (result.isEmpty()) {
// TODO: consider to return Status.OK for globs.
return MatchResult.create(Status.NOT_FOUND, new FileNotFoundException(String.format("No files found for spec: %s in working directory %s", spec, baseDir)));
} else {
return MatchResult.create(Status.OK, result);
}
}
use of java.nio.file.Files in project robolectric by robolectric.
the class ShadowTypeface method createFromAsset.
@Implementation
protected static Typeface createFromAsset(AssetManager mgr, String path) {
ShadowAssetManager shadowAssetManager = Shadow.extract(mgr);
Collection<Path> assetDirs = shadowAssetManager.getAllAssetDirs();
for (Path assetDir : assetDirs) {
Path assetFile = assetDir.resolve(path);
if (Files.exists(assetFile)) {
return createUnderlyingTypeface(path, Typeface.NORMAL);
}
// maybe path is e.g. "myFont", but we should match "myFont.ttf" too?
Path[] files;
try {
files = Fs.listFiles(assetDir, f -> f.getFileName().toString().startsWith(path));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (files.length != 0) {
return createUnderlyingTypeface(path, Typeface.NORMAL);
}
}
throw new RuntimeException("Font asset not found " + path);
}
use of java.nio.file.Files in project es6draft by anba.
the class IntlDataTools method numberingSystems.
static void numberingSystems(Path cldr) throws IOException {
// Late additions? [bali, limb]
LinkedHashSet<String> bcp47Numbers = new LinkedHashSet<>();
Path bcp47 = cldr.resolve("bcp47/number.xml");
try (Reader reader = Files.newBufferedReader(bcp47, StandardCharsets.UTF_8)) {
Document document = document(reader);
elementsByTagName(document, "type").map(type -> type.getAttribute("name")).forEach(bcp47Numbers::add);
}
System.out.println(bcp47Numbers.size());
System.out.println(bcp47Numbers);
LinkedHashSet<String> numberingSystems = new LinkedHashSet<>();
Path supplemental = cldr.resolve("supplemental/numberingSystems.xml");
try (Reader reader = Files.newBufferedReader(supplemental, StandardCharsets.UTF_8)) {
Document document = document(reader);
elementsByTagName(document, "numberingSystem").filter(ns -> !"algorithmic".equals(ns.getAttribute("type"))).peek(ns -> {
assert "numeric".equals(ns.getAttribute("type"));
String digits = ns.getAttribute("digits");
int radix = Character.codePointCount(digits, 0, digits.length());
if (radix != 10) {
System.out.printf("%s - %s [%d]%n", ns.getAttribute("id"), digits, radix);
}
}).map(ns -> ns.getAttribute("id")).forEach(numberingSystems::add);
}
System.out.println(numberingSystems.size());
System.out.println(numberingSystems);
// numberingSystems.forEach(s -> System.out.printf("\"%s\",", s));
TreeSet<String> defaultNames = new TreeSet<>();
TreeSet<String> otherNames = new TreeSet<>();
Files.walk(cldr.resolve("main")).filter(Files::isRegularFile).forEach(p -> {
try (Reader reader = Files.newBufferedReader(p, StandardCharsets.UTF_8)) {
Document document = document(reader);
elementByTagName(document, "numbers").ifPresent(numbers -> {
elementByTagName(numbers, "defaultNumberingSystem").map(Element::getTextContent).ifPresent(defaultNames::add);
elementByTagName(numbers, "otherNumberingSystems").ifPresent(otherNumberingSystems -> {
Stream.of("finance", "native", "traditional").map(name -> elementByTagName(otherNumberingSystems, name)).filter(Optional::isPresent).map(Optional::get).map(Element::getTextContent).forEach(otherNames::add);
});
});
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
System.out.println(defaultNames);
System.out.println(otherNames);
TreeSet<String> allNames = new TreeSet<>();
allNames.addAll(defaultNames);
allNames.addAll(otherNames);
System.out.println(allNames.stream().filter(n -> numberingSystems.contains(n)).collect(Collectors.toList()));
System.out.println(allNames.stream().filter(n -> !numberingSystems.contains(n)).collect(Collectors.toList()));
}
use of java.nio.file.Files in project es6draft by anba.
the class IntlDataTools method oldStyleLanguageTags.
/**
* {@link IntlAbstractOperations#oldStyleLanguageTags}
*
* @param cldrMainDir
* the CLDR directory
* @throws IOException
* if an I/O error occurs
*/
static void oldStyleLanguageTags(Path cldr) throws IOException {
LinkedHashMap<String, String> likelySubtags = new LinkedHashMap<>();
try (Reader reader = Files.newBufferedReader(cldr.resolve("supplemental/likelySubtags.xml"), StandardCharsets.UTF_8)) {
Document document = document(reader);
elementsByTagName(document, "likelySubtag").forEach(likelySubtag -> {
String from = likelySubtag.getAttribute("from").replace('_', '-');
String to = likelySubtag.getAttribute("to").replace('_', '-');
likelySubtags.put(from, to);
});
}
Set<String> allTags = Files.walk(cldr.resolve("main")).filter(Files::isRegularFile).map(Path::getFileName).map(Path::toString).map(p -> p.substring(0, p.indexOf(".xml")).replace('_', '-')).collect(Collectors.toCollection(LinkedHashSet::new));
class Entry implements Comparable<Entry> {
final String tag;
final String languageRegion;
final int priority;
Entry(String tag, String languageRegion, int priority) {
this.tag = tag;
this.languageRegion = languageRegion;
this.priority = priority;
}
@Override
public int compareTo(Entry o) {
int c = languageRegion.compareTo(o.languageRegion);
return c < 0 ? -1 : c > 0 ? 1 : Integer.compare(priority, o.priority);
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Entry) {
return languageRegion.equals(((Entry) obj).languageRegion);
}
return false;
}
@Override
public int hashCode() {
return languageRegion.hashCode();
}
}
Function<Locale, String> toLanguageScript = locale -> new Locale.Builder().setLanguage(locale.getLanguage()).setScript(locale.getScript()).build().toLanguageTag();
Function<Locale, String> toLanguageRegion = locale -> new Locale.Builder().setLanguage(locale.getLanguage()).setRegion(locale.getCountry()).build().toLanguageTag();
Function<Locale, String> toLanguage = locale -> new Locale.Builder().setLanguage(locale.getLanguage()).build().toLanguageTag();
System.out.printf("private static final String[] oldStyleLanguageTags = {%n");
allTags.stream().map(Locale::forLanguageTag).filter(locale -> !locale.getScript().isEmpty() && !locale.getCountry().isEmpty()).filter(locale -> allTags.contains(toLanguageScript.apply(locale))).map(locale -> {
String languageTag = locale.toLanguageTag();
String languageScript = toLanguageScript.apply(locale);
String languageRegion = toLanguageRegion.apply(locale);
String language = toLanguage.apply(locale);
int prio;
if (languageTag.equals(likelySubtags.get(languageScript))) {
prio = 1;
} else if (languageTag.equals(likelySubtags.get(languageRegion))) {
prio = 2;
} else if (languageTag.equals(likelySubtags.get(language))) {
prio = 3;
} else if (likelySubtags.getOrDefault(language, "").startsWith(languageScript)) {
prio = 4;
} else {
prio = 5;
}
return new Entry(languageTag, languageRegion, prio);
}).sorted().distinct().forEach(e -> {
System.out.printf(" \"%s\", \"%s\",%n", e.tag, e.languageRegion);
});
System.out.printf("};%n");
}
Aggregations