2 * Copyright 2015-2022 Open Networking Foundation and others. All rights reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package io.atomix.storage.journal;
18 import static java.util.Objects.requireNonNull;
23 * Segment file utility.
25 * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
27 public final class JournalSegmentFile {
28 private static final char PART_SEPARATOR = '-';
29 private static final char EXTENSION_SEPARATOR = '.';
30 private static final String EXTENSION = "log";
32 private final File file;
35 * @throws IllegalArgumentException if {@code file} is not a valid segment file
37 JournalSegmentFile(final File file) {
42 * Returns the segment file.
44 * @return The segment file.
51 * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
53 * @throws NullPointerException if {@code file} is null
55 public static boolean isSegmentFile(final String name, final File file) {
56 return isSegmentFile(name, file.getName());
60 * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
62 * @param journalName the name of the journal
63 * @param fileName the name of the file to check
64 * @throws NullPointerException if {@code file} is null
66 public static boolean isSegmentFile(final String journalName, final String fileName) {
67 requireNonNull(journalName, "journalName cannot be null");
68 requireNonNull(fileName, "fileName cannot be null");
70 int partSeparator = fileName.lastIndexOf(PART_SEPARATOR);
71 int extensionSeparator = fileName.lastIndexOf(EXTENSION_SEPARATOR);
73 if (extensionSeparator == -1 || partSeparator == -1 || extensionSeparator < partSeparator
74 || !fileName.endsWith(EXTENSION)) {
78 for (int i = partSeparator + 1; i < extensionSeparator; i++) {
79 if (!Character.isDigit(fileName.charAt(i))) {
84 return fileName.startsWith(journalName);
88 * Creates a segment file for the given directory, log name, segment ID, and segment version.
90 static File createSegmentFile(final String name, final File directory, final long id) {
91 return new File(directory, String.format("%s-%d.log", requireNonNull(name, "name cannot be null"), id));