From 31cd00853a94e72144a156ce9654e4a3e41bdca4 Mon Sep 17 00:00:00 2001 From: Kohsuke Kawaguchi Date: Fri, 4 Jan 2013 10:14:45 -0800 Subject: [PATCH] Addd a new utility for a persisted boolean --- .../java/jenkins/util/io/FileBoolean.java | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 core/src/main/java/jenkins/util/io/FileBoolean.java diff --git a/core/src/main/java/jenkins/util/io/FileBoolean.java b/core/src/main/java/jenkins/util/io/FileBoolean.java new file mode 100644 index 0000000000..3800ae287f --- /dev/null +++ b/core/src/main/java/jenkins/util/io/FileBoolean.java @@ -0,0 +1,61 @@ +package jenkins.util.io; + +import jenkins.model.Jenkins; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.logging.Level; +import java.util.logging.Logger; + +/** + * Uses a presence/absence of a file as a persisted boolean storage. + * + *

+ * This is convenient when you need to store just a few bits of infrequently accessed information + * as you can forget the explicit persistence of it. This class masks I/O problem, so if the persistence + * fails, you'll get no error report. + * + * @author Kohsuke Kawaguchi + * @since 1.498 + */ +public class FileBoolean { + private final File file; + + public FileBoolean(File file) { + this.file = file; + } + + public FileBoolean(Class owner, String name) { + this(new File(Jenkins.getInstance().getRootDir(),owner.getName().replace('$','.')+'/'+name)); + } + + /** + * Gets the current state. True if the file exists, false if it doesn't. + */ + public boolean get() { + return file.exists(); + } + + public boolean isOn() { return get(); } + public boolean isOff() { return !get(); } + + public void set(boolean b) { + if (b) on(); else off(); + } + + public void on() { + try { + file.getParentFile().mkdirs(); + new FileOutputStream(file).close(); + } catch (IOException e) { + LOGGER.log(Level.WARNING, "Failed to touch "+file); + } + } + + public void off() { + file.delete(); + } + + private static final Logger LOGGER = Logger.getLogger(FileBoolean.class.getName()); +} -- GitLab