[miio] Java style cleanup (#15610)

Introducing non-breaking improvements from #15520
- Java style array syntax
- remove redundant modifiers
- always move String constants to left side in comparisons
- multiline strings

Signed-off-by: Marcel Verpaalen <marcel@verpaalen.com>
Co-authored-by: Holger Friedrich <mail@holger-friedrich.de>
This commit is contained in:
Marcel 2023-09-19 22:53:50 +02:00 committed by GitHub
parent 14cfeb0996
commit bf1aa3deb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
12 changed files with 33 additions and 37 deletions

View File

@ -62,8 +62,7 @@ public class MiIoCrypto {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec, vector);
byte[] encrypted = cipher.doFinal(cipherText);
return encrypted;
return cipher.doFinal(cipherText);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new MiIoCryptoException(e.getMessage(), e);
@ -80,8 +79,7 @@ public class MiIoCrypto {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
cipher.init(Cipher.DECRYPT_MODE, keySpec, vector);
byte[] crypted = cipher.doFinal(cipherText);
return (crypted);
return cipher.doFinal(cipherText);
} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
throw new MiIoCryptoException(e.getMessage(), e);

View File

@ -91,10 +91,9 @@ public final class Utils {
public static String obfuscateToken(String tokenString) {
if (tokenString.length() > 8) {
String tokenText = tokenString.substring(0, 8)
return tokenString.substring(0, 8)
.concat((tokenString.length() < 24) ? tokenString.substring(8).replaceAll(".", "X")
: tokenString.substring(8, 24).replaceAll(".", "X").concat(tokenString.substring(24)));
return tokenText;
} else {
return tokenString;
}

View File

@ -46,7 +46,7 @@ public class CloudConnector {
private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
private static enum DeviceListState {
private enum DeviceListState {
FAILED,
STARTING,
REFRESHING,

View File

@ -131,7 +131,7 @@ public class MiCloudConnector {
}
private String getApiUrl(String country) {
return "https://" + (country.trim().equalsIgnoreCase("cn") ? "" : country.trim().toLowerCase() + ".")
return "https://" + ("cn".equalsIgnoreCase(country.trim()) ? "" : country.trim().toLowerCase() + ".")
+ "api.io.mi.com/app";
}
@ -180,8 +180,7 @@ public class MiCloudConnector {
}
public String getDeviceStatus(String device, String country) throws MiCloudException {
final String response = request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
return response;
return request("/home/device_list", country, "{\"dids\":[\"" + device + "\"]}");
}
public String sendRPCCommand(String device, String country, String command) throws MiCloudException {
@ -199,8 +198,7 @@ public class MiCloudConnector {
logger.debug("{}", err);
throw new MiCloudException(err, e);
}
final String response = request("/home/rpc/" + id, country, command);
return response;
return request("/home/rpc/" + id, country, command);
}
public List<CloudDeviceDTO> getDevices(String country) {
@ -412,7 +410,7 @@ public class MiCloudConnector {
try {
JsonElement resp = JsonParser.parseString(parseJson(content));
CloudLogin1DTO jsonResp = GSON.fromJson(resp, CloudLogin1DTO.class);
final String sign = jsonResp.getSign();
final String sign = jsonResp != null ? jsonResp.getSign() : null;
if (sign != null && !sign.isBlank()) {
logger.trace("Xiaomi Login step 1 sign = {}", sign);
return sign;
@ -476,8 +474,14 @@ public class MiCloudConnector {
if (0 != jsonResp.getSecurityStatus()) {
logger.debug("Xiaomi Cloud Step2 response: {}", parseJson(content2));
logger.debug(
"Xiaomi Login code: {} \r\nSecurityStatus: {}\r\nPwd code: {}\r\nLocation logon URL: {}\r\nIn case of login issues check userId/password details are correct.\r\n"
+ "If login details are correct, try to logon using browser from the openHAB ip using the browser. Alternatively try to complete logon with above URL.",
"""
Xiaomi Login code: {}
SecurityStatus: {}
Pwd code: {}
Location logon URL: {}
In case of login issues check userId/password details are correct.
If login details are correct, try to logon using browser from the openHAB ip using the browser. Alternatively try to complete logon with above URL.\
""",
jsonResp.getCode(), jsonResp.getSecurityStatus(), jsonResp.getPwd(), jsonResp.getLocation());
}
if (logger.isTraceEnabled()) {

View File

@ -314,7 +314,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
final MiIoAsyncCommunication connection = getConnection();
return (connection != null) ? connection.queueCommand(command, params, cloudServer, sender) : 0;
} catch (MiIoCryptoException | IOException e) {
logger.debug("Command {} for {} failed (type: {}): {}", command.toString(), getThing().getUID(),
logger.debug("Command {} for {} failed (type: {}): {}", command, getThing().getUID(),
getThing().getThingTypeUID(), e.getLocalizedMessage());
disconnected(e.getMessage());
}
@ -327,7 +327,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
// simple and only have the option for cloud or direct.
final MiIoBindingConfiguration configuration = this.configuration;
if (configuration != null) {
return configuration.communication.equals("cloud") ? cloudServer : "";
return "cloud".equals(configuration.communication) ? cloudServer : "";
}
return "";
}
@ -526,7 +526,7 @@ public abstract class MiIoAbstractHandler extends BaseThingHandler implements Mi
return cmd;
}
String returnCmd = cmd.replace("\"$", "$").replace("$\"", "$");
String cmdParts[] = cmd.split("\\$");
String[] cmdParts = cmd.split("\\$");
if (logger.isTraceEnabled()) {
logger.debug("processSubstitutions {} ", cmd);
for (Entry<String, Object> e : deviceVariables.entrySet()) {

View File

@ -213,13 +213,13 @@ public class MiIoVacuumHandler extends MiIoAbstractHandler {
}
}
if (channelUID.getId().equals(CHANNEL_CONTROL)) {
if (command.toString().equals("vacuum")) {
if ("vacuum".equals(command.toString())) {
sendCommand(MiIoCommand.START_VACUUM);
} else if (command.toString().equals("spot")) {
} else if ("spot".equals(command.toString())) {
sendCommand(MiIoCommand.START_SPOT);
} else if (command.toString().equals("pause")) {
} else if ("pause".equals(command.toString())) {
sendCommand(MiIoCommand.PAUSE);
} else if (command.toString().equals("dock")) {
} else if ("dock".equals(command.toString())) {
sendCommand(MiIoCommand.STOP_VACUUM);
miIoScheduler.schedule(() -> {
sendCommand(MiIoCommand.CHARGE);

View File

@ -241,7 +241,7 @@ public class MiotParser {
}
miIoBasicChannel.setRefresh(property.access.contains("read"));
// add option values
if (property.valueList != null && property.valueList.size() > 0) {
if (property.valueList != null && !property.valueList.isEmpty()) {
StateDescriptionDTO stateDescription = miIoBasicChannel.getStateDescription();
if (stateDescription == null) {
stateDescription = new StateDescriptionDTO();

View File

@ -281,7 +281,6 @@ public class RRMapDraw {
g2d.draw(noGo);
}
}
;
}
private void drawWalls(Graphics2D g2d, float scale) {
@ -369,8 +368,8 @@ public class RRMapDraw {
if (!(x == 0 && y == 0)) {
g2d.setStroke(new BasicStroke());
g2d.setColor(Color.YELLOW);
int x3[] = { (int) x, (int) (x - 2 * scale), (int) (x + 2 * scale) };
int y3[] = { (int) y, (int) (y - 5 * scale), (int) (y - 5 * scale) };
int[] x3 = { (int) x, (int) (x - 2 * scale), (int) (x + 2 * scale) };
int[] y3 = { (int) y, (int) (y - 5 * scale), (int) (y - 5 * scale) };
g2d.fill(new Polygon(x3, y3, 3));
}
}

View File

@ -93,9 +93,8 @@ public class RRMapDrawOptions {
throw new JsonParseException("missing json text");
}
JsonObject colorSave = json.getAsJsonObject();
Color color = new Color(colorSave.get("red").getAsInt(), colorSave.get("green").getAsInt(),
return new Color(colorSave.get("red").getAsInt(), colorSave.get("green").getAsInt(),
colorSave.get("blue").getAsInt(), colorSave.get("alpha").getAsInt());
return color;
}
}).create();
@ -301,8 +300,7 @@ public class RRMapDrawOptions {
public static RRMapDrawOptions getOptionsFromFile(String fileName, Logger logger) {
try {
RRMapDrawOptions options = GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class);
return options;
return GSON.fromJson(new FileReader(fileName), RRMapDrawOptions.class);
} catch (FileNotFoundException e) {
logger.debug("Vacuum map draw options file {} not found. Using defaults", fileName);
return new RRMapDrawOptions();

View File

@ -415,9 +415,8 @@ public class MiIoAsyncCommunication {
sendPacket.setData(new byte[MSG_BUFFER_SIZE]);
}
clientSocket.receive(receivePacket);
byte[] response = Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
return Arrays.copyOfRange(receivePacket.getData(), receivePacket.getOffset(),
receivePacket.getOffset() + receivePacket.getLength());
return response;
} catch (SocketTimeoutException e) {
logger.debug("Communication error for Mi device at {}: {}", ip, e.getMessage());
needPing = true;

View File

@ -140,7 +140,7 @@ public class ReadmeHelper {
"|------------------------------------|------------------|------------------------|--------------|------------|\n");
Arrays.asList(MiIoDevices.values()).forEach(device -> {
if (!device.getModel().equals("unknown")) {
if (!"unknown".equals(device.getModel())) {
String link = device.getModel().replace(".", "-");
boolean isSupported = device.getThingType().equals(MiIoBindingConstants.THING_TYPE_UNSUPPORTED);
Boolean experimental = false;

View File

@ -76,13 +76,13 @@ public class RoboMapViewer extends JFrame {
private static final long serialVersionUID = 2623447051590306992L;
@Disabled
public static void main(String args[]) {
public static void main(String[] args) {
System.setProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel");
RoboMapViewer vc = new RoboMapViewer(args);
vc.setVisible(true);
}
public RoboMapViewer(String args[]) {
public RoboMapViewer(String[] args) {
super(TITLE);
parent = this;
setSize(500, 600);
@ -319,9 +319,8 @@ public class RoboMapViewer extends JFrame {
}
protected boolean isRRFile(File fileEntry) {
boolean isRRFile = fileEntry.getName().toLowerCase().endsWith(".rrmap")
return fileEntry.getName().toLowerCase().endsWith(".rrmap")
|| fileEntry.getName().toLowerCase().endsWith(".gz");
return isRRFile;
}
private void loadFirstFile() {