2 * Copyright 2015-present Open Networking Foundation
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;
20 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";
31 private final File file;
34 * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
36 * @throws NullPointerException if {@code file} is null
38 public static boolean isSegmentFile(String name, File file) {
39 return isSegmentFile(name, file.getName());
43 * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
45 * @param journalName the name of the journal
46 * @param fileName the name of the file to check
47 * @throws NullPointerException if {@code file} is null
49 public static boolean isSegmentFile(String journalName, String fileName) {
50 requireNonNull(journalName, "journalName cannot be null");
51 requireNonNull(fileName, "fileName cannot be null");
53 int partSeparator = fileName.lastIndexOf(PART_SEPARATOR);
54 int extensionSeparator = fileName.lastIndexOf(EXTENSION_SEPARATOR);
56 if (extensionSeparator == -1
57 || partSeparator == -1
58 || extensionSeparator < partSeparator
59 || !fileName.endsWith(EXTENSION)) {
63 for (int i = partSeparator + 1; i < extensionSeparator; i++) {
64 if (!Character.isDigit(fileName.charAt(i))) {
69 return fileName.startsWith(journalName);
73 * Creates a segment file for the given directory, log name, segment ID, and segment version.
75 static File createSegmentFile(String name, File directory, long id) {
76 return new File(directory, String.format("%s-%d.log", requireNonNull(name, "name cannot be null"), id));
80 * @throws IllegalArgumentException if {@code file} is not a valid segment file
82 JournalSegmentFile(File file) {
87 * Returns the segment file.
89 * @return The segment file.