This repository has been archived by the owner on Dec 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 39
/
CredentialsPersistenceManager.java
94 lines (78 loc) · 2.94 KB
/
CredentialsPersistenceManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package nu.studer.gradle.credentials.domain;
import nu.studer.java.util.OrderedProperties;
import org.gradle.api.UncheckedIOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* Manages the storage and retrieval of encrypted credentials.
*/
public final class CredentialsPersistenceManager {
private static final Logger LOGGER = LoggerFactory.getLogger(CredentialsPersistenceManager.class);
private final File credentialsFile;
public CredentialsPersistenceManager(File credentialsFile) {
this.credentialsFile = credentialsFile;
}
public File getCredentialsFile() {
return new File(credentialsFile.toURI());
}
public OrderedProperties readCredentials() {
OrderedProperties credentials = createOrderedProperties();
// read the file with the encrypted credentials, if it already exists
File file = getCredentialsFile();
if (file.exists()) {
LOGGER.debug("Read existing credentials file: " + file.getAbsolutePath());
loadProperties(credentials, file);
} else {
LOGGER.debug("Credentials file does not exist yet: " + file.getAbsolutePath());
}
return credentials;
}
public void storeCredentials(OrderedProperties credentials) {
// write the updated credentials
File file = getCredentialsFile();
LOGGER.debug("Write updated credentials file: " + file.getAbsolutePath());
saveProperties(credentials, file);
}
private static void loadProperties(OrderedProperties properties, File file) {
try {
FileInputStream inputStream = new FileInputStream(file);
try {
loadProperties(properties, inputStream);
} finally {
inputStream.close();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void loadProperties(OrderedProperties properties, InputStream stream) {
try {
properties.load(stream);
stream.close();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static void saveProperties(OrderedProperties properties, File file) {
try {
FileOutputStream propertiesFileOutputStream = new FileOutputStream(file);
try {
properties.store(propertiesFileOutputStream, null);
} finally {
propertiesFileOutputStream.close();
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static OrderedProperties createOrderedProperties() {
return new OrderedProperties.OrderedPropertiesBuilder().
withSuppressDateInComment(true).
build();
}
}