Skip to content

Commit c1e6a77

Browse files
committed
Use var instead of explicit declaration
1 parent 61f8268 commit c1e6a77

File tree

4 files changed

+54
-52
lines changed

4 files changed

+54
-52
lines changed

src/main/java/org/keepassxc/Connection.java

Lines changed: 24 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -81,29 +81,29 @@ public void removePropertyChangeListener(PropertyChangeListener pcl) {
8181
* @throws IOException Sending failed due to technical reasons.
8282
*/
8383
private void sendEncryptedMessage(Map<String, Object> msg) throws IOException {
84-
boolean unlockRequested = false;
84+
var unlockRequested = false;
8585

8686
if (!isConnected()) {
8787
throw new IllegalStateException(NOT_CONNECTED);
8888
}
8989

90-
byte[] publicKey = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getServerPublicKey();
91-
TweetNaclFast.Box.KeyPair keyPair = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getOwnKeypair();
90+
var publicKey = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getServerPublicKey();
91+
var keyPair = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getOwnKeypair();
9292

9393
if (msg.containsKey("triggerUnlock") && msg.get("triggerUnlock").equals("true")) {
9494
msg.remove("triggerUnlock");
9595
unlockRequested = true;
9696
}
9797

98-
String strMsg = jsonTxt(msg);
98+
var strMsg = jsonTxt(msg);
9999
log.trace("Send - encrypting the following message: {}", strMsg);
100100

101101
box = new TweetNaclFast.Box(publicKey, keyPair.getSecretKey());
102102

103-
String encrypted = b64encode(box.box(strMsg.getBytes(), nonce));
103+
var encrypted = b64encode(box.box(strMsg.getBytes(), nonce));
104104

105105
// Map.of can't be used here, because we need a mutable object
106-
Map<String, Object> message = new HashMap<>();
106+
var message = new HashMap<String, Object>();
107107
message.put("action", msg.get("action").toString());
108108
message.put("message", encrypted);
109109
message.put("nonce", b64encode(nonce));
@@ -128,7 +128,7 @@ private void sendEncryptedMessage(Map<String, Object> msg) throws IOException {
128128
* @throws KeepassProxyAccessException It was impossible to process the requested action.
129129
*/
130130
private JSONObject getEncryptedResponseAndDecrypt(String action) throws IOException, KeepassProxyAccessException {
131-
JSONObject response = getCleartextResponse();
131+
var response = getCleartextResponse();
132132

133133
// Handle signals
134134
while (!response.has("error") && isSignal(response)) {
@@ -148,16 +148,16 @@ private JSONObject getEncryptedResponseAndDecrypt(String action) throws IOExcept
148148
throw new KeepassProxyAccessException("ErrorCode: " + response.getString("errorCode") + ", " + response.getString("error"));
149149
}
150150

151-
byte[] serverNonce = b64decode(response.getString("nonce").getBytes());
152-
byte[] bMessage = box.open(b64decode(response.getString("message").getBytes()), serverNonce);
151+
var serverNonce = b64decode(response.getString("nonce").getBytes());
152+
var bMessage = box.open(b64decode(response.getString("message").getBytes()), serverNonce);
153153

154154
if (bMessage == null) {
155155
throw new KeepassProxyAccessException("Error: message could not be decrypted");
156156
}
157157

158-
String decrypted = new String(bMessage, StandardCharsets.UTF_8);
158+
var decrypted = new String(bMessage, StandardCharsets.UTF_8);
159159
log.trace("Decrypted message: {}", decrypted);
160-
JSONObject decryptedResponse = new JSONObject(decrypted);
160+
var decryptedResponse = new JSONObject(decrypted);
161161

162162
if (!decryptedResponse.has("success")) {
163163
throw new KeepassProxyAccessException("ErrorCode: " + response.getString("errorCode") + ", " + response.getString("error"));
@@ -186,7 +186,7 @@ protected void changePublicKeys() throws IOException, KeepassProxyAccessExceptio
186186
throw new IllegalStateException(NOT_CONNECTED);
187187
}
188188

189-
TweetNaclFast.Box.KeyPair keyPair = TweetNaclFast.Box.keyPair();
189+
var keyPair = TweetNaclFast.Box.keyPair();
190190

191191
// Send change-public-keys request
192192
sendCleartextMessage(jsonTxt(Map.of(
@@ -195,13 +195,13 @@ protected void changePublicKeys() throws IOException, KeepassProxyAccessExceptio
195195
"nonce", b64encode(nonce),
196196
"clientID", clientID
197197
)));
198-
JSONObject response = getCleartextResponse();
198+
var response = getCleartextResponse();
199199

200200
if (!response.has("success")) {
201201
throw new KeepassProxyAccessException("ErrorCode: " + response.getString("errorCode") + ", " + response.getString("error"));
202202
}
203203

204-
byte[] publicKey = b64decode(response.getString("publicKey").getBytes());
204+
var publicKey = b64decode(response.getString("publicKey").getBytes());
205205
box = new TweetNaclFast.Box(publicKey, keyPair.getSecretKey());
206206

207207
if (credentials.isEmpty()) {
@@ -223,16 +223,16 @@ protected void changePublicKeys() throws IOException, KeepassProxyAccessExceptio
223223
* @throws KeepassProxyAccessException It was impossible to associate KeePassXC with a new client.
224224
*/
225225
public void associate() throws IOException, KeepassProxyAccessException {
226-
TweetNaclFast.Box.KeyPair idKeyPair = TweetNaclFast.Box.keyPair();
227-
TweetNaclFast.Box.KeyPair keyPair = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getOwnKeypair();
226+
var idKeyPair = TweetNaclFast.Box.keyPair();
227+
var keyPair = credentials.orElseThrow(() -> new IllegalStateException(KEYEXCHANGE_MISSING)).getOwnKeypair();
228228

229229
// Send associate request
230230
sendEncryptedMessage(Map.of(
231231
"action", "associate",
232232
"key", b64encode(keyPair.getPublicKey()),
233233
"idKey", b64encode(idKeyPair.getPublicKey())
234234
));
235-
JSONObject response = getEncryptedResponseAndDecrypt("associate");
235+
var response = getEncryptedResponseAndDecrypt("associate");
236236

237237
credentials.orElseThrow(() -> new IllegalStateException(MISSING_CLASS)).setAssociateId(response.getString("id"));
238238
credentials.orElseThrow(() -> new IllegalStateException(MISSING_CLASS)).setIdKeyPublicKey(idKeyPair.getPublicKey());
@@ -249,7 +249,7 @@ public void associate() throws IOException, KeepassProxyAccessException {
249249
public String getDatabasehash() throws IOException, KeepassProxyAccessException {
250250
// Send get-databasehash request
251251
sendEncryptedMessage(Map.of("action", "get-databasehash"));
252-
JSONObject response = getEncryptedResponseAndDecrypt("get-databasehash");
252+
var response = getEncryptedResponseAndDecrypt("get-databasehash");
253253

254254
return response.getString("hash");
255255
}
@@ -265,11 +265,11 @@ public String getDatabasehash() throws IOException, KeepassProxyAccessException
265265
*/
266266
public String getDatabasehash(boolean triggerUnlock) throws IOException, KeepassProxyAccessException {
267267
// Send get-databasehash request with triggerUnlock, if needed
268-
Map<String, Object> map = new HashMap<>(); // Map.of can't be used here, because we need a mutable object
268+
var map = new HashMap<String, Object>(); // Map.of can't be used here, because we need a mutable object
269269
map.put("action", "get-databasehash");
270270
map.put("triggerUnlock", Boolean.toString(triggerUnlock));
271271
sendEncryptedMessage(map);
272-
JSONObject response = getEncryptedResponseAndDecrypt("get-databasehash");
272+
var response = getEncryptedResponseAndDecrypt("get-databasehash");
273273

274274
return response.getString("hash");
275275
}
@@ -306,10 +306,10 @@ public void testAssociate(String id, String key) throws IOException, KeepassProx
306306
* @throws KeepassProxyAccessException No credentials found for the given URL.
307307
*/
308308
public JSONObject getLogins(String url, String submitUrl, boolean httpAuth, List<Map<String, String>> list) throws IOException, KeepassProxyAccessException {
309-
JSONArray array = new JSONArray();
309+
var array = new JSONArray();
310310
// Syntax check for list
311311
for (Map<String, String> m : list) {
312-
JSONObject o = new JSONObject(m);
312+
var o = new JSONObject(m);
313313
if (!(o.has("id") && o.has("key") && o.length() == 2)) {
314314
throw new KeepassProxyAccessException("JSON object key is malformed");
315315
}
@@ -464,8 +464,8 @@ private String jsonTxt(Map<String, Object> keysValues) {
464464
* Increment nonce by 1
465465
*/
466466
private void incrementNonce() {
467-
int newNonce = ByteBuffer.wrap(nonce).getInt() + 1;
468-
ByteBuffer dbuf = ByteBuffer.allocate(24).putInt(newNonce);
467+
var newNonce = ByteBuffer.wrap(nonce).getInt() + 1;
468+
var dbuf = ByteBuffer.allocate(24).putInt(newNonce);
469469
nonce = dbuf.array();
470470
}
471471

src/main/java/org/keepassxc/LinuxMacConnection.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public class LinuxMacConnection extends Connection {
2424
private final File socketFile;
2525

2626
public LinuxMacConnection() {
27-
String socketPath = getSocketPath();
27+
var socketPath = getSocketPath();
2828
this.socketFile = new File(new File(socketPath), "/" + PROXY_NAME);
2929
}
3030

@@ -62,7 +62,7 @@ protected void sendCleartextMessage(String msg) throws IOException {
6262
@Override
6363
protected JSONObject getCleartextResponse() throws IOException {
6464
int c;
65-
String raw = "";
65+
var raw = "";
6666
do {
6767
c = is.read();
6868
raw += (char) c;
@@ -78,7 +78,7 @@ protected JSONObject getCleartextResponse() throws IOException {
7878
*/
7979
private String getSocketPath() {
8080
if (SystemUtils.IS_OS_LINUX) {
81-
String path = System.getenv("XDG_RUNTIME_DIR");
81+
var path = System.getenv("XDG_RUNTIME_DIR");
8282
if (null == path) path = System.getenv("TMPDIR");
8383
return (null == path) ? "/tmp" : path;
8484
}

src/main/java/org/keepassxc/WindowsConnection.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ protected void sendCleartextMessage(String msg) throws IOException {
4646
@Override
4747
protected JSONObject getCleartextResponse() throws IOException {
4848
int c;
49-
String raw = "";
49+
var raw = "";
5050
do {
5151
c = pipe.read();
5252
raw += (char) c;

src/main/java/org/purejava/KeepassProxyAccess.java

Lines changed: 26 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package org.purejava;
22

33
import org.apache.commons.lang3.SystemUtils;
4-
import org.json.JSONArray;
54
import org.json.JSONException;
65
import org.json.JSONObject;
76
import org.keepassxc.Connection;
@@ -12,7 +11,10 @@
1211

1312
import java.beans.PropertyChangeEvent;
1413
import java.beans.PropertyChangeListener;
15-
import java.io.*;
14+
import java.io.FileInputStream;
15+
import java.io.IOException;
16+
import java.io.ObjectInputStream;
17+
import java.io.ObjectOutputStream;
1618
import java.nio.file.Files;
1719
import java.nio.file.Path;
1820
import java.nio.file.StandardCopyOption;
@@ -63,9 +65,9 @@ public KeepassProxyAccess() {
6365
* @return An Optional of the Credentials read from disc in case they are available, an empty Optional otherwise.
6466
*/
6567
private Optional<Credentials> loadCredentials() {
66-
try (FileInputStream fileIs = new FileInputStream(fileLocation);
67-
ObjectInputStream objIs = new ObjectInputStream(fileIs)) {
68-
Credentials c = (Credentials) objIs.readObject();
68+
try (var fileIs = new FileInputStream(fileLocation);
69+
var objIs = new ObjectInputStream(fileIs)) {
70+
var c = (Credentials) objIs.readObject();
6971
return Optional.of(c);
7072
} catch (IOException | ClassNotFoundException e) {
7173
log.debug("Credentials could not be read from disc");
@@ -85,8 +87,8 @@ private void scheduleSave(Optional<Credentials> credentials) {
8587
return;
8688
}
8789
Runnable saveCommand = () -> this.saveCredentials(credentials);
88-
ScheduledFuture<?> scheduledTask = scheduler.schedule(saveCommand, SAVE_DELAY_MS, TimeUnit.MILLISECONDS);
89-
ScheduledFuture<?> previouslyScheduledTask = scheduledSaveCmd.getAndSet(scheduledTask);
90+
var scheduledTask = scheduler.schedule(saveCommand, SAVE_DELAY_MS, TimeUnit.MILLISECONDS);
91+
var previouslyScheduledTask = scheduledSaveCmd.getAndSet(scheduledTask);
9092
if (previouslyScheduledTask != null) {
9193
previouslyScheduledTask.cancel(false);
9294
}
@@ -99,11 +101,11 @@ private void scheduleSave(Optional<Credentials> credentials) {
99101
private void saveCredentials(Optional<Credentials> credentials) {
100102
log.debug("Attempting to save credentials");
101103
try {
102-
Path path = Path.of(fileLocation);
104+
var path = Path.of(fileLocation);
103105
Files.createDirectories(path.getParent());
104-
Path tmpPath = path.resolveSibling(path.getFileName().toString() + ".tmp");
105-
try (OutputStream ops = Files.newOutputStream(tmpPath, StandardOpenOption.CREATE_NEW);
106-
ObjectOutputStream objOps = new ObjectOutputStream(ops)) {
106+
var tmpPath = path.resolveSibling(path.getFileName().toString() + ".tmp");
107+
try (var ops = Files.newOutputStream(tmpPath, StandardOpenOption.CREATE_NEW);
108+
var objOps = new ObjectOutputStream(ops)) {
107109
objOps.writeObject(credentials.get());
108110
objOps.flush();
109111
}
@@ -188,21 +190,21 @@ public Map<String, Object> getLogins(String url, String submitUrl, boolean httpA
188190
}
189191

190192
public boolean loginExists(String url, String submitUrl, boolean httpAuth, List<Map<String, String>> list, String password) {
191-
Map<String, Object> response = getLogins(url, submitUrl, httpAuth, list);
193+
var response = getLogins(url, submitUrl, httpAuth, list);
192194
if (response.isEmpty()) {
193195
return false;
194196
}
195-
List<Object> array = (ArrayList<Object>) response.get("entries");
197+
var array = (ArrayList<Object>) response.get("entries");
196198
for (Object o : array) {
197-
Map<String, Object> credentials = (HashMap<String, Object>) o;
199+
var credentials = (HashMap<String, Object>) o;
198200
if (credentials.get("password").equals(password)) return true;
199201
}
200202
return false;
201203
}
202204

203205
public boolean setLogin(String url, String submitUrl, String id, String login, String password, String group, String groupUuid, String uuid) {
204206
try {
205-
JSONObject response = connection.setLogin(url, submitUrl, id, login, password, group, groupUuid, uuid);
207+
var response = connection.setLogin(url, submitUrl, id, login, password, group, groupUuid, uuid);
206208
return response.has("success") && response.getString("success").equals("true");
207209
} catch (IOException | IllegalStateException | KeepassProxyAccessException | JSONException e) {
208210
log.info(e.toString(), e.getCause());
@@ -221,7 +223,7 @@ public JSONObject getDatabaseGroups() {
221223

222224
public String generatePassword() {
223225
try {
224-
JSONArray response = connection.generatePassword().getJSONArray("entries");
226+
var response = connection.generatePassword().getJSONArray("entries");
225227
return response.getJSONObject(0).getString("password");
226228
} catch (IOException | IllegalStateException | KeepassProxyAccessException | JSONException e) {
227229
log.info(e.toString(), e.getCause());
@@ -231,7 +233,7 @@ public String generatePassword() {
231233

232234
public boolean lockDatabase() {
233235
try {
234-
JSONObject response = connection.lockDatabase();
236+
connection.lockDatabase();
235237
return true;
236238
} catch (IOException | IllegalStateException | KeepassProxyAccessException | JSONException e) {
237239
log.info(e.toString(), e.getCause());
@@ -280,12 +282,12 @@ public Map<String, String> databaseGroupsToMap(JSONObject groups) {
280282
if (groups.isEmpty()) {
281283
return Map.of();
282284
}
283-
Map<String, String> groupTree = new HashMap<>();
284-
Map<String, Object> m = groups.toMap();
285-
Map<String, Object> n = (HashMap<String, Object>) m.get("groups");
286-
List<Object> rootGroups = (ArrayList<Object>) n.get("groups");
287-
Map<String, Object> rootGroup = (HashMap<String, Object>) rootGroups.get(0);
288-
List<Object> children = (ArrayList<Object>) rootGroup.get("children");
285+
var groupTree = new HashMap<String, String>();
286+
var m = groups.toMap();
287+
var n = (HashMap<String, Object>) m.get("groups");
288+
var rootGroups = (ArrayList<Object>) n.get("groups");
289+
var rootGroup = (HashMap<String, Object>) rootGroups.get(0);
290+
var children = (ArrayList<Object>) rootGroup.get("children");
289291
traverse(children, groupTree);
290292
return groupTree;
291293
}
@@ -294,7 +296,7 @@ private void traverse(List<Object> children, Map<String, String> groups) {
294296
children.stream()
295297
.map(listItem -> (HashMap<String, Object>) listItem)
296298
.forEach(li -> {
297-
List<Object> alc = (ArrayList<Object>) li.get("children");
299+
var alc = (ArrayList<Object>) li.get("children");
298300
if (alc.size() == 0) {
299301
groups.put(li.get("name").toString(), li.get("uuid").toString());
300302
} else {

0 commit comments

Comments
 (0)