Encode transport properties more compactly in QR codes.

This commit is contained in:
akwizgran
2016-11-07 16:25:30 +00:00
parent 7327029fca
commit 04d4ecad05
20 changed files with 326 additions and 168 deletions

View File

@@ -1,24 +1,34 @@
package org.briarproject.util;
import org.briarproject.api.nullsafety.NotNullByDefault;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.Collection;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import static java.nio.charset.CodingErrorAction.IGNORE;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
@NotNullByDefault
public class StringUtils {
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static Pattern MAC = Pattern.compile("[0-9a-f]{2}:[0-9a-f]{2}:" +
"[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}:[0-9a-f]{2}",
CASE_INSENSITIVE);
private static final char[] HEX = new char[] {
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
};
public static boolean isNullOrEmpty(String s) {
public static boolean isNullOrEmpty(@Nullable String s) {
return s == null || s.length() == 0;
}
@@ -61,7 +71,9 @@ public class StringUtils {
return fromUtf8(utf8, 0, maxUtf8Length);
}
/** Converts the given byte array to a hex character array. */
/**
* Converts the given byte array to a hex character array.
*/
private static char[] toHexChars(byte[] bytes) {
char[] hex = new char[bytes.length * 2];
for (int i = 0, j = 0; i < bytes.length; i++) {
@@ -71,12 +83,16 @@ public class StringUtils {
return hex;
}
/** Converts the given byte array to a hex string. */
/**
* Converts the given byte array to a hex string.
*/
public static String toHexString(byte[] bytes) {
return new String(toHexChars(bytes));
}
/** Converts the given hex string to a byte array. */
/**
* Converts the given hex string to a byte array.
*/
public static byte[] fromHexString(String hex) {
int len = hex.length();
if (len % 2 != 0)
@@ -107,4 +123,20 @@ public class StringUtils {
public static boolean utf8IsTooLong(String s, int maxLength) {
return toUtf8(s).length > maxLength;
}
public static byte[] macToBytes(String mac) {
if (!MAC.matcher(mac).matches()) throw new IllegalArgumentException();
return fromHexString(mac.replaceAll(":", ""));
}
public static String macToString(byte[] mac) {
if (mac.length != 6) throw new IllegalArgumentException();
StringBuilder s = new StringBuilder();
for (byte b : mac) {
if (s.length() > 0) s.append(':');
s.append(HEX[(b >> 4) & 0xF]);
s.append(HEX[b & 0xF]);
}
return s.toString();
}
}