代码优化

This commit is contained in:
MaxKey
2024-01-13 21:48:32 +08:00
parent 47c725624c
commit a1213a7539
64 changed files with 341 additions and 144 deletions

View File

@@ -67,8 +67,9 @@ public final class HexUtils {
int high = Character.digit(hex[i * 2], 16);
int low = Character.digit(hex[i * 2 + 1], 16);
int value = (high << 4) | low;
if (value > 127)
if (value > 127) {
value -= 256;
}
raw[i] = (byte) value;
}
return raw;

View File

@@ -170,14 +170,12 @@ public final class ReciprocalUtils {
}
public static String decoderHex(String ciphers, String secretKey, String algorithm) {
if(StringUtils.isBlank(ciphers))return "";
if (keyLengthCheck(secretKey, algorithm)) {
if(StringUtils.isNotBlank(ciphers) && keyLengthCheck(secretKey, algorithm)) {
byte[] byteSimple = HexUtils.hex2Bytes(ciphers);
return decoder(byteSimple, secretKey, algorithm);
}
return null;
return "";
}
public static String encode2Hex(String simple, String secretKey) {

View File

@@ -69,7 +69,9 @@ public final class X509V3CertGen {
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(publicKeyInputStream !=null)publicKeyInputStream.close();
if(publicKeyInputStream !=null) {
publicKeyInputStream.close();
}
}

View File

@@ -53,7 +53,9 @@ public class DesedeEncoder implements PasswordEncoder {
}
public String decoder(CharSequence encodedPassword) {
if(encodedPassword == null) return null;
if(encodedPassword == null) {
return null;
}
String encodedPasswordString = encodedPassword.toString();
if(encodedPasswordString.startsWith(CRYPT)) {
return ReciprocalUtils.decoderHex(encodedPasswordString.substring(PREFFIX_LENGTH), DEFAULT_SALT);
@@ -64,6 +66,7 @@ public class DesedeEncoder implements PasswordEncoder {
}
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
if(encodedPassword.startsWith(PLAIN)) {
encodedPassword = encode(encodedPassword.substring(PREFFIX_LENGTH));
@@ -78,7 +81,9 @@ public class DesedeEncoder implements PasswordEncoder {
}
public String encode(CharSequence plain,boolean isEncode) {
if(plain == null) return null;
if(plain == null) {
return null;
}
if(isEncode) {
return CRYPT + ReciprocalUtils.encode2Hex(plain + "", DEFAULT_SALT);
}else {

View File

@@ -117,6 +117,7 @@ public class LdapShaPasswordEncoder implements PasswordEncoder {
* @return the encoded password in the specified format
*
*/
@Override
public String encode(CharSequence rawPass) {
byte[] salt = this.saltGenerator.generateKey();
return encode(rawPass, salt);
@@ -172,6 +173,7 @@ public class LdapShaPasswordEncoder implements PasswordEncoder {
*
* @return true if they match (independent of the case of the prefix).
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return matches(rawPassword == null ? null : rawPassword.toString(), encodedPassword);
}

View File

@@ -114,6 +114,7 @@ public class Md4PasswordEncoder implements PasswordEncoder {
* @return Hex string of password digest (or base64 encoded string if
* encodeHashAsBase64 is enabled.
*/
@Override
public String encode(CharSequence rawPassword) {
String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX;
return digest(salt, rawPassword);
@@ -151,6 +152,7 @@ public class Md4PasswordEncoder implements PasswordEncoder {
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);

View File

@@ -130,6 +130,7 @@ public class MessageDigestPasswordEncoder implements PasswordEncoder {
* @return Hex string of password digest (or base64 encoded string if
* encodeHashAsBase64 is enabled.
*/
@Override
public String encode(CharSequence rawPassword) {
String salt = PREFIX + this.saltGenerator.generateKey() + SUFFIX;
return digest(salt, rawPassword);
@@ -160,6 +161,7 @@ public class MessageDigestPasswordEncoder implements PasswordEncoder {
* @param encodedPassword previously encoded password
* @return true or false
*/
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String salt = extractSalt(encodedPassword);
String rawPasswordEncoded = digest(salt, rawPassword);

View File

@@ -52,10 +52,12 @@ import org.springframework.security.crypto.password.PasswordEncoder;
public final class NoOpPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
return rawPassword.toString();
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return rawPassword.toString().equals(encodedPassword);
}

View File

@@ -56,6 +56,7 @@ public class PasswordReciprocal implements PasswordEncoder {
return plain.substring(salt.substring(PREFFIX_LENGTH).length());
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
String salt = encodedPassword.subSequence(0, 29).toString();
String finalPassword = encode(rawPassword,salt);

View File

@@ -53,10 +53,12 @@ public final class StandardPasswordEncoder implements PasswordEncoder {
this("SHA-256", secret);
}
@Override
public String encode(CharSequence rawPassword) {
return encode(rawPassword, saltGenerator.generateKey());
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
byte[] digested = decode(encodedPassword);
byte[] salt = subArray(digested, 0, saltGenerator.getKeyLength());

View File

@@ -47,6 +47,7 @@ public final class DsaSigner implements ISigner {
* */
public static final String SIGNATURE_ALGORITHM = "SHA1withDSA";
@Override
public byte[] sign(byte[] dataBytes, byte[] privateKeyByte) throws Exception {
// ȡ<><C8A1>˽Կ
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyByte);
@@ -63,7 +64,7 @@ public final class DsaSigner implements ISigner {
return signature.sign();
}
@Override
public String signB64(String data, String privateKey) throws Exception {
byte[] privateKeyByte = Base64Utils.decoder(privateKey);
@@ -74,6 +75,7 @@ public final class DsaSigner implements ISigner {
return Base64Utils.encoder(signatureBytes);
}
@Override
public boolean verify(byte[] dataBytes, byte[] publicKeyBytes, byte[] signBytes)throws Exception {
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM.name());
@@ -92,6 +94,7 @@ public final class DsaSigner implements ISigner {
return signature.verify(signBytes);
}
@Override
public boolean verifyB64(String data, String publicKey, String sign)throws Exception {
byte[] privateKeyByte = Base64Utils.decoder(publicKey);

View File

@@ -65,6 +65,7 @@ public final class RsaSigner implements ISigner {
return signature.sign();
}
@Override
public byte[] sign(byte[] dataBytes, byte[] privateKeyBytes) throws Exception {
return sign(dataBytes,privateKeyBytes,SIGNATURE_ALGORITHM);
}
@@ -72,6 +73,7 @@ public final class RsaSigner implements ISigner {
/**
* sign with BASE64 privateKey use SHA1withRSA Algorithm
*/
@Override
public String signB64(String data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decoder(privateKey);
byte[] dataBytes = data.getBytes();
@@ -104,6 +106,7 @@ public final class RsaSigner implements ISigner {
* @see com.connsec.crypto.signature.Signer#verify(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public boolean verify(byte[] dataBytes, byte[] publicKeyBytes , byte[] signBytes)throws Exception {
// verify
return verify(dataBytes,publicKeyBytes,signBytes,SIGNATURE_ALGORITHM);
@@ -115,6 +118,7 @@ public final class RsaSigner implements ISigner {
* @see com.connsec.crypto.signature.Signer#verify(java.lang.String,
* java.lang.String, java.lang.String)
*/
@Override
public boolean verifyB64(String data, String publicKey, String sign)throws Exception {
// <20><><EFBFBD>ܹ<EFBFBD>Կ
byte[] keyBytes = Base64Utils.decoder(publicKey);

View File

@@ -113,6 +113,7 @@ public class JsonPretty implements Pretty{
* @param JSON String
* @return String
*/
@Override
public String format(String jsonString){
return format(JsonParser.parseString(jsonString));
}

View File

@@ -193,10 +193,12 @@ public class XMLHelper {
serializer.setFilter(new LSSerializerFilter() {
@Override
public short acceptNode(Node arg0) {
return FILTER_ACCEPT;
}
@Override
public int getWhatToShow() {
return SHOW_ALL;
}

View File

@@ -67,7 +67,9 @@ public class BeanConvert {
} catch (Exception e) {
e.printStackTrace();
}
if(beanFiledMap==null)return bean;
if(beanFiledMap==null) {
return bean;
}
Iterator<?> fieldit = beanFiledMap.entrySet().iterator();
LogFactory.getLog(BeanConvert.class).debug("map2Bean() *******************************************");
LogFactory.getLog(BeanConvert.class).debug("map2Bean() "+bean.getClass().getName());
@@ -78,7 +80,9 @@ public class BeanConvert {
String fieldName = entry.getKey().toString();
Object value = null;
String fieldType=(String)beanFiledMap.get(fieldName);
if(valueMap.get(fieldName)==null)continue;
if(valueMap.get(fieldName)==null) {
continue;
}
String fillValue=valueMap.get(fieldName).toString();
LogFactory.getLog(BeanConvert.class).debug("map2Bean() field "+(i++)+" : "+fieldName+" = "+fillValue+" type : "+fieldType);
if(fieldType.equals("java.lang.String")){

View File

@@ -30,7 +30,9 @@ import org.apache.commons.logging.LogFactory;
public class BeanUtil {
public static void copyBean(Object origin,Object target) {
if( origin == null || target == null) return;
if( origin == null || target == null) {
return;
}
try {
BeanUtils.copyProperties( origin, target);
} catch (Exception e) {
@@ -40,7 +42,9 @@ public class BeanUtil {
public static Object cloneSupper(Object origin) {
Object target = null;
if(origin == null) return target;
if(origin == null) {
return target;
}
try {
target = origin.getClass().getSuperclass().newInstance();
BeanUtils.copyProperties(target,origin);
@@ -51,7 +55,9 @@ public class BeanUtil {
}
public static String getValue(Object bean,String field ) {
if(bean == null) return null;
if(bean == null) {
return null;
}
String retVal = "";
try {
retVal = BeanUtils.getProperty(bean, field);
@@ -216,8 +222,9 @@ public class BeanUtil {
Map<String, String> map = new HashMap<String, String>();
for (int i = 0; i < flds.length; i++) {
String fieldName = flds[i].getName();
if (isPublicProperty(cls, fieldName))
if (isPublicProperty(cls, fieldName)) {
map.put(flds[i].getName(), flds[i].getType().getName());
}
}
return map;
}
@@ -245,39 +252,61 @@ public class BeanUtil {
e1.printStackTrace();
}
if(fieldType.equals("java.lang.String")){
if(String.valueOf(fillValue)==null)isFieldNotEmpty= false;
if(String.valueOf(fillValue)==null) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("int")){
if(Integer.parseInt(fillValue)==0)isFieldNotEmpty= false;
if(Integer.parseInt(fillValue)==0) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("long")){
if(Long.parseLong(fillValue)==0)isFieldNotEmpty= false;
if(Long.parseLong(fillValue)==0) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("java.lang.Long")){
if(Long.parseLong(fillValue)==0)isFieldNotEmpty= false;
if(Long.parseLong(fillValue)==0) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("double")){
if(Double.valueOf(fillValue)==0.0d)isFieldNotEmpty= false;
if(Double.valueOf(fillValue)==0.0d) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("float")){
if(Float.parseFloat(fillValue)==0.0f)isFieldNotEmpty= false;
if(Float.parseFloat(fillValue)==0.0f) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("java.util.Date")){
try {
value=BeanUtil.get(entity, field.getName());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if(value==null)isFieldNotEmpty= false;
if(value==null) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("java.lang.Object")){
try {
value=BeanUtil.get(entity, field.getName());
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
if(value==null)isFieldNotEmpty= false;
if(value==null) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("char")){
if(Character.valueOf(fillValue.charAt(0))=='\u0000')isFieldNotEmpty= false;
if(Character.valueOf(fillValue.charAt(0))=='\u0000') {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("boolean")){
value=Boolean.parseBoolean(fillValue);
}else if(fieldType.equals("short")){
if(Short.parseShort(fillValue)==0)isFieldNotEmpty= false;
if(Short.parseShort(fillValue)==0) {
isFieldNotEmpty= false;
}
}else if(fieldType.equals("byte")){
if(Byte.parseByte(fillValue)==0)isFieldNotEmpty= false;
if(Byte.parseByte(fillValue)==0) {
isFieldNotEmpty= false;
}
}
LogFactory.getLog(BeanUtil.class).debug("isFieldNotEmpty() fieldName : "+field.getName()+", fieldType : "+fieldType+", Value : "+fillValue+", isFieldNotEmpty : "+isFieldNotEmpty);

View File

@@ -77,13 +77,13 @@ public class DateUtils {
public final static int compareDate(String stringValue1, String stringValue2)
throws ParseException {
Date date1 = tryParse(stringValue1);
if (date1 == null)
throw new ParseException("Can not parse " + stringValue1
+ " to Date.", 0);
if (date1 == null) {
throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0);
}
Date date2 = tryParse(stringValue2);
if (date2 == null)
throw new ParseException("Can not parse " + stringValue1
+ " to Date.", 0);
if (date2 == null) {
throw new ParseException("Can not parse " + stringValue1+ " to Date.", 0);
}
return date1.compareTo(date2);
}
@@ -343,10 +343,12 @@ public class DateUtils {
* @return
*/
public static int getDayOfWeek(int SUN_FST_DAY_OF_WEEK) {
if (SUN_FST_DAY_OF_WEEK > 7 || SUN_FST_DAY_OF_WEEK < 1)
if (SUN_FST_DAY_OF_WEEK > 7 || SUN_FST_DAY_OF_WEEK < 1) {
return 0;
if (SUN_FST_DAY_OF_WEEK == 1)
}
if (SUN_FST_DAY_OF_WEEK == 1) {
return 7;
}
return SUN_FST_DAY_OF_WEEK - 1;
}

View File

@@ -177,6 +177,7 @@ public class EthernetAddress
/**
* Default cloning behaviour (bitwise copy) is just fine...
*/
@Override
public Object clone()
{
return new EthernetAddress(_address);
@@ -418,9 +419,15 @@ public class EthernetAddress
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) return false;
if (o == this) {
return true;
}
if (o == null) {
return false;
}
if (o.getClass() != getClass()) {
return false;
}
return ((EthernetAddress) o)._address == _address;
}
@@ -433,10 +440,13 @@ public class EthernetAddress
* parameter address if they are equal, os positive non-zero number if this address
* should be sorted after parameter
*/
@Override
public int compareTo(EthernetAddress other)
{
long l = _address - other._address;
if (l < 0L) return -1;
if (l < 0L) {
return -1;
}
return (l == 0L) ? 0 : 1;
}

View File

@@ -39,6 +39,7 @@ public class HttpsTrusts {
try {
trustAllHttpsCertificates();
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String urlHostName, SSLSession session) {
System.out.println("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
return true;
@@ -50,6 +51,7 @@ public class HttpsTrusts {
}
static class HttpsTrustsTM implements javax.net.ssl.TrustManager,javax.net.ssl.X509TrustManager {
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
@@ -62,11 +64,13 @@ public class HttpsTrusts {
return true;
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;
}
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
throws java.security.cert.CertificateException {
return;

View File

@@ -56,20 +56,22 @@ public class JdbcUtils {
}
public static void release(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null)
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
System.out.println("SQLException");
}
if (stmt != null)
}
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
System.out.println("SQLException");
}
}
if (conn != null) {
try {
conn.close();
@@ -81,27 +83,30 @@ public class JdbcUtils {
}
public static void release(Connection conn, Statement stmt, PreparedStatement pstmt, ResultSet rs) {
if (rs != null)
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
System.out.println("ResultSet Close Exception");
}
if (stmt != null)
}
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException e) {
System.out.println("Statement Close Exception");
}
if (pstmt != null)
}
if (pstmt != null) {
try {
pstmt.close();
pstmt = null;
} catch (SQLException e) {
System.out.println("PreparedStatement Close Exception");
}
}
if (conn != null) {
try {
conn.close();

View File

@@ -45,9 +45,9 @@ public final class StringUtils extends org.apache.commons.lang3.StringUtils {
try {
byte[] utf8_bytes = strValue.getBytes("UTF-8");
if (utf8_bytes.length <= bytelen)
if (utf8_bytes.length <= bytelen) {
return strValue;
}
byte[] cutoff_bytes = new byte[real_bytelen];
System.arraycopy(utf8_bytes, 0, cutoff_bytes, 0, real_bytelen);
@@ -56,8 +56,9 @@ public final class StringUtils extends org.apache.commons.lang3.StringUtils {
return strResult;
} catch (Exception e) {
if (strValue.length() < strlen)
if (strValue.length() < strlen) {
return strValue;
}
return strValue.substring(0, strlen);
}
@@ -249,8 +250,9 @@ public final class StringUtils extends org.apache.commons.lang3.StringUtils {
public static String list2String(List<String> list, String split) {
String string = "";
if (list == null)
if (list == null) {
return string;
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i) != null && !list.get(i).equals("")) {
string += list.get(i) + split;

View File

@@ -100,18 +100,18 @@ public final class UUIDGenerator {
* @param bytes UUID content
*/
public UUIDGenerator(byte[] bytes) {
if (bytes.length != 16)
if (bytes.length != 16) {
throw new RuntimeException("Attempted to parse malformed UUID: " + Arrays.toString(bytes));
}
content = Arrays.copyOf(bytes, 16);
}
public UUIDGenerator(String id) {
id = id.trim();
if (id.length() != 36)
if (id.length() != 36) {
throw new RuntimeException("Attempted to parse malformed UUID: " + id);
}
content = new byte[16];
char[] chars = id.toCharArray();
@@ -180,12 +180,15 @@ public final class UUIDGenerator {
* @return four bit number representing offset from '0'
*/
private static int intValue(char x) {
if (x >= '0' && x <= '9')
if (x >= '0' && x <= '9') {
return x - '0';
if (x >= 'a' && x <= 'f')
}
if (x >= 'a' && x <= 'f') {
return x - 'a' + 10;
if (x >= 'A' && x <= 'F')
}
if (x >= 'A' && x <= 'F') {
return x - 'A' + 10;
}
throw new RuntimeException("Error parsing UUID at character: " + x);
}
@@ -267,9 +270,9 @@ public final class UUIDGenerator {
* @return id of process that generated the UUID, or -1 for unrecognized format
*/
public int getProcessId() {
if (getVersion() != VERSION)
if (getVersion() != VERSION) {
return -1;
}
return ((content[4] & 0xFF) << 8) | (content[5] & 0xFF);
}
@@ -278,9 +281,9 @@ public final class UUIDGenerator {
* @return millisecond UTC timestamp from generation of the UUID, or null for unrecognized format
*/
public Date getTimestamp() {
if (getVersion() != VERSION)
if (getVersion() != VERSION) {
return null;
}
long time;
time = ((long)content[10] & 0xFF) << 40;
time |= ((long)content[11] & 0xFF) << 32;
@@ -298,9 +301,9 @@ public final class UUIDGenerator {
* @return byte array of UUID fragment, or null for unrecognized format
*/
public byte[] getMacFragment() {
if (getVersion() != 'b')
if (getVersion() != 'b') {
return null;
}
byte[] x = new byte[6];
x[0] = 0;
@@ -315,18 +318,24 @@ public final class UUIDGenerator {
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
UUIDGenerator that = (UUIDGenerator) o;
if (this.content.length != that.content.length)
if (this.content.length != that.content.length) {
return false;
}
for (int i = 0; i < this.content.length; i++)
if (this.content[i] != that.content[i])
for (int i = 0; i < this.content.length; i++) {
if (this.content[i] != that.content[i]) {
return false;
}
}
return true;
}
@@ -341,9 +350,9 @@ public final class UUIDGenerator {
//byte[] mac = NetworkInterface.getNetworkInterfaces().nextElement().getHardwareAddress();
byte[] mac = EthernetAddress.fromInterface().toByteArray();
// if the machine is not connected to a network it has no active MAC address
if (mac == null)
if (mac == null) {
mac = new byte[] {0, 0, 0, 0, 0, 0};
}
return mac;
} catch (Exception e) {
throw new RuntimeException("Could not get MAC address");
@@ -357,9 +366,9 @@ public final class UUIDGenerator {
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('@');
if (index < 1)
if (index < 1) {
throw new RuntimeException("Could not get PID");
}
try {
return Integer.parseInt(jvmName.substring(0, index)) % MAX_PID;
} catch (NumberFormatException e) {

View File

@@ -62,6 +62,7 @@ public class TimestampUUIDGenerator
*
* @throws IllegalStateException if adjustmentOverflow() throws it
*/
@Override
public UUID nextUUID()
{
synchronized(this) {

View File

@@ -111,8 +111,12 @@ public final class UUID implements Serializable
byte[] node)
throws NullPointerException, IllegalArgumentException
{
if(node == null) throw new NullPointerException();
if(node.length != 6) throw new IllegalArgumentException();
if(node == null) {
throw new NullPointerException();
}
if(node.length != 6) {
throw new IllegalArgumentException();
}
this.time_low = time_low;
this.time_mid = time_mid;
@@ -135,20 +139,33 @@ public final class UUID implements Serializable
IllegalArgumentException,
NumberFormatException
{
if(s == null) throw new NullPointerException();
if(s.length() != 36) throw new IllegalArgumentException();
if(s == null) {
throw new NullPointerException();
}
if(s.length() != 36) {
throw new IllegalArgumentException();
}
time_low = parseHex(s.substring(0, 8));
if(s.charAt(8) != '-') throw new IllegalArgumentException();
if(s.charAt(8) != '-') {
throw new IllegalArgumentException();
}
time_mid = (short) parseHex(s.substring(9, 13));
if(s.charAt(13) != '-') throw new IllegalArgumentException();
if(s.charAt(13) != '-') {
throw new IllegalArgumentException();
}
time_hi_and_version = (short) parseHex(s.substring(14, 18));
if(s.charAt(18) != '-') throw new IllegalArgumentException();
if(s.charAt(18) != '-') {
throw new IllegalArgumentException();
}
clock_seq_hi_and_reserved = (byte) parseHex(s.substring(19, 21));
clock_seq_low = (byte) parseHex(s.substring(21, 23));
if(s.charAt(23) != '-') throw new IllegalArgumentException();
if(s.charAt(23) != '-') {
throw new IllegalArgumentException();
}
node = new byte[6];
for(int i = 0; i < 6; i++)
for(int i = 0; i < 6; i++) {
node[i] = (byte) parseHex(s.substring(2 * i + 24, 2 * i + 26));
}
}
/**
@@ -160,7 +177,9 @@ public final class UUID implements Serializable
*/
public UUID(DataInput in) throws IOException
{
if(in == null) throw new NullPointerException();
if(in == null) {
throw new NullPointerException();
}
readData(in);
}
@@ -172,8 +191,12 @@ public final class UUID implements Serializable
*/
public UUID(byte[] data)
{
if(data == null) throw new NullPointerException();
if(data.length != 16) throw new IllegalArgumentException();
if(data == null) {
throw new NullPointerException();
}
if(data.length != 16) {
throw new IllegalArgumentException();
}
try {
readData(new DataInputStream(new ByteArrayInputStream(data)));
} catch(IOException ex) {
@@ -221,19 +244,22 @@ public final class UUID implements Serializable
/*
* Returns true if two UUIDs are equal by value.
*/
public boolean equals(Object obj)
{
if(obj == null || !(obj instanceof UUID))
@Override
public boolean equals(Object obj){
if(obj == null || !(obj instanceof UUID)) {
return false;
}
UUID other = (UUID) obj;
if(this == other) return true;
if(this == other) {
return true;
}
if(hash_code != 0 &&
other.hash_code != 0 &&
hash_code != other.hash_code)
hash_code != other.hash_code) {
return false;
}
return
time_low == other.time_low &&
@@ -247,14 +273,16 @@ public final class UUID implements Serializable
/**
* Returns a hash code for this UUID.
*/
@Override
public int hashCode()
{
if(hash_code == 0) {
synchronized(this) {
if(hash_code == 0) {
hash_code = toString().hashCode();
if(hash_code == 0)
if(hash_code == 0) {
hash_code = -1;
}
}
}
}
@@ -266,9 +294,9 @@ public final class UUID implements Serializable
*/
private static void appendHex(StringBuffer sb, long num, int digits)
{
if(digits > 0 && digits < 16)
if(digits > 0 && digits < 16) {
num = num & ((1L << (digits * 4)) - 1);
}
String str = Long.toHexString(num);
int len = str.length();
while(len < digits) {
@@ -283,15 +311,16 @@ public final class UUID implements Serializable
*/
private static int parseHex(String s) throws NumberFormatException
{
if(s.charAt(0) == '-')
if(s.charAt(0) == '-') {
throw new NumberFormatException();
}
return Integer.parseInt(s, 16);
}
/**
* Returns the string representation of this UUID.
*/
@Override
public String toString()
{
if(string_rep == null) {
@@ -307,8 +336,9 @@ public final class UUID implements Serializable
appendHex(sb, clock_seq_hi_and_reserved, 2);
appendHex(sb, clock_seq_low, 2);
sb.append('-');
for(int i = 0; i < 6; i++)
for(int i = 0; i < 6; i++) {
appendHex(sb, node[i], 2);
}
string_rep = sb.toString();
}
}
@@ -343,9 +373,9 @@ public final class UUID implements Serializable
*/
public static UUID generate()
{
if(default_generator == null)
if(default_generator == null) {
default_generator = new TimestampUUIDGenerator(UUIDRandomness.randomClockSequence(), NodeIDGetter.getNodeID());
}
return default_generator.nextUUID();
}

View File

@@ -69,7 +69,9 @@ public final class UUIDRandomness
synchronized(random) {
next = random.nextInt(16383);
}
if(next >= prev) next++;
if(next >= prev) {
next++;
}
return next;
}
}

View File

@@ -69,13 +69,15 @@ public class UnsynchronizedTimestampUUIDGenerator implements UUIDGenerator
public UnsynchronizedTimestampUUIDGenerator(int clock_sequence,
byte[] node)
{
if(clock_sequence < 0 || clock_sequence >= 16384)
if(clock_sequence < 0 || clock_sequence >= 16384) {
throw new IllegalArgumentException();
if(node == null)
}
if(node == null) {
throw new NullPointerException();
if(node.length != 6)
}
if(node.length != 6) {
throw new IllegalArgumentException();
}
this.clock_sequence = clock_sequence;
this.node = (byte[]) node.clone();
checkSystemTime();
@@ -89,8 +91,9 @@ public class UnsynchronizedTimestampUUIDGenerator implements UUIDGenerator
long sys_time = System.currentTimeMillis();
/* If monotonicity is lost, bump clock_sequence. */
if(sys_time < last_time)
if(sys_time < last_time) {
clock_sequence = UUIDRandomness.nextRandomClockSequence(clock_sequence);
}
/* If the clock ticked, clear the adjustment. */
if(sys_time != last_time) {
@@ -106,8 +109,9 @@ public class UnsynchronizedTimestampUUIDGenerator implements UUIDGenerator
protected void adjustmentOverflow() throws IllegalStateException
{
checkSystemTime();
if(clock_adj >= CLOCK_RES)
if(clock_adj >= CLOCK_RES) {
throw new IllegalStateException();
}
}
/**
@@ -115,10 +119,13 @@ public class UnsynchronizedTimestampUUIDGenerator implements UUIDGenerator
*
* @throws IllegalStateException if adjustmentOverflow() throws it
*/
@Override
public UUID nextUUID()
{
long unique_time = (last_time + EPOCH_OFFSET) * CLOCK_RES + clock_adj;
if(++clock_adj > CLOCK_RES) adjustmentOverflow();
if(++clock_adj > CLOCK_RES) {
adjustmentOverflow();
}
return new UUID((int) (unique_time & 0xFFFFFFFF),
(short) ((unique_time >> 32) & 0xFFFF),