下面列出了java.nio.file.Path#resolveSibling ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private AbstractExecutionStep createRenameAssetLibrariesStep(
APKModule module,
ImmutableSortedSet.Builder<Path> inputAssetLibrariesBuilder,
ImmutableList.Builder<Path> outputAssetLibrariesBuilder) {
return new AbstractExecutionStep("rename_asset_libraries_as_temp_files_" + module.getName()) {
@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
ProjectFilesystem filesystem = getProjectFilesystem();
for (Path libPath : inputAssetLibrariesBuilder.build()) {
Path tempPath = libPath.resolveSibling(libPath.getFileName() + "~");
filesystem.move(libPath, tempPath);
outputAssetLibrariesBuilder.add(tempPath);
}
return StepExecutionResults.SUCCESS;
}
};
}
@Nullable
@CheckReturnValue
private NominalType resolveModuleType(String pathStr) {
Path path = resolveModulePath(pathStr);
NominalType type = resolveModuleType(path);
if (type != null) {
return type;
}
String baseName = Files.getNameWithoutExtension(path.getFileName().toString());
int index = baseName.indexOf('.');
if (index != -1) {
path = path.resolveSibling(baseName.substring(0, index) + ".js");
if (typeRegistry.isModule(path)) {
Module module = typeRegistry.getModule(path);
String typeName = module.getId() + baseName.substring(index);
if (typeRegistry.isType(typeName)) {
return typeRegistry.getType(typeName);
}
}
}
return null;
}
@Test
public void suppressStartupForKeygenOptionWithFileOutputOptions() throws Exception {
final KeyGenerator keyGenerator = MockKeyGeneratorFactory.getMockKeyGenerator();
Path publicKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
Path privateKeyPath = Files.createTempFile(UUID.randomUUID().toString(), "");
Files.write(privateKeyPath, Arrays.asList("SOMEDATA"));
Files.write(publicKeyPath, Arrays.asList("SOMEDATA"));
FilesystemKeyPair keypair = new FilesystemKeyPair(publicKeyPath, privateKeyPath, null);
when(keyGenerator.generate(anyString(), eq(null), eq(null))).thenReturn(keypair);
final Path configFile = createAndPopulatePaths(getClass().getResource("/sample-config.json"));
final Path configOutputPath = configFile.resolveSibling(UUID.randomUUID().toString() + ".json");
final CliResult cliResult =
cliDelegate.execute(
"-keygen", "-configfile", configFile.toString(), "-output", configOutputPath.toString());
assertThat(cliResult.isSuppressStartup()).isTrue();
}
@Test
public void testRenameFile() throws IOException {
// Create a temp folder
Path tempDirectory = Files.createTempDirectory("halo-test");
Path testPath = tempDirectory.resolve("test/test");
Path filePath = tempDirectory.resolve("test/test/test.file");
// Create a temp file and folder
Files.createDirectories(testPath);
Files.createFile(filePath);
// Write content to the temp file
String content = "Test Content!\n";
Files.write(filePath, content.getBytes());
// Rename temp file
FileUtils.rename(filePath, "newName");
Path newPath = filePath.resolveSibling("newName");
Assert.assertFalse(Files.exists(filePath));
Assert.assertTrue(Files.isRegularFile(newPath));
Assert.assertEquals(new String(Files.readAllBytes(newPath)), content);
FileUtils.deleteFolder(tempDirectory);
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException
{
if (!CacheUtil.isMetadataFile(file.toString(), conf)) {
totalCacheFiles++;
Path mdFile = file.resolveSibling(file.getFileName() + metadataFileSuffix);
if (Files.exists(mdFile)) {
successes++;
}
else {
filesWithoutMd.add(file.toString());
}
}
return super.visitFile(file, attrs);
}
/**
* (Private) constructor.
* <p>
* NOTA: The provided samples file is not accessed before {@link #loadRepository()} or
* {@link storeRepository()} is called.
*
* @param samplesFile path to the samples archive file.
*/
private SampleRepository (Path samplesFile)
{
final Path fileName = samplesFile.getFileName();
final Matcher matcher = SAMPLES_PATTERN.matcher(fileName.toString());
if (!matcher.find()) {
throw new IllegalArgumentException("Illegal samples archive name: " + samplesFile);
}
String prefix = matcher.group(1);
if (prefix == null) {
prefix = "";
}
bookRadix = prefix.isEmpty() ? "" : prefix.substring(0, prefix.length() - 1);
this.samplesFile = samplesFile;
this.imagesFile = samplesFile.resolveSibling(prefix + IMAGES_FILE_NAME);
// Set application exit listener
if (OMR.gui != null) {
OmrGui.getApplication().addExitListener(getExitListener());
}
}
@Override
public void backup(String filename) throws IOException {
String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd.HHmmss"));
Path path = directory.resolve(filename);
if (Files.exists(path)) {
Path dest = path.resolveSibling("backup-" + filename + "-" + time);
org.terracotta.utilities.io.Files.relocate(path, dest);
}
}
private static Optional<Path> maybeResolvePath(Path reference, String pathStr) {
// 1. Path resolves to another module exactly.
Path path = reference.resolveSibling(pathStr + ".js");
if (exists(path)) {
return Optional.of(path);
}
// 2. Path resolves to a directory with an index.js file.
path = reference.resolveSibling(pathStr);
if (isDirectory(path) && exists(path.resolve("index.js"))) {
return Optional.of(path.resolve("index"));
}
return Optional.empty();
}
/**
* JavaBeanオブジェクトをXML形式でファイルに書き込みます
*
* @param path ファイル
* @param obj JavaBean
* @throws IOException IOException
*/
public static void writeObject(Path path, Object obj) throws IOException {
if (Files.exists(path)) {
if (Files.isDirectory(path)) {
throw new IOException("File '" + path + "' exists but is a directory");
}
if (!Files.isWritable(path)) {
throw new IOException("File '" + path + "' cannot be written to");
}
} else {
Path parent = path.getParent();
if (parent != null) {
if (!Files.exists(parent)) {
Files.createDirectories(parent);
}
}
}
Path backup = path.resolveSibling(path.getFileName() + ".backup");
if (Files.exists(path) && (Files.size(path) > 0)) {
// ファイルが存在してかつサイズが0を超える場合、ファイルをバックアップにリネームする
Files.move(path, backup, StandardCopyOption.REPLACE_EXISTING);
}
try (XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(Files.newOutputStream(path,
StandardOpenOption.CREATE)))) {
encoder.setExceptionListener(e -> {
Class<?> clazz = null;
if (obj != null) {
clazz = obj.getClass();
}
LoggerHolder.LOG.warn("File '" + path + "', Bean Class '" + clazz + "' の書き込み時に例外", e);
});
encoder.writeObject(obj);
}
}
@Test
public void testResolveModuleTypeReference_pathResolvesToExportedType() throws IOException {
Path ref = path("a/b/c.js");
Path dir = ref.resolveSibling("d/e");
createDirectories(dir);
Path indexFile = dir.resolve("index.js");
createFile(indexFile);
Path otherFile = dir.resolve("foo.bar.js");
createFile(otherFile);
assertThat(resolveModuleTypeReference(ref, "./d/e.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "./d/../d/e.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "../b/d/e.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "./d/e.Foo.Bar"))
.isEqualTo(getModuleId(indexFile) + ".Foo.Bar");
assertThat(resolveModuleTypeReference(ref, "./d/e/index.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "./d/../d/e/index.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "../b/d/e/index.Foo"))
.isEqualTo(getModuleId(indexFile) + ".Foo");
assertThat(resolveModuleTypeReference(ref, "./d/e/index.Foo.Bar"))
.isEqualTo(getModuleId(indexFile) + ".Foo.Bar");
assertThat(resolveModuleTypeReference(ref, "./d/e/foo.bar.Baz"))
.isEqualTo(getModuleId(otherFile) + ".Baz");
assertThat(resolveModuleTypeReference(ref, "./d/../d/e/foo.bar.Baz"))
.isEqualTo(getModuleId(otherFile) + ".Baz");
assertThat(resolveModuleTypeReference(ref, "../b/d/e/foo.bar.Baz"))
.isEqualTo(getModuleId(otherFile) + ".Baz");
}
private void common(RequestMetaData request, ResponseMetaData response) throws IOException {
String uri = request.getRequestURI();
Path dir = Paths.get(AppConfig.get().getResourcesDir(), "common");
Path path = dir.resolve(Paths.get(URI.create(uri).getPath()).getFileName());
if (response.getResponseBody().isPresent()) {
this.write(response.getResponseBody().get(), path);
String filename = String.valueOf(path.getFileName());
// pngファイル
Path pngPath = null;
// jsonファイル
Path jsonPath = null;
// jsonファイルの場合
if (filename.endsWith(".json")) {
pngPath = path.resolveSibling(filename.replace(".json", ".png"));
jsonPath = path;
}
// pngファイルの場合
if (filename.endsWith(".png")) {
pngPath = path;
jsonPath = path.resolveSibling(filename.replace(".png", ".json"));
}
// 分解した画像の格納先
Path spriteDir = pngPath.resolveSibling(filename.substring(0, filename.lastIndexOf('.')));
this.sprite(spriteDir, pngPath, jsonPath);
}
}
private void saveProjectAs() {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(true);
String[] exts = { JadxProject.PROJECT_EXTENSION };
String description = "supported files: " + Arrays.toString(exts).replace('[', '(').replace(']', ')');
fileChooser.setFileFilter(new FileNameExtensionFilter(description, exts));
fileChooser.setToolTipText(NLS.str("file.save_project"));
Path currentDirectory = settings.getLastSaveProjectPath();
if (currentDirectory != null) {
fileChooser.setCurrentDirectory(currentDirectory.toFile());
}
int ret = fileChooser.showSaveDialog(mainPanel);
if (ret == JFileChooser.APPROVE_OPTION) {
settings.setLastSaveProjectPath(fileChooser.getCurrentDirectory().toPath());
Path path = fileChooser.getSelectedFile().toPath();
if (!path.getFileName().toString().toLowerCase(Locale.ROOT).endsWith(JadxProject.PROJECT_EXTENSION)) {
path = path.resolveSibling(path.getFileName() + "." + JadxProject.PROJECT_EXTENSION);
}
if (Files.exists(path)) {
int res = JOptionPane.showConfirmDialog(
this,
NLS.str("confirm.save_as_message", path.getFileName()),
NLS.str("confirm.save_as_title"),
JOptionPane.YES_NO_OPTION);
if (res == JOptionPane.NO_OPTION) {
return;
}
}
project.saveAs(path);
update();
}
}
@Test
public void testReadFromFile() throws IOException {
Path tempDir = super.newTempDir();
Path dict = tempDir.resolve("odd name.dict");
Path info = dict.resolveSibling("odd name.info");
try (InputStream dictInput = this.getClass().getResource("test-infix.dict").openStream();
InputStream infoInput = this.getClass().getResource("test-infix.info").openStream()) {
Files.copy(dictInput, dict);
Files.copy(infoInput, info);
}
assertNotNull(Dictionary.read(dict.toUri().toURL()));
assertNotNull(Dictionary.read(dict));
}
static void generateJAXPProps(String content) throws IOException {
Path filePath = getJAXPPropsPath();
Path bakPath = filePath.resolveSibling(JAXP_PROPS_BAK);
System.out.println("Creating new file " + filePath +
", saving old version to " + bakPath + ".");
if (Files.exists(filePath) && !Files.exists(bakPath)) {
Files.move(filePath, bakPath);
}
Files.write(filePath, content.getBytes());
}
/**
* Returns the name of the archived file
*
* @param time the archive date
*/
protected Path getArchivePath(long time)
{
Path path = getPath();
String archiveFormat = getArchiveFormat();
String name = getFormatName(archiveFormat + _archiveSuffix, time);
Path newPath = path.resolveSibling(name);
if (Files.exists(newPath)) {
if (archiveFormat.indexOf("%H") < 0)
archiveFormat = archiveFormat + ".%H%M";
else if (archiveFormat.indexOf("%M") < 0)
archiveFormat = archiveFormat + ".%M";
for (int i = 0; i < 100; i++) {
String suffix;
if (i == 0)
suffix = _archiveSuffix;
else
suffix = "." + i + _archiveSuffix;
name = getFormatName(archiveFormat + suffix, time);
newPath = path.resolveSibling(name);
if (! Files.exists(newPath)) {
break;
}
}
}
return newPath;
}
private static Path backupFile(Path file) throws IOException {
String fName = file.getFileName().toString();
int lastDot = fName.lastIndexOf(".");
if (lastDot != -1) {
String backupName = fName.substring(0, lastDot) + "-backup-" + TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis());
Path backup = file.resolveSibling(backupName + fName.substring(lastDot));
Files.move(file, backup);
return backup;
}
return null;
}
private static Path stripExtension(Path path) {
String name = path.getFileName().toString();
return path.resolveSibling(getNameWithoutExtension(name));
}
@Override
public CommandResult execute(LuckPermsPlugin plugin, Sender sender, ArgumentList args, String label) {
if (this.running.get()) {
Message.IMPORT_ALREADY_RUNNING.send(sender);
return CommandResult.STATE_ERROR;
}
String fileName = args.get(0);
Path dataDirectory = plugin.getBootstrap().getDataDirectory();
Path path = dataDirectory.resolve(fileName);
if (!path.getParent().equals(dataDirectory) || path.getFileName().toString().equals("config.yml")) {
Message.FILE_NOT_WITHIN_DIRECTORY.send(sender, path.toString());
return CommandResult.INVALID_ARGS;
}
// try auto adding the '.json.gz' extension
if (!Files.exists(path) && !fileName.contains(".")) {
Path pathWithDefaultExtension = path.resolveSibling(fileName + ".json.gz");
if (Files.exists(pathWithDefaultExtension)) {
path = pathWithDefaultExtension;
}
}
if (!Files.exists(path)) {
Message.IMPORT_FILE_DOESNT_EXIST.send(sender, path.toString());
return CommandResult.INVALID_ARGS;
}
if (!Files.isReadable(path)) {
Message.IMPORT_FILE_NOT_READABLE.send(sender, path.toString());
return CommandResult.FAILURE;
}
if (!this.running.compareAndSet(false, true)) {
Message.IMPORT_ALREADY_RUNNING.send(sender);
return CommandResult.STATE_ERROR;
}
JsonObject data;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(Files.newInputStream(path)), StandardCharsets.UTF_8))) {
data = GsonProvider.normal().fromJson(reader, JsonObject.class);
} catch (IOException e) {
e.printStackTrace();
Message.IMPORT_FILE_READ_FAILURE.send(sender);
this.running.set(false);
return CommandResult.FAILURE;
}
Importer importer = new Importer(plugin, sender, data, args.contains("--merge"));
// Run the importer in its own thread.
plugin.getBootstrap().getScheduler().executeAsync(() -> {
try {
importer.run();
} finally {
this.running.set(false);
}
});
return CommandResult.SUCCESS;
}
DatabaseKelp(Path path,
DatabaseKelpBuilder builder)
throws IOException
{
_path = path;
// _row = rowBuilder.build(this);
// _table = new TableKelp(this, "table", _row);
_segmentSizeMin = builder.getSegmentSizeMin();
_segmentSizeMax = builder.getSegmentSizeMax();
_segmentSizeFactorNew = builder.getSegmentSizeFactorNew();
_segmentSizeFactorGc = builder.getSegmentSizeFactorGc();
if (_segmentSizeMax < _segmentSizeMin) {
throw new IllegalArgumentException(L.l("Invalid segment size <{0},{1}>",
_segmentSizeMin, _segmentSizeMax));
}
_btreeNodeLength = builder.getBtreeNodeLength();
_deltaMax = builder.getDeltaMax();
_gcThreshold = builder.getGcThreshold();
_gcMinCollect = 2;
_gcMaxCollect = builder.getGcMaxCollect();
_blobInlineMax = builder.getBlobInlineMax();
_blobPageSizeMax = builder.getBlobPageSizeMax();
_memoryMax = builder.getMemorySize();
_deltaLeafMax = builder.getDeltaLeafMax();
_deltaTreeMax = builder.getDeltaTreeMax();
_isValidate = builder.isValidate();
_tempStore = builder.getTempStore();
/*
if (BLOCK_SIZE <= _inlineBlobMax - _row.getLength()) {
throw new IllegalStateException(L.l("Inline blob size '{0}' is too large",
_inlineBlobMax));
}
*/
_rampManager = builder.getManager(); // Ramp.newManager();
_dbService = _rampManager.newService(new DatabaseServiceKelpImpl(this))
.as(DatabaseServiceKelp.class);
SegmentKelpBuilder segmentBuilder = new SegmentKelpBuilder();
segmentBuilder.path(path);
segmentBuilder.services(_rampManager);
int lastSize = _segmentSizeMin;
for (int size = _segmentSizeMin; size <= _segmentSizeMax; size *= 4) {
segmentBuilder.segmentSize(size);
lastSize = size;
}
if (lastSize < _segmentSizeMax) {
segmentBuilder.segmentSize(_segmentSizeMax);
}
SegmentServiceImpl segmentServiceImpl = segmentBuilder.build();
_store = segmentServiceImpl.store();
_segmentService = _rampManager.newService(segmentServiceImpl)
.as(SegmentService.class);
String tail = path.getFileName().toString();
Path journalPath = path.resolveSibling(tail + ".log");
JournalStore.Builder journalBuilder;
journalBuilder = JournalStore.Builder.create(journalPath);
journalBuilder.segmentSize(builder.getJournalSegmentSize());
journalBuilder.rampManager(_rampManager);
_journalStore = journalBuilder.build();
_lifecycle.toActive();
// checkpoint();
}
private Path backupPath(Path filepath) {
return filepath.resolveSibling(filepath.getFileName() + ".backup"); //$NON-NLS-1$
}