HBASE-23626 Reduced number of Checkstyle violations in tests in hbase-common

Signed-off-by: stack <stack@apache.org>
This commit is contained in:
Jan Hentschel 2020-01-18 20:32:51 +01:00 committed by GitHub
parent 71bfac3353
commit dc602d7d5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 376 additions and 356 deletions

View File

@ -45,7 +45,6 @@ import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
@Category(SmallTests.class)
public class TestStruct {
private Struct generic;
@SuppressWarnings("rawtypes")
private DataType specialized;
@ -61,12 +60,12 @@ public class TestStruct {
@Parameters
public static Collection<Object[]> params() {
Object[][] pojo1Args = {
new Object[] { "foo", 5, 10.001 },
new Object[] { "foo", 100, 7.0 },
new Object[] { "foo", 100, 10.001 },
new Object[] { "bar", 5, 10.001 },
new Object[] { "bar", 100, 10.001 },
new Object[] { "baz", 5, 10.001 },
new Object[] { "foo", 5, 10.001 },
new Object[] { "foo", 100, 7.0 },
new Object[] { "foo", 100, 10.001 },
new Object[] { "bar", 5, 10.001 },
new Object[] { "bar", 100, 10.001 },
new Object[] { "baz", 5, 10.001 },
};
Object[][] pojo2Args = {
@ -78,22 +77,27 @@ public class TestStruct {
};
Object[][] params = new Object[][] {
{ SpecializedPojo1Type1.GENERIC, new SpecializedPojo1Type1(), pojo1Args },
{ SpecializedPojo2Type1.GENERIC, new SpecializedPojo2Type1(), pojo2Args },
{ SpecializedPojo1Type1.getGeneric(), new SpecializedPojo1Type1(), pojo1Args },
{ SpecializedPojo2Type1.getGeneric(), new SpecializedPojo2Type1(), pojo2Args },
};
return Arrays.asList(params);
}
static final Comparator<byte[]> NULL_SAFE_BYTES_COMPARATOR =
new Comparator<byte[]>() {
@Override
public int compare(byte[] o1, byte[] o2) {
if (o1 == o2) return 0;
if (null == o1) return -1;
if (null == o2) return 1;
return Bytes.compareTo(o1, o2);
}
};
static final Comparator<byte[]> NULL_SAFE_BYTES_COMPARATOR = new Comparator<byte[]>() {
@Override
public int compare(byte[] o1, byte[] o2) {
if (o1 == o2) {
return 0;
}
if (null == o1) {
return -1;
}
if (null == o2) {
return 1;
}
return Bytes.compareTo(o1, o2);
}
};
/**
* A simple object to serialize.
@ -161,20 +165,18 @@ public class TestStruct {
return false;
}
Pojo1 other = (Pojo1) obj;
if (Double.doubleToLongBits(doubleFieldAsc) != Double.doubleToLongBits(other.doubleFieldAsc)) {
if (Double.doubleToLongBits(doubleFieldAsc) !=
Double.doubleToLongBits(other.doubleFieldAsc)) {
return false;
}
if (intFieldAsc != other.intFieldAsc) {
return false;
}
if (stringFieldAsc == null) {
if (other.stringFieldAsc != null) {
return false;
}
} else if (!stringFieldAsc.equals(other.stringFieldAsc)) {
return false;
return other.stringFieldAsc == null;
} else {
return stringFieldAsc.equals(other.stringFieldAsc);
}
return true;
}
}
@ -220,16 +222,17 @@ public class TestStruct {
if (cmp != 0) {
return cmp;
}
if (null == stringFieldDsc) {
cmp = 1;
}
else if (null == o.stringFieldDsc) {
} else if (null == o.stringFieldDsc) {
cmp = -1;
}
else if (stringFieldDsc.equals(o.stringFieldDsc)) {
} else if (stringFieldDsc.equals(o.stringFieldDsc)) {
cmp = 0;
} else {
cmp = -stringFieldDsc.compareTo(o.stringFieldDsc);
}
else cmp = -stringFieldDsc.compareTo(o.stringFieldDsc);
if (cmp != 0) {
return cmp;
}
@ -269,13 +272,10 @@ public class TestStruct {
return false;
}
if (stringFieldDsc == null) {
if (other.stringFieldDsc != null) {
return false;
}
} else if (!stringFieldDsc.equals(other.stringFieldDsc)) {
return false;
return other.stringFieldDsc == null;
} else {
return stringFieldDsc.equals(other.stringFieldDsc);
}
return true;
}
}
@ -283,7 +283,6 @@ public class TestStruct {
* A custom data type implementation specialized for {@link Pojo1}.
*/
private static class SpecializedPojo1Type1 implements DataType<Pojo1> {
private static final RawStringTerminated stringField = new RawStringTerminated("/");
private static final RawInteger intField = new RawInteger();
private static final RawDouble doubleField = new RawDouble();
@ -291,34 +290,42 @@ public class TestStruct {
/**
* The {@link Struct} equivalent of this type.
*/
public static Struct GENERIC =
new StructBuilder().add(stringField)
.add(intField)
.add(doubleField)
.toStruct();
public static Struct getGeneric() {
return new StructBuilder().add(stringField).add(intField)
.add(doubleField).toStruct();
}
@Override
public boolean isOrderPreserving() { return true; }
public boolean isOrderPreserving() {
return true;
}
@Override
public Order getOrder() { return null; }
public Order getOrder() {
return null;
}
@Override
public boolean isNullable() { return false; }
public boolean isNullable() {
return false;
}
@Override
public boolean isSkippable() { return true; }
public boolean isSkippable() {
return true;
}
@Override
public int encodedLength(Pojo1 val) {
return
stringField.encodedLength(val.stringFieldAsc) +
return stringField.encodedLength(val.stringFieldAsc) +
intField.encodedLength(val.intFieldAsc) +
doubleField.encodedLength(val.doubleFieldAsc);
}
@Override
public Class<Pojo1> encodedClass() { return Pojo1.class; }
public Class<Pojo1> encodedClass() {
return Pojo1.class;
}
@Override
public int skip(PositionedByteRange src) {
@ -350,7 +357,6 @@ public class TestStruct {
* A custom data type implementation specialized for {@link Pojo2}.
*/
private static class SpecializedPojo2Type1 implements DataType<Pojo2> {
private static RawBytesTerminated byteField1 = new RawBytesTerminated("/");
private static RawBytesTerminated byteField2 =
new RawBytesTerminated(Order.DESCENDING, "/");
@ -361,36 +367,43 @@ public class TestStruct {
/**
* The {@link Struct} equivalent of this type.
*/
public static Struct GENERIC =
new StructBuilder().add(byteField1)
.add(byteField2)
.add(stringField)
.add(byteField3)
.toStruct();
public static Struct getGeneric() {
return new StructBuilder().add(byteField1).add(byteField2)
.add(stringField).add(byteField3).toStruct();
}
@Override
public boolean isOrderPreserving() { return true; }
public boolean isOrderPreserving() {
return true;
}
@Override
public Order getOrder() { return null; }
public Order getOrder() {
return null;
}
@Override
public boolean isNullable() { return false; }
public boolean isNullable() {
return false;
}
@Override
public boolean isSkippable() { return true; }
public boolean isSkippable() {
return true;
}
@Override
public int encodedLength(Pojo2 val) {
return
byteField1.encodedLength(val.byteField1Asc) +
return byteField1.encodedLength(val.byteField1Asc) +
byteField2.encodedLength(val.byteField2Dsc) +
stringField.encodedLength(val.stringFieldDsc) +
byteField3.encodedLength(val.byteField3Dsc);
}
@Override
public Class<Pojo2> encodedClass() { return Pojo2.class; }
public Class<Pojo2> encodedClass() {
return Pojo2.class;
}
@Override
public int skip(PositionedByteRange src) {

View File

@ -18,7 +18,6 @@
package org.apache.hadoop.hbase.types;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.apache.hadoop.hbase.testclassification.SmallTests;
import org.apache.hadoop.hbase.util.Order;
@ -29,12 +28,10 @@ import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestUnion2 {
/**
* An example <code>Union</code>
*/
private static class SampleUnion1 extends Union2<Integer, String> {
private static final byte IS_INTEGER = 0x00;
private static final byte IS_STRING = 0x01;
@ -72,13 +69,19 @@ public class TestUnion2 {
String s = null;
try {
i = (Integer) val;
} catch (ClassCastException e) {}
} catch (ClassCastException ignored) {}
try {
s = (String) val;
} catch (ClassCastException e) {}
} catch (ClassCastException ignored) {}
if (null != i) {
return 1 + typeA.encodedLength(i);
}
if (null != s) {
return 1 + typeB.encodedLength(s);
}
if (null != i) return 1 + typeA.encodedLength(i);
if (null != s) return 1 + typeB.encodedLength(s);
throw new IllegalArgumentException("val is not a valid member of this union.");
}
@ -88,10 +91,10 @@ public class TestUnion2 {
String s = null;
try {
i = (Integer) val;
} catch (ClassCastException e) {}
} catch (ClassCastException ignored) {}
try {
s = (String) val;
} catch (ClassCastException e) {}
} catch (ClassCastException ignored) {}
if (null != i) {
dst.put(IS_INTEGER);
@ -99,31 +102,31 @@ public class TestUnion2 {
} else if (null != s) {
dst.put(IS_STRING);
return 1 + typeB.encode(dst, s);
}
else
} else {
throw new IllegalArgumentException("val is not of a supported type.");
}
}
}
@Test
public void testEncodeDecode() {
Integer intVal = Integer.valueOf(10);
Integer intVal = 10;
String strVal = "hello";
PositionedByteRange buff = new SimplePositionedMutableByteRange(10);
SampleUnion1 type = new SampleUnion1();
type.encode(buff, intVal);
buff.setPosition(0);
assertTrue(0 == intVal.compareTo(type.decodeA(buff)));
assertEquals(0, intVal.compareTo(type.decodeA(buff)));
buff.setPosition(0);
type.encode(buff, strVal);
buff.setPosition(0);
assertTrue(0 == strVal.compareTo(type.decodeB(buff)));
assertEquals(0, strVal.compareTo(type.decodeB(buff)));
}
@Test
public void testSkip() {
Integer intVal = Integer.valueOf(10);
Integer intVal = 10;
String strVal = "hello";
PositionedByteRange buff = new SimplePositionedMutableByteRange(10);
SampleUnion1 type = new SampleUnion1();

View File

@ -18,6 +18,7 @@
package org.apache.hadoop.hbase.util;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.BufferedWriter;
import java.io.File;
@ -45,11 +46,14 @@ import org.apache.hadoop.fs.Path;
/**
* Some utilities to help class loader testing
*/
public class ClassLoaderTestHelper {
public final class ClassLoaderTestHelper {
private static final Log LOG = LogFactory.getLog(ClassLoaderTestHelper.class);
private static final int BUFFER_SIZE = 4096;
private ClassLoaderTestHelper() {
}
/**
* Jar a list of files into a jar archive.
*
@ -59,28 +63,29 @@ public class ClassLoaderTestHelper {
*/
private static boolean createJarArchive(File archiveFile, File[] tobeJared) {
try {
byte buffer[] = new byte[BUFFER_SIZE];
byte[] buffer = new byte[BUFFER_SIZE];
// Open archive file
FileOutputStream stream = new FileOutputStream(archiveFile);
JarOutputStream out = new JarOutputStream(stream, new Manifest());
for (int i = 0; i < tobeJared.length; i++) {
if (tobeJared[i] == null || !tobeJared[i].exists()
|| tobeJared[i].isDirectory()) {
for (File file : tobeJared) {
if (file == null || !file.exists() || file.isDirectory()) {
continue;
}
// Add archive entry
JarEntry jarAdd = new JarEntry(tobeJared[i].getName());
jarAdd.setTime(tobeJared[i].lastModified());
JarEntry jarAdd = new JarEntry(file.getName());
jarAdd.setTime(file.lastModified());
out.putNextEntry(jarAdd);
// Write file to archive
FileInputStream in = new FileInputStream(tobeJared[i]);
FileInputStream in = new FileInputStream(file);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
if (nRead <= 0) {
break;
}
out.write(buffer, 0, nRead);
}
in.close();
@ -104,7 +109,7 @@ public class ClassLoaderTestHelper {
* @param testDir the folder under which to store the test class and jar
* @param className the test class name
* @param code the optional test class code, which can be null.
* If null, a bare empty class will be used
* If null, a bare empty class will be used
* @return the test jar file generated
*/
public static File buildJar(String testDir,
@ -119,7 +124,7 @@ public class ClassLoaderTestHelper {
* @param testDir the folder under which to store the test class
* @param className the test class name
* @param code the optional test class code, which can be null.
* If null, an empty class will be used
* If null, an empty class will be used
* @param folder the folder under which to store the generated jar
* @return the test jar file generated
*/
@ -136,13 +141,13 @@ public class ClassLoaderTestHelper {
// compile it by JavaCompiler
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
ArrayList<String> srcFileNames = new ArrayList<String>();
ArrayList<String> srcFileNames = new ArrayList<>();
srcFileNames.add(sourceCodeFile.toString());
StandardJavaFileManager fm = compiler.getStandardFileManager(null, null,
null);
Iterable<? extends JavaFileObject> cu =
fm.getJavaFileObjects(sourceCodeFile);
List<String> options = new ArrayList<String>();
List<String> options = new ArrayList<>();
options.add("-classpath");
// only add hbase classes to classpath. This is a little bit tricky: assume
// the classpath is {hbaseSrc}/target/classes.
@ -165,7 +170,7 @@ public class ClassLoaderTestHelper {
jarFile.getParentFile().mkdirs();
if (!createJarArchive(jarFile,
new File[]{new File(srcDir.toString(), className + ".class")})){
assertTrue("Build jar file failed.", false);
fail("Build jar file failed.");
}
return jarFile;
}
@ -185,7 +190,7 @@ public class ClassLoaderTestHelper {
String libPrefix, File... srcJars) throws Exception {
FileOutputStream stream = new FileOutputStream(targetJar);
JarOutputStream out = new JarOutputStream(stream, new Manifest());
byte buffer[] = new byte[BUFFER_SIZE];
byte[] buffer = new byte[BUFFER_SIZE];
for (File jarFile: srcJars) {
// Add archive entry
@ -197,8 +202,10 @@ public class ClassLoaderTestHelper {
FileInputStream in = new FileInputStream(jarFile);
while (true) {
int nRead = in.read(buffer, 0, buffer.length);
if (nRead <= 0)
if (nRead <= 0) {
break;
}
out.write(buffer, 0, nRead);
}
in.close();
@ -212,5 +219,4 @@ public class ClassLoaderTestHelper {
return conf.get(ClassLoaderBase.LOCAL_DIR_KEY)
+ File.separator + "jars" + File.separator;
}
}

View File

@ -1,5 +1,4 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@ -23,7 +22,9 @@ package org.apache.hadoop.hbase.util;
* the use of the injectEdge method giving it default permissions, but in
* testing we may need to use this functionality elsewhere.
*/
public class EnvironmentEdgeManagerTestHelper {
public final class EnvironmentEdgeManagerTestHelper {
private EnvironmentEdgeManagerTestHelper() {
}
public static void reset() {
EnvironmentEdgeManager.reset();

View File

@ -17,6 +17,8 @@
*/
package org.apache.hadoop.hbase.util;
import static org.junit.Assert.assertArrayEquals;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
@ -38,10 +40,8 @@ import org.apache.hadoop.io.WritableUtils;
import org.junit.Assert;
import org.junit.experimental.categories.Category;
@Category(SmallTests.class)
public class TestBytes extends TestCase {
private static void setUnsafe(boolean value) throws Exception {
Field field = Bytes.class.getDeclaredField("UNSAFE_UNALIGNED");
field.setAccessible(true);
@ -95,141 +95,141 @@ public class TestBytes extends TestCase {
assertNotNull(ee);
}
public void testAdd () throws Exception {
public void testAdd() {
byte[] a = {0,0,0,0,0,0,0,0,0,0};
byte[] b = {1,1,1,1,1,1,1,1,1,1,1};
byte[] c = {2,2,2,2,2,2,2,2,2,2,2,2};
byte[] d = {3,3,3,3,3,3,3,3,3,3,3,3,3};
byte[] result1 = Bytes.add (a, b, c);
byte[] result2 = Bytes.add (new byte[][] {a, b, c});
byte[] result1 = Bytes.add(a, b, c);
byte[] result2 = Bytes.add(new byte[][] {a, b, c});
assertEquals(0, Bytes.compareTo(result1, result2));
byte[] result4 = Bytes.add (result1, d);
byte[] result5 = Bytes.add (new byte[][] {result1, d});
byte[] result4 = Bytes.add(result1, d);
byte[] result5 = Bytes.add(new byte[][] {result1, d});
assertEquals(0, Bytes.compareTo(result1, result2));
}
public void testSplit() throws Exception {
byte [] lowest = Bytes.toBytes("AAA");
byte [] middle = Bytes.toBytes("CCC");
byte [] highest = Bytes.toBytes("EEE");
byte [][] parts = Bytes.split(lowest, highest, 1);
for (int i = 0; i < parts.length; i++) {
System.out.println(Bytes.toString(parts[i]));
public void testSplit() {
byte[] lowest = Bytes.toBytes("AAA");
byte[] middle = Bytes.toBytes("CCC");
byte[] highest = Bytes.toBytes("EEE");
byte[][] parts = Bytes.split(lowest, highest, 1);
for (byte[] bytes : parts) {
System.out.println(Bytes.toString(bytes));
}
assertEquals(3, parts.length);
assertTrue(Bytes.equals(parts[1], middle));
// Now divide into three parts. Change highest so split is even.
highest = Bytes.toBytes("DDD");
parts = Bytes.split(lowest, highest, 2);
for (int i = 0; i < parts.length; i++) {
System.out.println(Bytes.toString(parts[i]));
for (byte[] part : parts) {
System.out.println(Bytes.toString(part));
}
assertEquals(4, parts.length);
// Assert that 3rd part is 'CCC'.
assertTrue(Bytes.equals(parts[2], middle));
}
public void testSplit2() throws Exception {
public void testSplit2() {
// More split tests.
byte [] lowest = Bytes.toBytes("http://A");
byte [] highest = Bytes.toBytes("http://z");
byte [] middle = Bytes.toBytes("http://]");
byte [][] parts = Bytes.split(lowest, highest, 1);
for (int i = 0; i < parts.length; i++) {
System.out.println(Bytes.toString(parts[i]));
for (byte[] part : parts) {
System.out.println(Bytes.toString(part));
}
assertEquals(3, parts.length);
assertTrue(Bytes.equals(parts[1], middle));
}
public void testSplit3() throws Exception {
public void testSplit3() {
// Test invalid split cases
byte [] low = { 1, 1, 1 };
byte [] high = { 1, 1, 3 };
byte[] low = { 1, 1, 1 };
byte[] high = { 1, 1, 3 };
// If swapped, should throw IAE
try {
Bytes.split(high, low, 1);
assertTrue("Should not be able to split if low > high", false);
fail("Should not be able to split if low > high");
} catch(IllegalArgumentException iae) {
// Correct
}
// Single split should work
byte [][] parts = Bytes.split(low, high, 1);
byte[][] parts = Bytes.split(low, high, 1);
for (int i = 0; i < parts.length; i++) {
System.out.println("" + i + " -> " + Bytes.toStringBinary(parts[i]));
}
assertTrue("Returned split should have 3 parts but has " + parts.length, parts.length == 3);
assertEquals("Returned split should have 3 parts but has " + parts.length, 3, parts.length);
// If split more than once, use additional byte to split
parts = Bytes.split(low, high, 2);
assertTrue("Split with an additional byte", parts != null);
assertNotNull("Split with an additional byte", parts);
assertEquals(parts.length, low.length + 1);
// Split 0 times should throw IAE
try {
parts = Bytes.split(low, high, 0);
assertTrue("Should not be able to split 0 times", false);
Bytes.split(low, high, 0);
fail("Should not be able to split 0 times");
} catch(IllegalArgumentException iae) {
// Correct
}
}
public void testToInt() throws Exception {
int [] ints = {-1, 123, Integer.MIN_VALUE, Integer.MAX_VALUE};
for (int i = 0; i < ints.length; i++) {
byte [] b = Bytes.toBytes(ints[i]);
assertEquals(ints[i], Bytes.toInt(b));
byte [] b2 = bytesWithOffset(b);
assertEquals(ints[i], Bytes.toInt(b2, 1));
assertEquals(ints[i], Bytes.toInt(b2, 1, Bytes.SIZEOF_INT));
public void testToInt() {
int[] ints = { -1, 123, Integer.MIN_VALUE, Integer.MAX_VALUE };
for (int anInt : ints) {
byte[] b = Bytes.toBytes(anInt);
assertEquals(anInt, Bytes.toInt(b));
byte[] b2 = bytesWithOffset(b);
assertEquals(anInt, Bytes.toInt(b2, 1));
assertEquals(anInt, Bytes.toInt(b2, 1, Bytes.SIZEOF_INT));
}
}
public void testToLong() throws Exception {
long [] longs = {-1l, 123l, Long.MIN_VALUE, Long.MAX_VALUE};
for (int i = 0; i < longs.length; i++) {
byte [] b = Bytes.toBytes(longs[i]);
assertEquals(longs[i], Bytes.toLong(b));
byte [] b2 = bytesWithOffset(b);
assertEquals(longs[i], Bytes.toLong(b2, 1));
assertEquals(longs[i], Bytes.toLong(b2, 1, Bytes.SIZEOF_LONG));
public void testToLong() {
long[] longs = { -1L, 123L, Long.MIN_VALUE, Long.MAX_VALUE };
for (long aLong : longs) {
byte[] b = Bytes.toBytes(aLong);
assertEquals(aLong, Bytes.toLong(b));
byte[] b2 = bytesWithOffset(b);
assertEquals(aLong, Bytes.toLong(b2, 1));
assertEquals(aLong, Bytes.toLong(b2, 1, Bytes.SIZEOF_LONG));
}
}
public void testToFloat() throws Exception {
float [] floats = {-1f, 123.123f, Float.MAX_VALUE};
for (int i = 0; i < floats.length; i++) {
byte [] b = Bytes.toBytes(floats[i]);
assertEquals(floats[i], Bytes.toFloat(b), 0.0f);
byte [] b2 = bytesWithOffset(b);
assertEquals(floats[i], Bytes.toFloat(b2, 1), 0.0f);
public void testToFloat() {
float[] floats = { -1f, 123.123f, Float.MAX_VALUE };
for (float aFloat : floats) {
byte[] b = Bytes.toBytes(aFloat);
assertEquals(aFloat, Bytes.toFloat(b), 0.0f);
byte[] b2 = bytesWithOffset(b);
assertEquals(aFloat, Bytes.toFloat(b2, 1), 0.0f);
}
}
public void testToDouble() throws Exception {
public void testToDouble() {
double [] doubles = {Double.MIN_VALUE, Double.MAX_VALUE};
for (int i = 0; i < doubles.length; i++) {
byte [] b = Bytes.toBytes(doubles[i]);
assertEquals(doubles[i], Bytes.toDouble(b), 0.0);
byte [] b2 = bytesWithOffset(b);
assertEquals(doubles[i], Bytes.toDouble(b2, 1), 0.0);
for (double aDouble : doubles) {
byte[] b = Bytes.toBytes(aDouble);
assertEquals(aDouble, Bytes.toDouble(b), 0.0);
byte[] b2 = bytesWithOffset(b);
assertEquals(aDouble, Bytes.toDouble(b2, 1), 0.0);
}
}
public void testToBigDecimal() throws Exception {
BigDecimal [] decimals = {new BigDecimal("-1"), new BigDecimal("123.123"),
new BigDecimal("123123123123")};
for (int i = 0; i < decimals.length; i++) {
byte [] b = Bytes.toBytes(decimals[i]);
assertEquals(decimals[i], Bytes.toBigDecimal(b));
byte [] b2 = bytesWithOffset(b);
assertEquals(decimals[i], Bytes.toBigDecimal(b2, 1, b.length));
public void testToBigDecimal() {
BigDecimal[] decimals = { new BigDecimal("-1"), new BigDecimal("123.123"),
new BigDecimal("123123123123") };
for (BigDecimal decimal : decimals) {
byte[] b = Bytes.toBytes(decimal);
assertEquals(decimal, Bytes.toBigDecimal(b));
byte[] b2 = bytesWithOffset(b);
assertEquals(decimal, Bytes.toBigDecimal(b2, 1, b.length));
}
}
private byte [] bytesWithOffset(byte [] src) {
private byte[] bytesWithOffset(byte[] src) {
// add one byte in front to test offset
byte [] result = new byte[src.length + 1];
result[0] = (byte) 0xAA;
@ -245,7 +245,7 @@ public class TestBytes extends TestCase {
byte[] actual = Bytes.toBytes(target);
byte[] expected = { 0, 1, 2, 3, 4, 5, 6 };
assertTrue(Arrays.equals(expected, actual));
assertArrayEquals(expected, actual);
assertEquals(2, target.position());
assertEquals(7, target.limit());
@ -255,7 +255,7 @@ public class TestBytes extends TestCase {
byte[] actual2 = Bytes.toBytes(target2);
byte[] expected2 = { 2, 3, 4, 5, 6 };
assertTrue(Arrays.equals(expected2, actual2));
assertArrayEquals(expected2, actual2);
assertEquals(0, target2.position());
assertEquals(5, target2.limit());
}
@ -268,21 +268,21 @@ public class TestBytes extends TestCase {
byte[] actual = Bytes.getBytes(target);
byte[] expected = { 2, 3, 4, 5, 6 };
assertTrue(Arrays.equals(expected, actual));
assertArrayEquals(expected, actual);
assertEquals(2, target.position());
assertEquals(7, target.limit());
}
public void testReadAsVLong() throws Exception {
long [] longs = {-1l, 123l, Long.MIN_VALUE, Long.MAX_VALUE};
for (int i = 0; i < longs.length; i++) {
long[] longs = { -1L, 123L, Long.MIN_VALUE, Long.MAX_VALUE };
for (long aLong : longs) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream output = new DataOutputStream(baos);
WritableUtils.writeVLong(output, longs[i]);
WritableUtils.writeVLong(output, aLong);
byte[] long_bytes_no_offset = baos.toByteArray();
assertEquals(longs[i], Bytes.readAsVLong(long_bytes_no_offset, 0));
assertEquals(aLong, Bytes.readAsVLong(long_bytes_no_offset, 0));
byte[] long_bytes_with_offset = bytesWithOffset(long_bytes_no_offset);
assertEquals(longs[i], Bytes.readAsVLong(long_bytes_with_offset, 1));
assertEquals(aLong, Bytes.readAsVLong(long_bytes_with_offset, 1));
}
}
@ -313,23 +313,23 @@ public class TestBytes extends TestCase {
assertEquals(expected, actual);
}
public void testBinarySearch() throws Exception {
byte [][] arr = {
{1},
{3},
{5},
{7},
{9},
{11},
{13},
{15},
public void testBinarySearch() {
byte[][] arr = {
{ 1 },
{ 3 },
{ 5 },
{ 7 },
{ 9 },
{ 11 },
{ 13 },
{ 15 },
};
byte [] key1 = {3,1};
byte [] key2 = {4,9};
byte [] key2_2 = {4};
byte [] key3 = {5,11};
byte [] key4 = {0};
byte [] key5 = {2};
byte[] key1 = { 3, 1 };
byte[] key2 = { 4, 9 };
byte[] key2_2 = { 4 };
byte[] key3 = { 5, 11 };
byte[] key4 = { 0 };
byte[] key5 = { 2 };
assertEquals(1, Bytes.binarySearch(arr, key1, 0, 1,
Bytes.BYTES_RAWCOMPARATOR));
@ -393,8 +393,7 @@ public class TestBytes extends TestCase {
assertFalse(Bytes.startsWith(Bytes.toBytes(""), Bytes.toBytes("hello")));
}
public void testIncrementBytes() throws IOException {
public void testIncrementBytes() {
assertTrue(checkTestIncrementBytes(10, 1));
assertTrue(checkTestIncrementBytes(12, 123435445));
assertTrue(checkTestIncrementBytes(124634654, 1));
@ -414,10 +413,9 @@ public class TestBytes extends TestCase {
assertTrue(checkTestIncrementBytes(-1546543452, -34565445));
}
private static boolean checkTestIncrementBytes(long val, long amount)
throws IOException {
private static boolean checkTestIncrementBytes(long val, long amount) {
byte[] value = Bytes.toBytes(val);
byte [] testValue = {-1, -1, -1, -1, -1, -1, -1, -1};
byte[] testValue = { -1, -1, -1, -1, -1, -1, -1, -1 };
if (value[0] > 0) {
testValue = new byte[Bytes.SIZEOF_LONG];
}
@ -454,14 +452,14 @@ public class TestBytes extends TestCase {
assertEquals("", Bytes.readStringFixedSize(dis, 9));
}
public void testCopy() throws Exception {
byte [] bytes = Bytes.toBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
byte [] copy = Bytes.copy(bytes);
assertFalse(bytes == copy);
public void testCopy() {
byte[] bytes = Bytes.toBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
byte[] copy = Bytes.copy(bytes);
assertNotSame(bytes, copy);
assertTrue(Bytes.equals(bytes, copy));
}
public void testToBytesBinaryTrailingBackslashes() throws Exception {
public void testToBytesBinaryTrailingBackslashes() {
try {
Bytes.toBytesBinary("abc\\x00\\x01\\");
} catch (StringIndexOutOfBoundsException ex) {
@ -469,13 +467,13 @@ public class TestBytes extends TestCase {
}
}
public void testToStringBinary_toBytesBinary_Reversable() throws Exception {
public void testToStringBinary_toBytesBinary_Reversable() {
String bytes = Bytes.toStringBinary(Bytes.toBytes(2.17));
assertEquals(2.17, Bytes.toDouble(Bytes.toBytesBinary(bytes)), 0);
assertEquals(2.17, Bytes.toDouble(Bytes.toBytesBinary(bytes)), 0);
}
public void testUnsignedBinarySearch(){
byte[] bytes = new byte[]{0,5,123,127,-128,-100,-1};
byte[] bytes = new byte[] { 0,5,123,127,-128,-100,-1 };
Assert.assertEquals(1, Bytes.unsignedBinarySearch(bytes, 0, bytes.length, (byte)5));
Assert.assertEquals(3, Bytes.unsignedBinarySearch(bytes, 0, bytes.length, (byte)127));
Assert.assertEquals(4, Bytes.unsignedBinarySearch(bytes, 0, bytes.length, (byte)-128));
@ -488,19 +486,19 @@ public class TestBytes extends TestCase {
public void testUnsignedIncrement(){
byte[] a = Bytes.toBytes(0);
int a2 = Bytes.toInt(Bytes.unsignedCopyAndIncrement(a), 0);
Assert.assertTrue(a2==1);
Assert.assertEquals(1, a2);
byte[] b = Bytes.toBytes(-1);
byte[] actual = Bytes.unsignedCopyAndIncrement(b);
Assert.assertNotSame(b, actual);
byte[] expected = new byte[]{1,0,0,0,0};
Assert.assertArrayEquals(expected, actual);
assertArrayEquals(expected, actual);
byte[] c = Bytes.toBytes(255);//should wrap to the next significant byte
int c2 = Bytes.toInt(Bytes.unsignedCopyAndIncrement(c), 0);
Assert.assertTrue(c2==256);
Assert.assertEquals(256, c2);
}
public void testIndexOf() {
byte[] array = Bytes.toBytes("hello");
assertEquals(1, Bytes.indexOf(array, (byte) 'e'));
@ -510,22 +508,22 @@ public class TestBytes extends TestCase {
assertEquals(2, Bytes.indexOf(array, Bytes.toBytes("ll")));
assertEquals(-1, Bytes.indexOf(array, Bytes.toBytes("hll")));
}
public void testContains() {
byte[] array = Bytes.toBytes("hello world");
assertTrue(Bytes.contains(array, (byte) 'e'));
assertTrue(Bytes.contains(array, (byte) 'd'));
assertFalse( Bytes.contains(array, (byte) 'a'));
assertFalse(Bytes.contains(array, (byte) 'a'));
assertTrue(Bytes.contains(array, Bytes.toBytes("world")));
assertTrue(Bytes.contains(array, Bytes.toBytes("ello")));
assertFalse(Bytes.contains(array, Bytes.toBytes("owo")));
}
public void testZero() {
byte[] array = Bytes.toBytes("hello");
Bytes.zero(array);
for (int i = 0; i < array.length; i++) {
assertEquals(0, array[i]);
for (byte b : array) {
assertEquals(0, b);
}
array = Bytes.toBytes("hello world");
Bytes.zero(array, 2, 7);
@ -542,57 +540,38 @@ public class TestBytes extends TestCase {
public void testPutBuffer() {
byte[] b = new byte[100];
for (byte i = 0; i < 100; i++) {
Bytes.putByteBuffer(b, i, ByteBuffer.wrap(new byte[]{i}));
Bytes.putByteBuffer(b, i, ByteBuffer.wrap(new byte[] { i }));
}
for (byte i = 0; i < 100; i++) {
Assert.assertEquals(i, b[i]);
}
}
public void testToFromHex() {
List<String> testStrings = new ArrayList<String>();
testStrings.addAll(Arrays.asList(new String[] {
"",
"00",
"A0",
"ff",
"FFffFFFFFFFFFF",
"12",
"0123456789abcdef",
"283462839463924623984692834692346ABCDFEDDCA0",
}));
for (String testString : testStrings)
{
List<String> testStrings = new ArrayList<>();
testStrings.addAll(Arrays.asList("", "00", "A0", "ff", "FFffFFFFFFFFFF", "12",
"0123456789abcdef", "283462839463924623984692834692346ABCDFEDDCA0"));
for (String testString : testStrings) {
byte[] byteData = Bytes.fromHex(testString);
Assert.assertEquals(testString.length() / 2, byteData.length);
String result = Bytes.toHex(byteData);
Assert.assertTrue(testString.equalsIgnoreCase(result));
}
List<byte[]> testByteData = new ArrayList<byte[]>();
testByteData.addAll(Arrays.asList(new byte[][] {
new byte[0],
new byte[1],
new byte[10],
new byte[] {1, 2, 3, 4, 5},
new byte[] {(byte) 0xFF},
}));
List<byte[]> testByteData = new ArrayList<>(Arrays.asList(new byte[0], new byte[1],
new byte[10], new byte[] { 1, 2, 3, 4, 5 }, new byte[] { (byte) 0xFF }));
Random r = new Random();
for (int i = 0; i < 20; i++)
{
for (int i = 0; i < 20; i++) {
byte[] bytes = new byte[r.nextInt(100)];
r.nextBytes(bytes);
testByteData.add(bytes);
}
for (byte[] testData : testByteData)
{
for (byte[] testData : testByteData) {
String hexString = Bytes.toHex(testData);
Assert.assertEquals(testData.length * 2, hexString.length());
byte[] result = Bytes.fromHex(hexString);
Assert.assertArrayEquals(testData, result);
assertArrayEquals(testData, result);
}
}
}

View File

@ -1,5 +1,4 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@ -18,10 +17,10 @@
*/
package org.apache.hadoop.hbase.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import java.io.File;
@ -41,7 +40,6 @@ import org.junit.experimental.categories.Category;
*/
@Category(SmallTests.class)
public class TestCoprocessorClassLoader {
private static final HBaseCommonTestingUtility TEST_UTIL = new HBaseCommonTestingUtility();
private static final Configuration conf = TEST_UTIL.getConfiguration();
static {
@ -55,7 +53,11 @@ public class TestCoprocessorClassLoader {
File jarFile = ClassLoaderTestHelper.buildJar(
folder, className, null, ClassLoaderTestHelper.localDirPath(conf));
File tmpJarFile = new File(jarFile.getParent(), "/tmp/" + className + ".test.jar");
if (tmpJarFile.exists()) tmpJarFile.delete();
if (tmpJarFile.exists()) {
tmpJarFile.delete();
}
assertFalse("tmp jar file should not exist", tmpJarFile.exists());
IOUtils.copyBytes(new FileInputStream(jarFile),
new FileOutputStream(tmpJarFile), conf, true);
@ -127,12 +129,10 @@ public class TestCoprocessorClassLoader {
ClassLoader parent = TestCoprocessorClassLoader.class.getClassLoader();
CoprocessorClassLoader.parentDirLockSet.clear(); // So that clean up can be triggered
CoprocessorClassLoader coprocessorClassLoader = null;
Path testPath = null;
// Directory
testPath = new Path(localDirContainingJar);
coprocessorClassLoader = CoprocessorClassLoader.getClassLoader(testPath, parent, "113_1", conf);
Path testPath = new Path(localDirContainingJar);
CoprocessorClassLoader coprocessorClassLoader = CoprocessorClassLoader.getClassLoader(testPath,
parent, "113_1", conf);
verifyCoprocessorClassLoader(coprocessorClassLoader, testClassName);
// Wildcard - *.jar
@ -150,10 +150,11 @@ public class TestCoprocessorClassLoader {
* Verify the coprocessorClassLoader is not null and the expected class can be loaded successfully
* @param coprocessorClassLoader the CoprocessorClassLoader to verify
* @param className the expected class to be loaded by the coprocessorClassLoader
* @throws ClassNotFoundException
* @throws ClassNotFoundException if the class, which should be loaded via the
* coprocessorClassLoader, does not exist
*/
private void verifyCoprocessorClassLoader(CoprocessorClassLoader coprocessorClassLoader, String className)
throws ClassNotFoundException{
private void verifyCoprocessorClassLoader(CoprocessorClassLoader coprocessorClassLoader,
String className) throws ClassNotFoundException {
assertNotNull("Classloader should be created and not null", coprocessorClassLoader);
assertEquals(className, coprocessorClassLoader.loadClass(className).getName());
}

View File

@ -109,12 +109,13 @@ public class TestOrderedBytes {
*/
@Test
public void testVaruint64Boundaries() {
long vals[] =
{ 239L, 240L, 2286L, 2287L, 67822L, 67823L, 16777214L, 16777215L, 4294967294L, 4294967295L,
1099511627774L, 1099511627775L, 281474976710654L, 281474976710655L, 72057594037927934L,
72057594037927935L, Long.MAX_VALUE - 1, Long.MAX_VALUE, Long.MIN_VALUE + 1,
Long.MIN_VALUE, -2L, -1L };
int lens[] = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9 };
long[] vals = {
239L, 240L, 2286L, 2287L, 67822L, 67823L, 16777214L, 16777215L, 4294967294L, 4294967295L,
1099511627774L, 1099511627775L, 281474976710654L, 281474976710655L, 72057594037927934L,
72057594037927935L, Long.MAX_VALUE - 1, Long.MAX_VALUE, Long.MIN_VALUE + 1,
Long.MIN_VALUE, -2L, -1L
};
int[] lens = { 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9 };
assertEquals("Broken test!", vals.length, lens.length);
/*
@ -201,8 +202,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Long[] sortedVals = Arrays.copyOf(I_VALS, I_VALS.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
pbr.set(encoded[i]);
@ -249,8 +254,8 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
D_VALS[i].doubleValue(), OrderedBytes.decodeNumericAsDouble(buf1), MIN_EPSILON);
assertEquals("Deserialization failed.", D_VALS[i],
OrderedBytes.decodeNumericAsDouble(buf1), MIN_EPSILON);
assertEquals("Did not consume enough bytes.", D_LENGTHS[i], buf1.getPosition() - 1);
}
}
@ -268,8 +273,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Double[] sortedVals = Arrays.copyOf(D_VALS, D_VALS.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
pbr.set(encoded[i]);
@ -277,8 +286,7 @@ public class TestOrderedBytes {
assertEquals(
String.format(
"Encoded representations do not preserve natural order: <%s>, <%s>, %s",
sortedVals[i], decoded, ord),
sortedVals[i].doubleValue(), decoded, MIN_EPSILON);
sortedVals[i], decoded, ord), sortedVals[i], decoded, MIN_EPSILON);
}
}
}
@ -371,17 +379,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Byte val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[2 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 2 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
2, OrderedBytes.encodeInt8(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 2, OrderedBytes.encodeInt8(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 2, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -394,8 +401,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
vals[i].byteValue(), OrderedBytes.decodeInt8(buf1));
assertEquals("Deserialization failed.", val.byteValue(), OrderedBytes.decodeInt8(buf1));
assertEquals("Did not consume enough bytes.", 2, buf1.getPosition() - 1);
}
}
@ -412,8 +418,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Byte[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
int decoded = OrderedBytes.decodeInt8(pbr.set(encoded[i]));
@ -439,17 +449,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Short val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[3 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 3 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
3, OrderedBytes.encodeInt16(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 3, OrderedBytes.encodeInt16(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 3, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -462,8 +471,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
vals[i].shortValue(), OrderedBytes.decodeInt16(buf1));
assertEquals("Deserialization failed.", val.shortValue(), OrderedBytes.decodeInt16(buf1));
assertEquals("Did not consume enough bytes.", 3, buf1.getPosition() - 1);
}
}
@ -480,8 +488,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Short[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
int decoded = OrderedBytes.decodeInt16(pbr.set(encoded[i]));
@ -507,17 +519,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Integer val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[5 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 5 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
5, OrderedBytes.encodeInt32(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 5, OrderedBytes.encodeInt32(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 5, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -530,8 +541,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
vals[i].intValue(), OrderedBytes.decodeInt32(buf1));
assertEquals("Deserialization failed.", val.intValue(), OrderedBytes.decodeInt32(buf1));
assertEquals("Did not consume enough bytes.", 5, buf1.getPosition() - 1);
}
}
@ -548,8 +558,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Integer[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
int decoded = OrderedBytes.decodeInt32(pbr.set(encoded[i]));
@ -574,17 +588,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Long val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[9 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 9 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
9, OrderedBytes.encodeInt64(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 9, OrderedBytes.encodeInt64(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 9, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -597,8 +610,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
vals[i].longValue(), OrderedBytes.decodeInt64(buf1));
assertEquals("Deserialization failed.", val.longValue(), OrderedBytes.decodeInt64(buf1));
assertEquals("Did not consume enough bytes.", 9, buf1.getPosition() - 1);
}
}
@ -615,8 +627,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Long[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
long decoded = OrderedBytes.decodeInt64(pbr.set(encoded[i]));
@ -642,17 +658,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Float val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[5 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 5 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
5, OrderedBytes.encodeFloat32(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 5, OrderedBytes.encodeFloat32(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 5, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -665,8 +680,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
Float.floatToIntBits(vals[i].floatValue()),
assertEquals("Deserialization failed.", Float.floatToIntBits(val),
Float.floatToIntBits(OrderedBytes.decodeFloat32(buf1)));
assertEquals("Did not consume enough bytes.", 5, buf1.getPosition() - 1);
}
@ -684,8 +698,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Float[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
float decoded = OrderedBytes.decodeFloat32(pbr.set(encoded[i]));
@ -693,7 +711,7 @@ public class TestOrderedBytes {
String.format(
"Encoded representations do not preserve natural order: <%s>, <%s>, %s",
sortedVals[i], decoded, ord),
Float.floatToIntBits(sortedVals[i].floatValue()),
Float.floatToIntBits(sortedVals[i]),
Float.floatToIntBits(decoded));
}
}
@ -712,17 +730,16 @@ public class TestOrderedBytes {
* starting at an offset to detect over/underflow conditions.
*/
for (Order ord : new Order[] { Order.ASCENDING, Order.DESCENDING }) {
for (int i = 0; i < vals.length; i++) {
for (Double val : vals) {
// allocate a buffer 3-bytes larger than necessary to detect over/underflow
byte[] a = new byte[9 + 3];
PositionedByteRange buf1 = new SimplePositionedMutableByteRange(a, 1, 9 + 1);
buf1.setPosition(1);
// verify encode
assertEquals("Surprising return value.",
9, OrderedBytes.encodeFloat64(buf1, vals[i], ord));
assertEquals("Broken test: serialization did not consume entire buffer.",
buf1.getLength(), buf1.getPosition());
assertEquals("Surprising return value.", 9, OrderedBytes.encodeFloat64(buf1, val, ord));
assertEquals("Broken test: serialization did not consume entire buffer.", buf1.getLength(),
buf1.getPosition());
assertEquals("Surprising serialized length.", 9, buf1.getPosition() - 1);
assertEquals("Buffer underflow.", 0, a[0]);
assertEquals("Buffer underflow.", 0, a[1]);
@ -735,8 +752,7 @@ public class TestOrderedBytes {
// verify decode
buf1.setPosition(1);
assertEquals("Deserialization failed.",
Double.doubleToLongBits(vals[i].doubleValue()),
assertEquals("Deserialization failed.", Double.doubleToLongBits(val),
Double.doubleToLongBits(OrderedBytes.decodeFloat64(buf1)));
assertEquals("Did not consume enough bytes.", 9, buf1.getPosition() - 1);
}
@ -754,8 +770,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
Double[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
double decoded = OrderedBytes.decodeFloat64(pbr.set(encoded[i]));
@ -763,7 +783,7 @@ public class TestOrderedBytes {
String.format(
"Encoded representations do not preserve natural order: <%s>, <%s>, %s",
sortedVals[i], decoded, ord),
Double.doubleToLongBits(sortedVals[i].doubleValue()),
Double.doubleToLongBits(sortedVals[i]),
Double.doubleToLongBits(decoded));
}
}
@ -775,7 +795,7 @@ public class TestOrderedBytes {
@Test
public void testString() {
String[] vals = { "foo", "baaaar", "bazz" };
int expectedLengths[] = { 5, 8, 6 };
int[] expectedLengths = { 5, 8, 6 };
/*
* assert encoded values match decoded values. encode into target buffer
@ -824,8 +844,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
String[] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals);
else Arrays.sort(sortedVals, Collections.reverseOrder());
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder());
}
for (int i = 0; i < sortedVals.length; i++) {
pbr.set(encoded[i]);
@ -945,8 +969,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
byte[][] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals, Bytes.BYTES_COMPARATOR);
else Arrays.sort(sortedVals, Collections.reverseOrder(Bytes.BYTES_COMPARATOR));
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals, Bytes.BYTES_COMPARATOR);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder(Bytes.BYTES_COMPARATOR));
}
for (int i = 0; i < sortedVals.length; i++) {
pbr.set(encoded[i]);
@ -1022,8 +1050,12 @@ public class TestOrderedBytes {
Arrays.sort(encoded, Bytes.BYTES_COMPARATOR);
byte[][] sortedVals = Arrays.copyOf(vals, vals.length);
if (ord == Order.ASCENDING) Arrays.sort(sortedVals, Bytes.BYTES_COMPARATOR);
else Arrays.sort(sortedVals, Collections.reverseOrder(Bytes.BYTES_COMPARATOR));
if (ord == Order.ASCENDING) {
Arrays.sort(sortedVals, Bytes.BYTES_COMPARATOR);
} else {
Arrays.sort(sortedVals, Collections.reverseOrder(Bytes.BYTES_COMPARATOR));
}
for (int i = 0; i < sortedVals.length; i++) {
pbr.set(encoded[i]);
@ -1075,7 +1107,7 @@ public class TestOrderedBytes {
BigDecimal negLarge = longMax.multiply(longMax).negate();
BigDecimal negMed = new BigDecimal("-10.0");
BigDecimal negSmall = new BigDecimal("-0.0010");
long zero = 0l;
long zero = 0L;
BigDecimal posSmall = negSmall.negate();
BigDecimal posMed = negMed.negate();
BigDecimal posLarge = negLarge.negate();
@ -1084,7 +1116,7 @@ public class TestOrderedBytes {
byte int8 = 100;
short int16 = 100;
int int32 = 100;
long int64 = 100l;
long int64 = 100L;
float float32 = 100.0f;
double float64 = 100.0d;
String text = "hello world.";
@ -1206,7 +1238,7 @@ public class TestOrderedBytes {
BigDecimal negLarge = longMax.multiply(longMax).negate();
BigDecimal negMed = new BigDecimal("-10.0");
BigDecimal negSmall = new BigDecimal("-0.0010");
long zero = 0l;
long zero = 0L;
BigDecimal posSmall = negSmall.negate();
BigDecimal posMed = negMed.negate();
BigDecimal posLarge = negLarge.negate();
@ -1215,7 +1247,7 @@ public class TestOrderedBytes {
byte int8 = 100;
short int16 = 100;
int int32 = 100;
long int64 = 100l;
long int64 = 100L;
float float32 = 100.0f;
double float64 = 100.0d;
String text = "hello world.";

View File

@ -31,9 +31,7 @@ public class TestSimplePositionedMutableByteRange {
PositionedByteRange r = new SimplePositionedMutableByteRange(new byte[5], 1, 3);
// exercise single-byte put
r.put(Bytes.toBytes("f")[0])
.put(Bytes.toBytes("o")[0])
.put(Bytes.toBytes("o")[0]);
r.put(Bytes.toBytes("f")[0]).put(Bytes.toBytes("o")[0]).put(Bytes.toBytes("o")[0]);
Assert.assertEquals(3, r.getPosition());
Assert.assertArrayEquals(
new byte[] { 0, Bytes.toBytes("f")[0], Bytes.toBytes("o")[0], Bytes.toBytes("o")[0], 0 },
@ -41,9 +39,7 @@ public class TestSimplePositionedMutableByteRange {
// exercise multi-byte put
r.setPosition(0);
r.put(Bytes.toBytes("f"))
.put(Bytes.toBytes("o"))
.put(Bytes.toBytes("o"));
r.put(Bytes.toBytes("f")).put(Bytes.toBytes("o")).put(Bytes.toBytes("o"));
Assert.assertEquals(3, r.getPosition());
Assert.assertArrayEquals(
new byte[] { 0, Bytes.toBytes("f")[0], Bytes.toBytes("o")[0], Bytes.toBytes("o")[0], 0 },
@ -69,7 +65,7 @@ public class TestSimplePositionedMutableByteRange {
}
@Test
public void testPutAndGetPrimitiveTypes() throws Exception {
public void testPutAndGetPrimitiveTypes() {
PositionedByteRange pbr = new SimplePositionedMutableByteRange(100);
int i1 = 18, i2 = 2;
short s1 = 0;
@ -95,7 +91,7 @@ public class TestSimplePositionedMutableByteRange {
}
@Test
public void testPutGetAPIsCompareWithBBAPIs() throws Exception {
public void testPutGetAPIsCompareWithBBAPIs() {
// confirm that the long/int/short writing is same as BBs
PositionedByteRange pbr = new SimplePositionedMutableByteRange(100);
int i1 = -234, i2 = 2;

View File

@ -1,5 +1,4 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
@ -16,7 +15,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase.util;
import org.apache.hadoop.hbase.classification.InterfaceAudience;
@ -25,17 +23,9 @@ import org.apache.hadoop.hbase.classification.InterfaceAudience;
public class TimeOffsetEnvironmentEdge implements EnvironmentEdge {
private long offset;
public TimeOffsetEnvironmentEdge(){}
public void setTimeOffset(long off){
this.offset = off;
public TimeOffsetEnvironmentEdge() {
}
public long getTimeOffset()
{
return offset;
}
public void increment(long incr)
{
this.offset += incr;
@ -45,5 +35,4 @@ public class TimeOffsetEnvironmentEdge implements EnvironmentEdge {
public long currentTime() {
return System.currentTimeMillis() + offset;
}
}