src_fm_fc_ms_ff
stringlengths 43
86.8k
| target
stringlengths 20
276k
|
---|---|
GitRepositoryParser { @Nullable public Repository parseRepositoryUrl(@NotNull String uri) { return parseRepositoryUrl(uri, null); } GitRepositoryParser(); GitRepositoryParser(final boolean lowerCaseOwnerAndRepo); @Deprecated @Nullable static Repository parseRepository(@NotNull String uri); @Deprecated @Nullable static Repository parseRepository(@NotNull String uri, @Nullable String pathPrefix); @Nullable Repository parseRepositoryUrl(@NotNull String uri); @Nullable Repository parseRepositoryUrl(@NotNull String uri, @Nullable String pathPrefix); } | @TestFor(issues = "TW-47493") public void parse_git_like_urls() { final String url = "git: Repository repo = myGitRepositoryParser.parseRepositoryUrl(url); then(repo.owner()).isEqualTo("owner"); then(repo.repositoryName()).isEqualTo("repository"); then(repo.url()).isEqualTo(url); }
@TestFor(issues = "TW-43075") public void parse_scp_like_urls_ghe() { final String url = "[email protected]:owner/repository.git"; Repository repo = myGitRepositoryParser.parseRepositoryUrl(url); then(repo.owner()).isEqualTo("owner"); then(repo.repositoryName()).isEqualTo("repository"); then(repo.url()).isEqualTo(url); } |
BasicValidator implements Validator { public Result validate(final ExecutableElement element) { for (final Rule rule : rules) { final Result result = rule.checkElement(element); if (!result.isSuccessful()) { return result; } } return Result.createSuccessful(); } @Inject BasicValidator(); Result validate(final ExecutableElement element); } | @Test public void testValidateElement_usingDataFileElements() { for (final Element element : elements) { if (element.getKind() != ElementKind.METHOD) { throw new RuntimeException("All test elements must be executable elements (e.g. methods)."); } final Target targetAnnotation = element.getAnnotation(Target.class); final boolean shouldPassValidation = targetAnnotation.isValid(); final Result validationResult = validator.validate((ExecutableElement) element); assertThat(validationResult.isSuccessful(), is(shouldPassValidation)); } } |
AnyValueIsAvailableMethodGenerator { public MethodSpec generateFor(final AnnotationMirror unconditionalHandlerAnnotation) { checkNotNull(unconditionalHandlerAnnotation, "Argument \'unconditionalHandlerAnnotation\' cannot be null."); final String annotationClassName = unconditionalHandlerAnnotation.getAnnotationType().toString(); if (!methodBodySuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'unconditionalHandlerAnnotation\' is not an unconditional handler."); } return MethodSpec .methodBuilder("valueIsAvailable") .returns(Boolean.class) .addCode(methodBodySuppliers.get(annotationClassName).apply(unconditionalHandlerAnnotation)) .build(); } @Inject AnyValueIsAvailableMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror unconditionalHandlerAnnotation); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullSupplied() { generator.generateFor(null); }
@Test public void testGenerateFor_booleanHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, BooleanHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_colorHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, ColorHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_colorStateListHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color state list"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, ColorStateListHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_dimensionHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("dimension"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DimensionHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_drawableHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("drawable"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DrawableHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_enumConstantHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("enum constant"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, EnumConstantHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_EnumOrdinalHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("enum ordinal"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, EnumOrdinalHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_floatHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, FloatHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_fractionHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("fraction"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, FractionHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_integerHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("integer"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, IntegerHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_stringHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, StringHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); } |
PlaceholderRetriever { public static AnnotationMirror getAnnotation(final VariableElement element) { checkNotNull(element, "Argument \'element\' cannot be null."); for (final Class<? extends Annotation> annotationClass : AnnotationRegistry.PLACEHOLDERS) { final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, annotationClass); if (mirror != null) { return mirror; } } return null; } private PlaceholderRetriever(); static AnnotationMirror getAnnotation(final VariableElement element); static boolean hasAnnotation(final VariableElement element); } | @Test public void testGetAnnotation_useIntAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("int"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseInt.class.getName())); }
@Test public void testGetAnnotation_useLongAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("long"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseLong.class.getName())); }
@Test public void testGetAnnotation_useNullAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("null"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseNull.class.getName())); }
@Test public void testGetAnnotation_useShortAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("short"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseShort.class.getName())); }
@Test public void testGetAnnotation_useStringAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseString.class.getName())); }
@Test public void testGetAnnotation_noUseAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("no placeholder"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(nullValue())); }
@Test(expected = IllegalArgumentException.class) public void testGetAnnotation_nullSupplied() { PlaceholderRetriever.getAnnotation(null); }
@Test public void testGetAnnotation_useBooleanAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseBoolean.class.getName())); }
@Test public void testGetAnnotation_useByteAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("byte"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseByte.class.getName())); }
@Test public void testGetAnnotation_useCharAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("char"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseChar.class.getName())); }
@Test public void testGetAnnotation_useDoubleAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("double"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseDouble.class.getName())); }
@Test public void testGetAnnotation_useFloatAnnotationPresent() { final VariableElement element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = PlaceholderRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(UseFloat.class.getName())); } |
CallerGenerator { public TypeSpec generateFor( final ExecutableElement method, final CodeBlock targetParameter, final CodeBlock contextParameter, final CodeBlock attrsParameter) { checkNotNull(method, "Argument \'method\' cannot be null."); checkNotNull(targetParameter, "Argument \'targetParameter\' cannot be null."); checkNotNull(contextParameter, "Argument \'contextParameter\' cannot be null."); checkNotNull(attrsParameter, "Argument \'attrsParameter\' cannot be null."); if (ConditionalHandlerRetriever.hasAnnotation(method)) { return generateForConditionalHandler(method, targetParameter, contextParameter, attrsParameter); } else if (UnconditionalHandlerRetriever.hasAnnotation(method)) { if (DefaultRetriever.hasAnnotation(method)) { return generateForUnconditionalHandlerWithDefault(method, targetParameter, contextParameter, attrsParameter); } else { return generateForUnconditionalHandlerWithoutDefault( method, targetParameter, contextParameter, attrsParameter); } } else { throw new IllegalArgumentException("Argument \'method\' does not have a handler annotation."); } } @Inject CallerGenerator(
final Elements elementUtil,
final Types typeUtil,
final TypeMirrorHelper typeMirrorHelper,
final GetDefaultMethodGenerator getDefaultMethodGenerator,
final GetValueMethodGenerator getValueMethodGenerator,
final GetPlaceholderMethodGenerator getPlaceholderMethodGenerator,
final AnyValueIsAvailableMethodGenerator anyValueIsAvailableMethodGenerator,
final SpecificValueIsAvailableMethodGenerator specificValueIsAvailableGenerator,
final CastWrapperGenerator castWrapperGenerator); TypeSpec generateFor(
final ExecutableElement method,
final CodeBlock targetParameter,
final CodeBlock contextParameter,
final CodeBlock attrsParameter); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullMethodSupplied() { callerGenerator.generateFor(null, CodeBlock.of(""), CodeBlock.of(""), CodeBlock.of("")); }
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullContextParameterSupplied() { callerGenerator.generateFor(mock(ExecutableElement.class), null, CodeBlock.of(""), CodeBlock.of("")); }
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullTargetParameterSupplied() { callerGenerator.generateFor(mock(ExecutableElement.class), CodeBlock.of(""), null, CodeBlock.of("")); }
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullAttrsParameterSupplied() { callerGenerator.generateFor(mock(ExecutableElement.class), CodeBlock.of(""), CodeBlock.of(""), null); }
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_elementWithNoHandlerAnnotation() { final ExecutableElement element = avatarRule.getElementWithUniqueId("no handler"); callerGenerator.generateFor( element, CodeBlock.of("target"), CodeBlock.of("context"), CodeBlock.of("attrs")); }
@Test public void testGenerateFor_elementWithConditionalHandler() { final ExecutableElement element = avatarRule.getElementWithUniqueId("conditional handler"); final TypeSpec result = callerGenerator.generateFor( element, CodeBlock.of("target"), CodeBlock.of("context"), CodeBlock.of("attrs")); assertThat(result, is(notNullValue())); checkCompiles(result); }
@Test public void testGenerateFor_elementWithUnconditionalHandlerButNoDefault() { final ExecutableElement element = avatarRule.getElementWithUniqueId("unconditional handler no default"); final TypeSpec result = callerGenerator.generateFor( element, CodeBlock.of("target"), CodeBlock.of("context"), CodeBlock.of("attrs")); assertThat(result, is(notNullValue())); checkCompiles(result); }
@Test public void testGenerateFor_elementWithUnconditionalHandlerAndDefault() { final ExecutableElement element = avatarRule.getElementWithUniqueId("unconditional handler with default"); final TypeSpec result = callerGenerator.generateFor( element, CodeBlock.of("target"), CodeBlock.of("context"), CodeBlock.of("attrs")); assertThat(result, is(notNullValue())); checkCompiles(result); } |
GetPlaceholderMethodGenerator { public MethodSpec generateFor(final AnnotationMirror placeholderAnnotation, final int parameterIndex) { checkNotNull(placeholderAnnotation, "Argument \'placeholderAnnotation\' cannot be null."); checkGreaterThanOrEqualTo(parameterIndex, 0, "Argument \'parameterIndex\' must be at least zero."); final String annotationClassName = placeholderAnnotation.getAnnotationType().toString(); if (!methodSpecSuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'placeholderAnnotation\' is not a placeholder annotation."); } return methodSpecSuppliers.get(annotationClassName).apply(placeholderAnnotation, parameterIndex); } @Inject GetPlaceholderMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror placeholderAnnotation, final int parameterIndex); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullParameter() { generator.generateFor(null, 0); }
@Test(expected = IllegalArgumentException.class) public void testGenerateFor_negativeParameterIndex() { final VariableElement parameter = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror placeholder = PlaceholderRetriever.getAnnotation(parameter); generator.generateFor(placeholder, -1); }
@Test public void testGenerateFor_zeroParameterIndex() { final VariableElement parameter = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); generator.generateFor(useAnnotation, 0); }
@Test public void testGenerateFor_positiveParameterIndex() { final VariableElement parameter = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); generator.generateFor(useAnnotation, 1); }
@Test public void testGenerateFor_parameterWithUseBoolean() { final VariableElement parameter = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Boolean.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseByte() { final VariableElement parameter = avatarRule.getElementWithUniqueId("byte"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseChar() { final VariableElement parameter = avatarRule.getElementWithUniqueId("char"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Character.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseDouble() { final VariableElement parameter = avatarRule.getElementWithUniqueId("double"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseFloat() { final VariableElement parameter = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseInt() { final VariableElement parameter = avatarRule.getElementWithUniqueId("int"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseLong() { final VariableElement parameter = avatarRule.getElementWithUniqueId("long"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseNull() { final VariableElement parameter = avatarRule.getElementWithUniqueId("null"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Object.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseShort() { final VariableElement parameter = avatarRule.getElementWithUniqueId("short"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_parameterWithUseString() { final VariableElement parameter = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror useAnnotation = PlaceholderRetriever.getAnnotation(parameter); final MethodSpec generatedMethod = generator.generateFor(useAnnotation, 0); checkSignature(generatedMethod, ClassName.get(String.class)); checkCompiles(generatedMethod); } |
TypeMirrorHelper { public boolean isPrimitive(final TypeMirror typeMirror) { final String typeMirrorString = typeMirror.toString(); return typeMirrorString.equals("byte") || typeMirrorString.equals("char") || typeMirrorString.equals("short") || typeMirrorString.equals("int") || typeMirrorString.equals("long") || typeMirrorString.equals("double") || typeMirrorString.equals("float") || typeMirrorString.equals("boolean"); } @Inject TypeMirrorHelper(final Elements elementHelper, final Types typeHelper); boolean isPrimitive(final TypeMirror typeMirror); boolean isNumber(final TypeMirror typeMirror); boolean isCharacter(final TypeMirror typeMirror); boolean isBoolean(final TypeMirror typeMirror); boolean isRxObservableType(final TypeMirror typeMirror); } | @Test public void testIsPrimitive_typeMirrorForPrimitiveBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveChar() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveInt() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForPrimitiveShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsPrimitive_typeMirrorForBoxedBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedCharacter() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedInteger() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForBoxedShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsPrimitive_typeMirrorForObject() { final TypeMirror typeMirror = elementUtils.getTypeElement(Object.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForObject() { final TypeMirror typeMirror = elementUtils.getTypeElement(Object.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForObject() { final TypeMirror typeMirror = elementUtils.getTypeElement(Object.class.getCanonicalName()).asType(); assertThat(helper.isPrimitive(typeMirror), is(false)); } |
TypeMirrorHelper { public boolean isNumber(final TypeMirror typeMirror) { final TypeMirror numberType = elementUtil.getTypeElement(Number.class.getCanonicalName()).asType(); return typeUtil.isAssignable(typeMirror, numberType) || typeMirror.toString().equals("byte") || typeMirror.toString().equals("short") || typeMirror.toString().equals("int") || typeMirror.toString().equals("long") || typeMirror.toString().equals("double") || typeMirror.toString().equals("float"); } @Inject TypeMirrorHelper(final Elements elementHelper, final Types typeHelper); boolean isPrimitive(final TypeMirror typeMirror); boolean isNumber(final TypeMirror typeMirror); boolean isCharacter(final TypeMirror typeMirror); boolean isBoolean(final TypeMirror typeMirror); boolean isRxObservableType(final TypeMirror typeMirror); } | @Test public void testIsNumber_typeMirrorForPrimitiveBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsNumber_typeMirrorForPrimitiveByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveChar() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsNumber_typeMirrorForPrimitiveDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveInt() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(false)); }
@Test public void testIsNumber_typeMirrorForBoxedByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedCharacter() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(false)); }
@Test public void testIsNumber_typeMirrorForBoxedDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedInteger() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForBoxedShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForObject() { final TypeMirror typeMirror = elementUtils.getTypeElement(Object.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(false)); }
@Test public void testIsNumber_typeMirrorForNumber() { final TypeMirror typeMirror = elementUtils.getTypeElement(Number.class.getCanonicalName()).asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForOtherNumberImplementation() { final TypeMirror typeMirror = elementUtils .getTypeElement(NumberImplementation.class.getCanonicalName()) .asType(); assertThat(helper.isNumber(typeMirror), is(true)); }
@Test public void testIsNumber_typeMirrorForPrimitiveImplementationSubclass() { final TypeMirror typeMirror = elementUtils .getTypeElement(NumberImplementationSubclass.class.getCanonicalName()) .asType(); assertThat(helper.isNumber(typeMirror), is(true)); } |
PlaceholderRetriever { public static boolean hasAnnotation(final VariableElement element) { return getAnnotation(element) != null; } private PlaceholderRetriever(); static AnnotationMirror getAnnotation(final VariableElement element); static boolean hasAnnotation(final VariableElement element); } | @Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { PlaceholderRetriever.hasAnnotation(null); } |
TypeMirrorHelper { public boolean isCharacter(final TypeMirror typeMirror) { final TypeMirror characterType = elementUtil.getTypeElement(Character.class.getCanonicalName()).asType(); return typeUtil.isAssignable(typeMirror, characterType) || typeMirror.toString().equals("char"); } @Inject TypeMirrorHelper(final Elements elementHelper, final Types typeHelper); boolean isPrimitive(final TypeMirror typeMirror); boolean isNumber(final TypeMirror typeMirror); boolean isCharacter(final TypeMirror typeMirror); boolean isBoolean(final TypeMirror typeMirror); boolean isRxObservableType(final TypeMirror typeMirror); } | @Test public void testIsCharacter_typeMirrorForPrimitiveBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveChar() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveInt() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForPrimitiveShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedCharacter() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(true)); }
@Test public void testIsCharacter_typeMirrorForBoxedDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedInteger() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); }
@Test public void testIsCharacter_typeMirrorForBoxedShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isCharacter(typeMirror), is(false)); } |
DefaultRetriever { public static AnnotationMirror getAnnotation(final ExecutableElement element) { checkNotNull(element, "Argument \'element\' cannot be null."); for (final Class<? extends Annotation> annotationClass : AnnotationRegistry.DEFAULTS) { final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, annotationClass); if (mirror != null) { return mirror; } } return null; } private DefaultRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testGetAnnotation_nullSupplied() { DefaultRetriever.getAnnotation(null); }
@Test public void testGetAnnotation_defaultToBooleanAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToBoolean.class.getName())); }
@Test public void testGetAnnotation_defaultToBooleanResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("boolean resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToBooleanResource.class.getName())); }
@Test public void testGetAnnotation_defaultToColorResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("color resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToColorResource.class.getName())); }
@Test public void testGetAnnotation_defaultToColorStateListResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("color state list resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToColorStateListResource.class.getName())); }
@Test public void testGetAnnotation_defaultToDimensionAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("dimension"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToDimension.class.getName())); }
@Test public void testGetAnnotation_defaultToDimensionResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("dimension resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToDimensionResource.class.getName())); }
@Test public void testGetAnnotation_defaultToDrawableResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("drawable resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToDrawableResource.class.getName())); }
@Test public void testGetAnnotation_defaultToEnumConstantAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("enum constant"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToEnumConstant.class.getName())); }
@Test public void testGetAnnotation_defaultToFloatAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToFloat.class.getName())); }
@Test public void testGetAnnotation_defaultToFractionResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("fraction resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToFractionResource.class.getName())); }
@Test public void testGetAnnotation_defaultToIntegerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("integer"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToInteger.class.getName())); }
@Test public void testGetAnnotation_defaultToIntegerResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("integer resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToIntegerResource.class.getName())); }
@Test public void testGetAnnotation_defaultToNullAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("null"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToNull.class.getName())); }
@Test public void testGetAnnotation_defaultToStringAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToString.class.getName())); }
@Test public void testGetAnnotation_defaultToStringResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("string resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToStringResource.class.getName())); }
@Test public void testGetAnnotation_defaultToTextArrayResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("text array resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToTextArrayResource.class.getName())); }
@Test public void testGetAnnotation_defaultToTextResourceAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("text resource"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DefaultToTextResource.class.getName())); }
@Test public void testGetAnnotation_noDefaultAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("no default annotation"); final AnnotationMirror mirror = DefaultRetriever.getAnnotation(element); assertThat(mirror, is(nullValue())); } |
TypeMirrorHelper { public boolean isBoolean(final TypeMirror typeMirror) { final TypeMirror booleanType = elementUtil.getTypeElement(Boolean.class.getCanonicalName()).asType(); return typeUtil.isAssignable(typeMirror, booleanType) || typeMirror.toString().equals("boolean"); } @Inject TypeMirrorHelper(final Elements elementHelper, final Types typeHelper); boolean isPrimitive(final TypeMirror typeMirror); boolean isNumber(final TypeMirror typeMirror); boolean isCharacter(final TypeMirror typeMirror); boolean isBoolean(final TypeMirror typeMirror); boolean isRxObservableType(final TypeMirror typeMirror); } | @Test public void testIsBoolean_typeMirrorForPrimitiveBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(true)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveChar() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveInt() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForPrimitiveShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeUtils.unboxedType(typeMirror)), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedBoolean() { final TypeMirror typeMirror = elementUtils.getTypeElement(Boolean.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(true)); }
@Test public void testIsBoolean_typeMirrorForBoxedByte() { final TypeMirror typeMirror = elementUtils.getTypeElement(Byte.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedCharacter() { final TypeMirror typeMirror = elementUtils.getTypeElement(Character.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedDouble() { final TypeMirror typeMirror = elementUtils.getTypeElement(Double.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedFloat() { final TypeMirror typeMirror = elementUtils.getTypeElement(Float.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedInteger() { final TypeMirror typeMirror = elementUtils.getTypeElement(Integer.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedLong() { final TypeMirror typeMirror = elementUtils.getTypeElement(Long.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); }
@Test public void testIsBoolean_typeMirrorForBoxedShort() { final TypeMirror typeMirror = elementUtils.getTypeElement(Short.class.getCanonicalName()).asType(); assertThat(helper.isBoolean(typeMirror), is(false)); } |
CompanionNamer { public static String getCompanionNameFor(final TypeElement targetClass) { return getParentChain(targetClass) + "_SpyglassCompanion"; } static String getCompanionNameFor(final TypeElement targetClass); } | @Test public void testGetCompanionNameFor_topLevelClass() { final TypeElement element = avatarRule.getElementWithUniqueId("top level"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_SpyglassCompanion"; assertThat(companionName, is(expectedName)); }
@Test public void testGetCompanionNameFor_classNestedByOneLevel() { final TypeElement element = avatarRule.getElementWithUniqueId("nested one level"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_ClassA_SpyglassCompanion"; assertThat(companionName, is(expectedName)); }
@Test public void testGetCompanionNameFor_classNestedByMultipleLevels() { final TypeElement element = avatarRule.getElementWithUniqueId("nested multiple levels"); final String companionName = CompanionNamer.getCompanionNameFor(element); final String expectedName = "TestCompanionNamerData_ClassA_ClassB_ClassC_ClassD_SpyglassCompanion"; assertThat(companionName, is(expectedName)); } |
AnnotationMirrorHelper { public static AnnotationMirror getAnnotationMirror( final Element element, final Class<? extends Annotation> annotationClass) { checkNotNull(element, "Argument \'element\' cannot be null."); checkNotNull(annotationClass, "Argument \'annotationClass\' cannot be null."); for (final AnnotationMirror mirror : element.getAnnotationMirrors()) { if (mirror.getAnnotationType().toString().equals(annotationClass.getName())) { return mirror; } } return null; } @Inject AnnotationMirrorHelper(final Elements elementHelper); static AnnotationMirror getAnnotationMirror(
final Element element,
final Class<? extends Annotation> annotationClass); AnnotationValue getValueIgnoringDefaults(final AnnotationMirror mirror, final String valueKey); AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey); } | @Test(expected = IllegalArgumentException.class) public void testGetAnnotationMirror_nullElement() { AnnotationMirrorHelper.getAnnotationMirror(null, Annotation.class); }
@Test(expected = IllegalArgumentException.class) public void testGetAnnotationMirror_nullAnnotationClass() { AnnotationMirrorHelper.getAnnotationMirror(mock(Element.class), null); }
@Test public void testGetAnnotationMirror_annotationMissing() { final Element element = avatarRule.getElementWithUniqueId("get annotation mirror: without annotation"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SomeAnnotationWithValue.class); assertThat(mirror, is(nullValue())); }
@Test public void testGetAnnotationMirror_annotationPresent() { final Element element = avatarRule.getElementWithUniqueId("get annotation mirror: with annotation"); final AnnotationMirror mirror = AnnotationMirrorHelper .getAnnotationMirror(element, SomeAnnotationWithValue.class); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SomeAnnotationWithValue.class.getName())); } |
AnnotationMirrorHelper { public AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey) { checkNotNull(mirror, "Argument \'mirror\' cannot be null."); checkNotNull(valueKey, "Argument \'valueKey\' cannot be null."); final Map<? extends ExecutableElement, ? extends AnnotationValue> values = elementHelper .getElementValuesWithDefaults(mirror); for (final ExecutableElement mapKey : values.keySet()) { if (mapKey.getSimpleName().toString().equals(valueKey)) { return values.get(mapKey); } } return null; } @Inject AnnotationMirrorHelper(final Elements elementHelper); static AnnotationMirror getAnnotationMirror(
final Element element,
final Class<? extends Annotation> annotationClass); AnnotationValue getValueIgnoringDefaults(final AnnotationMirror mirror, final String valueKey); AnnotationValue getValueUsingDefaults(final AnnotationMirror mirror, final String valueKey); } | @Test(expected = IllegalArgumentException.class) public void testGetValueUsingDefaults_nullAnnotationMirrorSupplied() { helper.getValueUsingDefaults(null, ""); }
@Test(expected = IllegalArgumentException.class) public void testGetValueUsingDefaults_nullValueKeySupplied() { helper.getValueUsingDefaults(mock(AnnotationMirror.class), null); } |
DefaultRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private DefaultRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { DefaultRetriever.hasAnnotation(null); } |
UnconditionalHandlerRetriever { public static AnnotationMirror getAnnotation(final ExecutableElement element) { checkNotNull(element, "Argument \'element\' cannot be null."); for (final Class<? extends Annotation> annotationClass : AnnotationRegistry.UNCONDITIONAL_HANDLERS) { final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, annotationClass); if (mirror != null) { return mirror; } } return null; } private UnconditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testGetAnnotation_nullSupplied() { UnconditionalHandlerRetriever.getAnnotation(null); }
@Test public void testGetAnnotation_booleanHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(BooleanHandler.class.getName())); }
@Test public void testGetAnnotation_colorHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("color"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(ColorHandler.class.getName())); }
@Test public void testGetAnnotation_colorStateListHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("color state list"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(ColorStateListHandler.class.getName())); }
@Test public void testGetAnnotation_dimensionHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("dimension"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DimensionHandler.class.getName())); }
@Test public void testGetAnnotation_drawableHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("drawable"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(DrawableHandler.class.getName())); }
@Test public void testGetAnnotation_enumConstantHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("enum constant"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(EnumConstantHandler.class.getName())); }
@Test public void testGetAnnotation_enumOrdinalHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("enum ordinal"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(EnumOrdinalHandler.class.getName())); }
@Test public void testGetAnnotation_floatHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(FloatHandler.class.getName())); }
@Test public void testGetAnnotation_fractionHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("fraction"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(FractionHandler.class.getName())); }
@Test public void testGetAnnotation_integerHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("integer"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(IntegerHandler.class.getName())); }
@Test public void testGetAnnotation_stringHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(StringHandler.class.getName())); }
@Test public void testGetAnnotation_noUnconditionalHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("no value handler annotation"); final AnnotationMirror mirror = UnconditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(nullValue())); } |
UnconditionalHandlerRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private UnconditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { UnconditionalHandlerRetriever.hasAnnotation(null); } |
ConditionalHandlerRetriever { public static AnnotationMirror getAnnotation(final ExecutableElement element) { checkNotNull(element, "Argument \'element\' cannot be null."); for (final Class<? extends Annotation> annotationClass : AnnotationRegistry.CONDITIONAL_HANDLERS) { final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, annotationClass); if (mirror != null) { return mirror; } } return null; } private ConditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testGetAnnotation_nullSupplied() { ConditionalHandlerRetriever.getAnnotation(null); }
@Test public void testGetAnnotation_specificBooleanHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific boolean"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificBooleanHandler.class.getName())); }
@Test public void testGetAnnotation_specificEnumHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific enum"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificEnumHandler.class.getName())); }
@Test public void testGetAnnotation_specificFlagHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("specific flag"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(notNullValue())); assertThat(mirror.getAnnotationType().toString(), is(SpecificFlagHandler.class.getName())); }
@Test public void testGetAnnotation_noConditionalHandlerAnnotationPresent() { final ExecutableElement element = avatarRule.getElementWithUniqueId("no call handler annotation"); final AnnotationMirror mirror = ConditionalHandlerRetriever.getAnnotation(element); assertThat(mirror, is(nullValue())); } |
ConditionalHandlerRetriever { public static boolean hasAnnotation(final ExecutableElement element) { return getAnnotation(element) != null; } private ConditionalHandlerRetriever(); static AnnotationMirror getAnnotation(final ExecutableElement element); static boolean hasAnnotation(final ExecutableElement element); } | @Test(expected = IllegalArgumentException.class) public void testHasAnnotation_nullSupplied() { ConditionalHandlerRetriever.hasAnnotation(null); } |
TypeElementWrapper { @Override public int hashCode() { return element.getQualifiedName().toString().hashCode(); } TypeElementWrapper(final TypeElement element); TypeElement unwrap(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testHashcode_checkContractIsSatisfied() { final TypeElementWrapper wrapper1A = new TypeElementWrapper(class1); final TypeElementWrapper wrapper1B = new TypeElementWrapper(class1); for (int i = 0; i < 1000; i++) { assertThat(wrapper1A.hashCode(), is(wrapper1B.hashCode())); } } |
TypeElementWrapper { public TypeElement unwrap() { return element; } TypeElementWrapper(final TypeElement element); TypeElement unwrap(); @Override boolean equals(final Object o); @Override int hashCode(); } | @Test public void testUnwrap() { final TypeElementWrapper wrapper = new TypeElementWrapper(class1); assertThat(wrapper.unwrap() == class1, is(true)); } |
Grouper { public static <T extends Element> Map<TypeElementWrapper, Set<T>> groupByEnclosingClass(final Set<T> elements) { checkNotNull(elements, "Argument \'elements\' cannot be null."); checkEachElementIsNotNull(elements, "Argument \'elements\' cannot contain null."); final Map<TypeElementWrapper, Set<T>> groups = new HashMap<>(); for (final T element : elements) { final Element parent = element.getEnclosingElement(); if (parent instanceof TypeElement) { final TypeElementWrapper parentWrapper = new TypeElementWrapper((TypeElement) parent); if (!groups.containsKey(parentWrapper)) { groups.put(parentWrapper, new HashSet<>()); } groups.get(parentWrapper).add(element); } else { throw new IllegalArgumentException( "Argument \'elements\' contains an element which is not the immediate child of a TypeElement."); } } return groups; } private Grouper(); static Map<TypeElementWrapper, Set<T>> groupByEnclosingClass(final Set<T> elements); } | @Test(expected = IllegalArgumentException.class) public void testGroupByEnclosingClass_nullSupplied() { groupByEnclosingClass(null); }
@Test(expected = IllegalArgumentException.class) public void testGroupByEnclosingClass_collectionContainsNull() { final Set<Element> set = new HashSet<>(); set.add(null); groupByEnclosingClass(set); }
@Test public void testGroupByEnclosingClass_primaryClassComponents() { final Map<TypeElementWrapper, Set<Element>> groupedByClass = groupByEnclosingClass(primaryClassChildren); assertThat("There should only be one group.", groupedByClass.size(), is(1)); assertThat( "Wrong children found.", groupedByClass.get(new TypeElementWrapper(primaryClass)), is(primaryClassChildren)); }
@Test public void testGroupByEnclosingClass_secondaryClassComponents() { final Map<TypeElementWrapper, Set<Element>> groupedByClass = groupByEnclosingClass(secondaryClassChildren); assertThat("There should only be one group.", groupedByClass.size(), is(1)); assertThat( "Wrong children found.", groupedByClass.get(new TypeElementWrapper(secondaryClass)), is(secondaryClassChildren)); }
@Test public void testGroupByEnclosingClass_innerClassComponents() { final Map<TypeElementWrapper, Set<Element>> groupedByClass = groupByEnclosingClass(innerClassChildren); assertThat("There should only be one group.", groupedByClass.size(), is(1)); assertThat( "Wrong children found.", groupedByClass.get(new TypeElementWrapper(innerClass)), is(innerClassChildren)); }
@Test public void testGroupByEnclosingClass_veryNestedClassComponents() { final Map<TypeElementWrapper, Set<Element>> groupedByClass = groupByEnclosingClass(veryNestedClassChildren); assertThat("There should only be one group.", groupedByClass.size(), is(1)); assertThat( "Wrong children found.", groupedByClass.get(new TypeElementWrapper(veryNestedClass)), is(veryNestedClassChildren)); }
@Test public void testGroupByEnclosingClass_allComponents() { final Set<Element> allChildren = new HashSet<>(); allChildren.addAll(primaryClassChildren); allChildren.addAll(secondaryClassChildren); allChildren.addAll(innerClassChildren); allChildren.addAll(veryNestedClassChildren); final Map<TypeElementWrapper, Set<Element>> groupedByClass = groupByEnclosingClass(allChildren); assertThat("There should only be four groups.", groupedByClass.size(), is(4)); assertThat("Wrong children found for primary class.", groupedByClass.get(new TypeElementWrapper(primaryClass)), is(primaryClassChildren)); assertThat("Wrong children found for secondary class.", groupedByClass.get(new TypeElementWrapper(secondaryClass)), is(secondaryClassChildren)); assertThat("Wrong children found for inner class.", groupedByClass.get(new TypeElementWrapper(innerClass)), is(innerClassChildren)); assertThat("Wrong children found for very nested class.", groupedByClass.get(new TypeElementWrapper(veryNestedClass)), is(veryNestedClassChildren)); } |
SpecificValueIsAvailableMethodGenerator { public MethodSpec generateFor(final AnnotationMirror conditionalHandlerAnnotation) { checkNotNull(conditionalHandlerAnnotation, "Argument \'conditionalHandlerAnnotation\' cannot be null."); final String annotationClassName = conditionalHandlerAnnotation.getAnnotationType().toString(); if (!methodBodySuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'conditionalHandlerAnnotation\' is not a call handler annotation."); } return MethodSpec .methodBuilder("specificValueIsAvailable") .returns(Boolean.class) .addCode(methodBodySuppliers.get(annotationClassName).apply(conditionalHandlerAnnotation)) .build(); } @Inject SpecificValueIsAvailableMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror conditionalHandlerAnnotation); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullSupplied() { generator.generateFor(null); }
@Test public void testGenerateFor_specificBooleanHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific boolean"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, SpecificBooleanHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_specificEnumHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific enum"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SpecificEnumHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_specificFlagHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("specific flag"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, SpecificFlagHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkMethodSignature(generatedMethod); checkCompiles(generatedMethod); } |
GetValueMethodGenerator { public MethodSpec generateFor(final AnnotationMirror unconditionalHandlerAnnotation) { checkNotNull(unconditionalHandlerAnnotation, "Argument \'unconditionalHandlerAnnotation\' cannot be null."); final String annotationClassName = unconditionalHandlerAnnotation.getAnnotationType().toString(); if (!methodSpecSuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'unconditionalHandlerAnnotation\' cannot contain null."); } return methodSpecSuppliers.get(annotationClassName).apply(unconditionalHandlerAnnotation); } @Inject GetValueMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror unconditionalHandlerAnnotation); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullSupplied() { generator.generateFor(null); }
@Test public void testGenerateFor_booleanHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, BooleanHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, TypeName.BOOLEAN.box()); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_colorHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, ColorHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_colorStateListHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color state list"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, ColorStateListHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(ColorStateList.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_dimensionHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("dimension"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DimensionHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_drawableHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("drawable"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DrawableHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Drawable.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_enumConstantHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("enum constant"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, EnumConstantHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(PlaceholderEnum.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_EnumOrdinalHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("enum ordinal"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, EnumOrdinalHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_floatHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, FloatHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_fractionHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("fraction"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, FractionHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_integerHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("integer"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, IntegerHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_stringHandlerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, StringHandler.class); final MethodSpec generatedMethod = generator.generateFor(mirror); checkSignature(generatedMethod, ClassName.get(String.class)); checkCompiles(generatedMethod); } |
GetDefaultMethodGenerator { public MethodSpec generateFor(final AnnotationMirror defaultAnnotation) { checkNotNull(defaultAnnotation, "Argument \'defaultAnnotation\' cannot be null."); final String annotationClassName = defaultAnnotation.getAnnotationType().toString(); if (!methodSpecSuppliers.containsKey(annotationClassName)) { throw new IllegalArgumentException("Argument \'defaultAnnotation\' is not a default annotation."); } return methodSpecSuppliers.get(annotationClassName).apply(defaultAnnotation); } @Inject GetDefaultMethodGenerator(final AnnotationMirrorHelper annotationMirrorHelper); MethodSpec generateFor(final AnnotationMirror defaultAnnotation); } | @Test(expected = IllegalArgumentException.class) public void testGenerateFor_nullSupplied() { generator.generateFor(null); }
@Test public void testGenerateFor_defaultToBooleanAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("boolean"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToBoolean.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.BOOLEAN.box()); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToBooleanResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("boolean resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToBooleanResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.BOOLEAN.box()); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToColorResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToColorResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToColorStatListResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("color state list resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToColorStateListResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(ColorStateList.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToDimensionAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("dimension"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToDimension.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToDimensionResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("dimension resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToDimensionResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToDrawableResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("drawable resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToDrawableResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Drawable.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToEnumConstantAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("enum constant"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToEnumConstant.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(PlaceholderEnum.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToFloatAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("float"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToFloat.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToFractionResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("fraction resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToFractionResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToIntegerAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("integer"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToInteger.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToIntegerResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("integer resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToIntegerResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(Number.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToNullAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("null"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToNull.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, TypeName.OBJECT); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToStringAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("string"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror(element, DefaultToString.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(String.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToStringResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("string resource"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToStringResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(String.class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToTextArrayResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("text array"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToTextArrayResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, TypeName.get(CharSequence[].class)); checkCompiles(generatedMethod); }
@Test public void testGenerateFor_defaultToTextResourceAnnotationSupplied() { final Element element = avatarRule.getElementWithUniqueId("text"); final AnnotationMirror mirror = AnnotationMirrorHelper.getAnnotationMirror( element, DefaultToTextResource.class); final MethodSpec generatedMethod = generator.generateFor(mirror); assertThat(generatedMethod, is(notNullValue())); checkMethodSignature(generatedMethod, ClassName.get(CharSequence.class)); checkCompiles(generatedMethod); } |
NoopMetricsSystemFactory implements MetricsSystemFactory { @Override public NoopMetricsSystem create(MetricsSystemConfiguration<?> config) { return NoopMetricsSystem.getInstance(); } @Override NoopMetricsSystem create(MetricsSystemConfiguration<?> config); } | @Test public void testSingleton() { NoopMetricsSystemFactory factory = new NoopMetricsSystemFactory(); NoopMetricsSystemConfiguration config = NoopMetricsSystemConfiguration.getInstance(); assertTrue("The factory should only return one NoopMetricsSystem instance", factory.create(config) == factory.create(config)); } |
DateTimeUtils { public static int ymdToUnixDate(int year, int month, int day) { final int julian = ymdToJulian(year, month, day); return julian - EPOCH_JULIAN; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testYmdToUnixDate() { assertEquals(0, ymdToUnixDate(1970, 1, 1)); assertEquals(365, ymdToUnixDate(1971, 1, 1)); assertEquals(-365, ymdToUnixDate(1969, 1, 1)); assertEquals(11015, ymdToUnixDate(2000, 2, 28)); assertEquals(11016, ymdToUnixDate(2000, 2, 29)); assertEquals(11017, ymdToUnixDate(2000, 3, 1)); assertEquals(-9077, ymdToUnixDate(1945, 2, 24)); assertEquals(-25509, ymdToUnixDate(1900, 2, 28)); assertEquals(-25508, ymdToUnixDate(1900, 3, 1)); } |
DateTimeUtils { public static int unixTimestampExtract(TimeUnitRange range, long timestamp) { return unixTimeExtract(range, (int) floorMod(timestamp, MILLIS_PER_DAY)); } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testTimestampExtract() { assertThat(unixTimestampExtract(TimeUnitRange.HOUR, 0L), is(0)); assertThat(unixTimestampExtract(TimeUnitRange.MINUTE, 0L), is(0)); assertThat(unixTimestampExtract(TimeUnitRange.SECOND, 0L), is(0)); assertThat(unixTimestampExtract(TimeUnitRange.HOUR, 86400000L), is(0)); assertThat(unixTimestampExtract(TimeUnitRange.MINUTE, 86400000L), is(0)); assertThat(unixTimestampExtract(TimeUnitRange.SECOND, 86400000L), is(0)); } |
DateTimeUtils { public static int unixTimeExtract(TimeUnitRange range, int time) { assert time >= 0; assert time < MILLIS_PER_DAY; switch (range) { case HOUR: return time / (int) MILLIS_PER_HOUR; case MINUTE: final int minutes = time / (int) MILLIS_PER_MINUTE; return minutes % 60; case SECOND: final int seconds = time / (int) MILLIS_PER_SECOND; return seconds % 60; default: throw new AssertionError(range); } } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testTimeExtract() { assertThat(unixTimeExtract(TimeUnitRange.HOUR, 0), is(0)); assertThat(unixTimeExtract(TimeUnitRange.MINUTE, 0), is(0)); assertThat(unixTimeExtract(TimeUnitRange.SECOND, 0), is(0)); assertThat(unixTimeExtract(TimeUnitRange.HOUR, 3599999), is(0)); assertThat(unixTimeExtract(TimeUnitRange.MINUTE, 3599999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.SECOND, 3599999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.HOUR, 7199999), is(1)); assertThat(unixTimeExtract(TimeUnitRange.MINUTE, 7199999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.SECOND, 7199999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.HOUR, 7139999), is(1)); assertThat(unixTimeExtract(TimeUnitRange.MINUTE, 7139999), is(58)); assertThat(unixTimeExtract(TimeUnitRange.SECOND, 7139999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.HOUR, 86399999), is(23)); assertThat(unixTimeExtract(TimeUnitRange.MINUTE, 86399999), is(59)); assertThat(unixTimeExtract(TimeUnitRange.SECOND, 86399999), is(59)); } |
DateTimeUtils { public static String intervalYearMonthToString(int v, TimeUnitRange range) { final StringBuilder buf = new StringBuilder(); if (v >= 0) { buf.append('+'); } else { buf.append('-'); v = -v; } final int y; final int m; switch (range) { case YEAR: v = roundUp(v, 12); y = v / 12; buf.append(y); break; case YEAR_TO_MONTH: y = v / 12; buf.append(y); buf.append('-'); m = v % 12; number(buf, m, 2); break; case MONTH: m = v; buf.append(m); break; default: throw new AssertionError(range); } return buf.toString(); } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testIntervalYearMonthToString() { TimeUnitRange range = TimeUnitRange.YEAR_TO_MONTH; assertEquals("+0-00", intervalYearMonthToString(0, range)); assertEquals("+1-00", intervalYearMonthToString(12, range)); assertEquals("+1-01", intervalYearMonthToString(13, range)); assertEquals("-1-01", intervalYearMonthToString(-13, range)); } |
DateTimeUtils { public static String intervalDayTimeToString(long v, TimeUnitRange range, int scale) { final StringBuilder buf = new StringBuilder(); if (v >= 0) { buf.append('+'); } else { buf.append('-'); v = -v; } final long ms; final long s; final long m; final long h; final long d; switch (range) { case DAY_TO_SECOND: v = roundUp(v, powerX(10, 3 - scale)); ms = v % 1000; v /= 1000; s = v % 60; v /= 60; m = v % 60; v /= 60; h = v % 24; v /= 24; d = v; buf.append((int) d); buf.append(' '); number(buf, (int) h, 2); buf.append(':'); number(buf, (int) m, 2); buf.append(':'); number(buf, (int) s, 2); fraction(buf, scale, ms); break; case DAY_TO_MINUTE: v = roundUp(v, 1000 * 60); v /= 1000; v /= 60; m = v % 60; v /= 60; h = v % 24; v /= 24; d = v; buf.append((int) d); buf.append(' '); number(buf, (int) h, 2); buf.append(':'); number(buf, (int) m, 2); break; case DAY_TO_HOUR: v = roundUp(v, 1000 * 60 * 60); v /= 1000; v /= 60; v /= 60; h = v % 24; v /= 24; d = v; buf.append((int) d); buf.append(' '); number(buf, (int) h, 2); break; case DAY: v = roundUp(v, 1000 * 60 * 60 * 24); d = v / (1000 * 60 * 60 * 24); buf.append((int) d); break; case HOUR: v = roundUp(v, 1000 * 60 * 60); v /= 1000; v /= 60; v /= 60; h = v; buf.append((int) h); break; case HOUR_TO_MINUTE: v = roundUp(v, 1000 * 60); v /= 1000; v /= 60; m = v % 60; v /= 60; h = v; buf.append((int) h); buf.append(':'); number(buf, (int) m, 2); break; case HOUR_TO_SECOND: v = roundUp(v, powerX(10, 3 - scale)); ms = v % 1000; v /= 1000; s = v % 60; v /= 60; m = v % 60; v /= 60; h = v; buf.append((int) h); buf.append(':'); number(buf, (int) m, 2); buf.append(':'); number(buf, (int) s, 2); fraction(buf, scale, ms); break; case MINUTE_TO_SECOND: v = roundUp(v, powerX(10, 3 - scale)); ms = v % 1000; v /= 1000; s = v % 60; v /= 60; m = v; buf.append((int) m); buf.append(':'); number(buf, (int) s, 2); fraction(buf, scale, ms); break; case MINUTE: v = roundUp(v, 1000 * 60); v /= 1000; v /= 60; m = v; buf.append((int) m); break; case SECOND: v = roundUp(v, powerX(10, 3 - scale)); ms = v % 1000; v /= 1000; s = v; buf.append((int) s); fraction(buf, scale, ms); break; default: throw new AssertionError(range); } return buf.toString(); } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testIntervalDayTimeToString() { assertEquals("+0", intervalYearMonthToString(0, TimeUnitRange.YEAR)); assertEquals("+0-00", intervalYearMonthToString(0, TimeUnitRange.YEAR_TO_MONTH)); assertEquals("+0", intervalYearMonthToString(0, TimeUnitRange.MONTH)); assertEquals("+0", intervalDayTimeToString(0, TimeUnitRange.DAY, 0)); assertEquals("+0 00", intervalDayTimeToString(0, TimeUnitRange.DAY_TO_HOUR, 0)); assertEquals("+0 00:00", intervalDayTimeToString(0, TimeUnitRange.DAY_TO_MINUTE, 0)); assertEquals("+0 00:00:00", intervalDayTimeToString(0, TimeUnitRange.DAY_TO_SECOND, 0)); assertEquals("+0", intervalDayTimeToString(0, TimeUnitRange.HOUR, 0)); assertEquals("+0:00", intervalDayTimeToString(0, TimeUnitRange.HOUR_TO_MINUTE, 0)); assertEquals("+0:00:00", intervalDayTimeToString(0, TimeUnitRange.HOUR_TO_SECOND, 0)); assertEquals("+0", intervalDayTimeToString(0, TimeUnitRange.MINUTE, 0)); assertEquals("+0:00", intervalDayTimeToString(0, TimeUnitRange.MINUTE_TO_SECOND, 0)); assertEquals("+0", intervalDayTimeToString(0, TimeUnitRange.SECOND, 0)); } |
DateTimeUtils { public static int ymdToJulian(int year, int month, int day) { int a = (14 - month) / 12; int y = year + 4800 - a; int m = month + 12 * a - 3; return day + (153 * m + 2) / 5 + 365 * y + y / 4 - y / 100 + y / 400 - 32045; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testYmdToJulian() { assertThat(ymdToJulian(2014, 4, 3), is(2456751)); assertThat(ymdToJulian(2000, 1, 1), is(2451545)); assertThat(ymdToJulian(2000, 2, 28), is(2451603)); assertThat(ymdToJulian(2000, 2, 29), is(2451604)); assertThat(ymdToJulian(2000, 3, 1), is(2451605)); assertThat(ymdToJulian(1970, 1, 1), is(2440588)); assertThat(ymdToJulian(1970, 1, 1), is(EPOCH_JULIAN)); assertThat(ymdToJulian(1901, 1, 1), is(2415386)); assertThat(ymdToJulian(1900, 10, 17), is(2415310)); assertThat(ymdToJulian(1900, 3, 1), is(2415080)); assertThat(ymdToJulian(1900, 2, 28), is(2415079)); assertThat(ymdToJulian(1900, 2, 1), is(2415052)); assertThat(ymdToJulian(1900, 1, 1), is(2415021)); assertThat(ymdToJulian(1777, 7, 4), is(2370281)); assertThat(ymdToJulian(2016, 2, 28), is(2457447)); assertThat(ymdToJulian(2016, 2, 29), is(2457448)); assertThat(ymdToJulian(2016, 3, 1), is(2457449)); } |
DateTimeUtils { public static long addMonths(long timestamp, int m) { final long millis = DateTimeUtils.floorMod(timestamp, DateTimeUtils.MILLIS_PER_DAY); timestamp -= millis; final long x = addMonths((int) (timestamp / DateTimeUtils.MILLIS_PER_DAY), m); return x * DateTimeUtils.MILLIS_PER_DAY + millis; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testAddMonths() { checkAddMonths(2016, 1, 1, 2016, 2, 1, 1); checkAddMonths(2016, 1, 1, 2017, 1, 1, 12); checkAddMonths(2016, 1, 1, 2017, 2, 1, 13); checkAddMonths(2016, 1, 1, 2015, 1, 1, -12); checkAddMonths(2016, 1, 1, 2018, 10, 1, 33); checkAddMonths(2016, 1, 31, 2016, 5, 1, 3); checkAddMonths(2016, 4, 30, 2016, 7, 30, 3); checkAddMonths(2016, 1, 31, 2016, 3, 1, 1); checkAddMonths(2016, 3, 31, 2016, 3, 1, -1); checkAddMonths(2016, 3, 31, 2116, 3, 31, 1200); checkAddMonths(2016, 2, 28, 2116, 2, 28, 1200); } |
DateTimeUtils { public static long unixTimestamp(int year, int month, int day, int hour, int minute, int second) { final int date = ymdToUnixDate(year, month, day); return (long) date * MILLIS_PER_DAY + (long) hour * MILLIS_PER_HOUR + (long) minute * MILLIS_PER_MINUTE + (long) second * MILLIS_PER_SECOND; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testUnixTimestamp() { assertThat(unixTimestamp(1970, 1, 1, 0, 0, 0), is(0L)); final long day = 86400000L; assertThat(unixTimestamp(1970, 1, 2, 0, 0, 0), is(day)); assertThat(unixTimestamp(1970, 1, 1, 23, 59, 59), is(86399000L)); final long y1900 = -2203977600000L; assertThat(unixTimestamp(1900, 2, 28, 0, 0, 0), is(y1900)); assertThat(unixTimestamp(1900, 3, 1, 0, 0, 0), is(y1900 + day)); final long y2k = 951696000000L; assertThat(unixTimestamp(2000, 2, 28, 0, 0, 0), is(y2k)); assertThat(unixTimestamp(2000, 2, 29, 0, 0, 0), is(y2k + day)); assertThat(unixTimestamp(2000, 3, 1, 0, 0, 0), is(y2k + day + day)); final long y2016 = 1456617600000L; assertThat(unixTimestamp(2016, 2, 28, 0, 0, 0), is(y2016)); assertThat(unixTimestamp(2016, 2, 29, 0, 0, 0), is(y2016 + day)); assertThat(unixTimestamp(2016, 3, 1, 0, 0, 0), is(y2016 + day + day)); } |
QueryState { public ResultSet invoke(Connection conn, Statement statement) throws SQLException { switch (type) { case SQL: boolean ret = Objects.requireNonNull(statement).execute(sql); ResultSet results = statement.getResultSet(); assert ret || null == results; return results; case METADATA: DatabaseMetaData metadata = Objects.requireNonNull(conn).getMetaData(); switch (metaDataOperation) { case GET_ATTRIBUTES: verifyOpArgs(4); return metadata.getAttributes((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_BEST_ROW_IDENTIFIER: verifyOpArgs(5); return metadata.getBestRowIdentifier((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (int) operationArgs[3], (boolean) operationArgs[4]); case GET_CATALOGS: verifyOpArgs(0); return metadata.getCatalogs(); case GET_COLUMNS: verifyOpArgs(4); return metadata.getColumns((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_COLUMN_PRIVILEGES: verifyOpArgs(4); return metadata.getColumnPrivileges((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_CROSS_REFERENCE: verifyOpArgs(6); return metadata.getCrossReference((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3], (String) operationArgs[4], (String) operationArgs[5]); case GET_EXPORTED_KEYS: verifyOpArgs(3); return metadata.getExportedKeys((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_FUNCTIONS: verifyOpArgs(3); return metadata.getFunctions((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_FUNCTION_COLUMNS: verifyOpArgs(4); return metadata.getFunctionColumns((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_IMPORTED_KEYS: verifyOpArgs(3); return metadata.getImportedKeys((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_INDEX_INFO: verifyOpArgs(5); return metadata.getIndexInfo((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (boolean) operationArgs[3], (boolean) operationArgs[4]); case GET_PRIMARY_KEYS: verifyOpArgs(3); return metadata.getPrimaryKeys((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_PROCEDURES: verifyOpArgs(3); return metadata.getProcedures((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_PROCEDURE_COLUMNS: verifyOpArgs(4); return metadata.getProcedureColumns((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_PSEUDO_COLUMNS: verifyOpArgs(4); return metadata.getPseudoColumns((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String) operationArgs[3]); case GET_SCHEMAS: verifyOpArgs(0); return metadata.getSchemas(); case GET_SCHEMAS_WITH_ARGS: verifyOpArgs(2); return metadata.getSchemas((String) operationArgs[0], (String) operationArgs[1]); case GET_SUPER_TABLES: verifyOpArgs(3); return metadata.getSuperTables((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_SUPER_TYPES: verifyOpArgs(3); return metadata.getSuperTypes((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_TABLES: verifyOpArgs(4); return metadata.getTables((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (String[]) operationArgs[3]); case GET_TABLE_PRIVILEGES: verifyOpArgs(3); return metadata.getTablePrivileges((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); case GET_TABLE_TYPES: verifyOpArgs(0); return metadata.getTableTypes(); case GET_TYPE_INFO: verifyOpArgs(0); return metadata.getTypeInfo(); case GET_UDTS: verifyOpArgs(4); return metadata.getUDTs((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2], (int[]) operationArgs[3]); case GET_VERSION_COLUMNS: verifyOpArgs(3); return metadata.getVersionColumns((String) operationArgs[0], (String) operationArgs[1], (String) operationArgs[2]); default: throw new IllegalArgumentException("Unhandled Metadata operation: " + metaDataOperation); } default: throw new IllegalArgumentException("Unable to process QueryState of type " + type); } } QueryState(String sql); QueryState(MetaDataOperation op, Object... args); QueryState(StateType type, String sql, MetaDataOperation op, Object... args); QueryState(); StateType getType(); String getSql(); MetaDataOperation getMetaDataOperation(); Object[] getOperationArgs(); ResultSet invoke(Connection conn, Statement statement); Common.QueryState toProto(); static QueryState fromProto(Common.QueryState protoState); @Override int hashCode(); @Override boolean equals(Object o); @JsonProperty("type")
final StateType type; @JsonProperty("sql")
final String sql; @JsonProperty("metaDataOperation")
final MetaDataOperation metaDataOperation; @JsonProperty("operationArgs")
final Object[] operationArgs; } | @Test public void testMetadataGetAttributes() throws Exception { final String catalog = "catalog"; final String schemaPattern = null; final String typeNamePattern = "%"; final String attributeNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_ATTRIBUTES, catalog, schemaPattern, typeNamePattern, attributeNamePattern); state.invoke(conn, statement); Mockito.verify(metadata).getAttributes(catalog, schemaPattern, typeNamePattern, attributeNamePattern); }
@Test public void testMetadataGetBestRowIdentifier() throws Exception { final String catalog = "catalog"; final String schema = null; final String table = "table"; final int scope = 1; final boolean nullable = true; QueryState state = new QueryState(MetaDataOperation.GET_BEST_ROW_IDENTIFIER, new Object[] { catalog, schema, table, scope, nullable }); state.invoke(conn, statement); Mockito.verify(metadata).getBestRowIdentifier(catalog, schema, table, scope, nullable); }
@Test public void testMetadataGetCatalogs() throws Exception { QueryState state = new QueryState(MetaDataOperation.GET_CATALOGS, new Object[0]); state.invoke(conn, statement); Mockito.verify(metadata).getCatalogs(); }
@Test public void testMetadataGetColumnPrivileges() throws Exception { final String catalog = null; final String schema = "schema"; final String table = "table"; final String columnNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_COLUMN_PRIVILEGES, new Object[] { catalog, schema, table, columnNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getColumnPrivileges(catalog, schema, table, columnNamePattern); }
@Test public void testMetadataGetColumns() throws Exception { final String catalog = null; final String schemaPattern = "%"; final String tableNamePattern = "%"; final String columnNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_COLUMNS, new Object[] { catalog, schemaPattern, tableNamePattern, columnNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern); }
@Test public void testMetadataGetCrossReference() throws Exception { final String parentCatalog = null; final String parentSchema = null; final String parentTable = "%"; final String foreignCatalog = null; final String foreignSchema = null; final String foreignTable = "%"; QueryState state = new QueryState(MetaDataOperation.GET_CROSS_REFERENCE, new Object[] { parentCatalog, parentSchema, parentTable, foreignCatalog, foreignSchema, foreignTable }); state.invoke(conn, statement); Mockito.verify(metadata).getCrossReference(parentCatalog, parentSchema, parentTable, foreignCatalog, foreignSchema, foreignTable); }
@Test public void testMetadataGetExportedKeys() throws Exception { final String catalog = ""; final String schema = null; final String table = "mytable"; QueryState state = new QueryState(MetaDataOperation.GET_EXPORTED_KEYS, new Object[] { catalog, schema, table }); state.invoke(conn, statement); Mockito.verify(metadata).getExportedKeys(catalog, schema, table); }
@Test public void testMetadataGetFunctionColumns() throws Exception { final String catalog = null; final String schemaPattern = "%"; final String functionNamePattern = "%"; final String columnNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_FUNCTION_COLUMNS, new Object[] { catalog, schemaPattern, functionNamePattern, columnNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getFunctionColumns(catalog, schemaPattern, functionNamePattern, columnNamePattern); }
@Test public void testMetadataGetFunctions() throws Exception { final String catalog = null; final String schemaPattern = "%"; final String functionNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_FUNCTIONS, new Object[] { catalog, schemaPattern, functionNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getFunctions(catalog, schemaPattern, functionNamePattern); }
@Test public void testMetadataGetImportedKeys() throws Exception { final String catalog = ""; final String schema = null; final String table = "my_table"; QueryState state = new QueryState(MetaDataOperation.GET_IMPORTED_KEYS, new Object[] { catalog, schema, table }); state.invoke(conn, statement); Mockito.verify(metadata).getImportedKeys(catalog, schema, table); }
@Test public void testMetadataGetIndexInfo() throws Exception { final String catalog = ""; final String schema = null; final String table = "my_table"; final boolean unique = true; final boolean approximate = true; QueryState state = new QueryState(MetaDataOperation.GET_INDEX_INFO, new Object[] { catalog, schema, table, unique, approximate }); state.invoke(conn, statement); Mockito.verify(metadata).getIndexInfo(catalog, schema, table, unique, approximate); }
@Test public void testMetadataGetPrimaryKeys() throws Exception { final String catalog = ""; final String schema = null; final String table = "my_table"; QueryState state = new QueryState(MetaDataOperation.GET_PRIMARY_KEYS, new Object[] { catalog, schema, table }); state.invoke(conn, statement); Mockito.verify(metadata).getPrimaryKeys(catalog, schema, table); }
@Test public void testMetadataGetProcedureColumns() throws Exception { final String catalog = ""; final String schemaPattern = null; final String procedureNamePattern = "%"; final String columnNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_PROCEDURE_COLUMNS, new Object[] { catalog, schemaPattern, procedureNamePattern, columnNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getProcedureColumns(catalog, schemaPattern, procedureNamePattern, columnNamePattern); }
@Test public void testMetadataGetProcedures() throws Exception { final String catalog = ""; final String schemaPattern = null; final String procedureNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_PROCEDURES, new Object[] { catalog, schemaPattern, procedureNamePattern, }); state.invoke(conn, statement); Mockito.verify(metadata).getProcedures(catalog, schemaPattern, procedureNamePattern); }
@Test public void testMetadataGetPseudoColumns() throws Exception { final String catalog = ""; final String schemaPattern = null; final String tableNamePattern = "%"; final String columnNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_PSEUDO_COLUMNS, new Object[] { catalog, schemaPattern, tableNamePattern, columnNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getPseudoColumns(catalog, schemaPattern, tableNamePattern, columnNamePattern); }
@Test public void testMetadataGetSchemas() throws Exception { QueryState state = new QueryState(MetaDataOperation.GET_SCHEMAS, new Object[0]); state.invoke(conn, statement); Mockito.verify(metadata).getSchemas(); }
@Test public void testMetadataGetSchemasWithArgs() throws Exception { final String catalog = ""; final String schemaPattern = null; QueryState state = new QueryState(MetaDataOperation.GET_SCHEMAS_WITH_ARGS, new Object[] { catalog, schemaPattern }); state.invoke(conn, statement); Mockito.verify(metadata).getSchemas(catalog, schemaPattern); }
@Test public void testMetadataGetSuperTables() throws Exception { final String catalog = ""; final String schemaPattern = null; final String tableNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_SUPER_TABLES, new Object[] { catalog, schemaPattern, tableNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getSuperTables(catalog, schemaPattern, tableNamePattern); }
@Test public void testMetadataGetSuperTypes() throws Exception { final String catalog = ""; final String schemaPattern = null; final String tableNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_SUPER_TYPES, new Object[] { catalog, schemaPattern, tableNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getSuperTypes(catalog, schemaPattern, tableNamePattern); }
@Test public void testMetadataGetTablePrivileges() throws Exception { final String catalog = ""; final String schemaPattern = null; final String tableNamePattern = "%"; QueryState state = new QueryState(MetaDataOperation.GET_TABLE_PRIVILEGES, new Object[] { catalog, schemaPattern, tableNamePattern }); state.invoke(conn, statement); Mockito.verify(metadata).getTablePrivileges(catalog, schemaPattern, tableNamePattern); }
@Test public void testMetadataGetTables() throws Exception { final String catalog = ""; final String schemaPattern = null; final String tableNamePattern = "%"; final String[] types = new String[] {"VIEW", "TABLE"}; QueryState state = new QueryState(MetaDataOperation.GET_TABLES, new Object[] { catalog, schemaPattern, tableNamePattern, types }); state.invoke(conn, statement); Mockito.verify(metadata).getTables(catalog, schemaPattern, tableNamePattern, types); }
@Test public void testMetadataGetTableTypes() throws Exception { QueryState state = new QueryState(MetaDataOperation.GET_TABLE_TYPES, new Object[0]); state.invoke(conn, statement); Mockito.verify(metadata).getTableTypes(); }
@Test public void testMetadataGetTypeInfo() throws Exception { QueryState state = new QueryState(MetaDataOperation.GET_TYPE_INFO, new Object[0]); state.invoke(conn, statement); Mockito.verify(metadata).getTypeInfo(); }
@Test public void testMetadataGetUDTs() throws Exception { final String catalog = ""; final String schemaPattern = null; final String typeNamePattern = "%"; final int[] types = new int[] {1, 2}; QueryState state = new QueryState(MetaDataOperation.GET_UDTS, new Object[] { catalog, schemaPattern, typeNamePattern, types }); state.invoke(conn, statement); Mockito.verify(metadata).getUDTs(catalog, schemaPattern, typeNamePattern, types); }
@Test public void testMetadataGetVersionColumns() throws Exception { final String catalog = ""; final String schemaPattern = null; final String table = "my_table"; QueryState state = new QueryState(MetaDataOperation.GET_VERSION_COLUMNS, new Object[] { catalog, schemaPattern, table }); state.invoke(conn, statement); Mockito.verify(metadata).getVersionColumns(catalog, schemaPattern, table); } |
NoopMetricsSystem implements MetricsSystem { public static NoopMetricsSystem getInstance() { return NOOP_METRICS; } private NoopMetricsSystem(); static NoopMetricsSystem getInstance(); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testSingleton() { assertTrue("Should be a singleton", NoopMetricsSystem.getInstance() == NoopMetricsSystem.getInstance()); } |
ArrayImpl implements Array { public Object getArray() throws SQLException { return getArray(list, accessor); } ArrayImpl(List<Object> list, AbstractCursor.ArrayAccessor accessor); String getBaseTypeName(); int getBaseType(); Object getArray(); @Override String toString(); @Override Object getArray(Map<String, Class<?>> map); @Override Object getArray(long index, int count); @Override Object getArray(long index, int count, Map<String, Class<?>> map); @Override ResultSet getResultSet(); @Override ResultSet getResultSet(Map<String, Class<?>> map); @Override ResultSet getResultSet(long index, int count); @Override ResultSet getResultSet(long index, int count,
Map<String, Class<?>> map); @Override void free(); static boolean equalContents(Array left, Array right); } | @Test public void arraysOfStructs() throws Exception { ColumnMetaData intMetaData = MetaImpl.columnMetaData("MY_INT", 1, int.class, false); ColumnMetaData stringMetaData = MetaImpl.columnMetaData("MY_STRING", 2, String.class, true); StructType structType = ColumnMetaData.struct(Arrays.asList(intMetaData, stringMetaData)); Struct struct1 = new StructImpl(Arrays.<Object>asList(1, "one")); Struct struct2 = new StructImpl(Arrays.<Object>asList(2, "two")); Struct struct3 = new StructImpl(Arrays.<Object>asList(3)); Struct struct4 = new StructImpl(Arrays.<Object>asList(4, "four")); ArrayType arrayType = ColumnMetaData.array(structType, "OBJECT", Rep.STRUCT); ColumnMetaData arrayMetaData = MetaImpl.columnMetaData("MY_ARRAY", 1, arrayType, false); ArrayImpl.Factory factory = new ArrayFactoryImpl(Unsafe.localCalendar().getTimeZone()); Array array1 = factory.createArray(structType, Arrays.<Object>asList(struct1, struct2)); Array array2 = factory.createArray(structType, Arrays.<Object>asList(struct3, struct4)); List<List<Object>> rows = Arrays.asList(Collections.<Object>singletonList(array1), Collections.<Object>singletonList(array2)); try (Cursor cursor = new ListIteratorCursor(rows.iterator())) { List<Accessor> accessors = cursor.createAccessors(Collections.singletonList(arrayMetaData), Unsafe.localCalendar(), factory); assertEquals(1, accessors.size()); Accessor accessor = accessors.get(0); assertTrue(cursor.next()); Array actualArray = accessor.getArray(); Object[] arrayData = (Object[]) actualArray.getArray(); assertEquals(2, arrayData.length); Struct actualStruct = (Struct) arrayData[0]; Object[] o = actualStruct.getAttributes(); assertEquals(2, o.length); assertEquals(1, o[0]); assertEquals("one", o[1]); actualStruct = (Struct) arrayData[1]; o = actualStruct.getAttributes(); assertEquals(2, o.length); assertEquals(2, o[0]); assertEquals("two", o[1]); assertTrue(cursor.next()); actualArray = accessor.getArray(); arrayData = (Object[]) actualArray.getArray(); assertEquals(2, arrayData.length); actualStruct = (Struct) arrayData[0]; o = actualStruct.getAttributes(); assertEquals(1, o.length); assertEquals(3, o[0]); actualStruct = (Struct) arrayData[1]; o = actualStruct.getAttributes(); assertEquals(2, o.length); assertEquals(4, o[0]); assertEquals("four", o[1]); } }
@Test public void testArrayWithOffsets() throws Exception { ScalarType intType = ColumnMetaData.scalar(Types.INTEGER, "INTEGER", Rep.INTEGER); ArrayImpl.Factory factory = new ArrayFactoryImpl(Unsafe.localCalendar().getTimeZone()); Array array1 = factory.createArray(intType, Arrays.<Object>asList(1, 2)); Array array3 = factory.createArray(intType, Arrays.<Object>asList(4, 5, 6)); Object[] data = (Object[]) array1.getArray(2, 1); assertEquals(1, data.length); assertEquals(2, data[0]); data = (Object[]) array3.getArray(1, 1); assertEquals(1, data.length); assertEquals(4, data[0]); data = (Object[]) array3.getArray(2, 2); assertEquals(2, data.length); assertEquals(5, data[0]); assertEquals(6, data[1]); data = (Object[]) array3.getArray(1, 3); assertEquals(3, data.length); assertEquals(4, data[0]); assertEquals(5, data[1]); assertEquals(6, data[2]); } |
ConnectionPropertiesImpl implements Meta.ConnectionProperties { @Override public ConnectionPropertiesImpl merge(Meta.ConnectionProperties that) { if (this == that) { return this; } if (that.isAutoCommit() != null && !Objects.equals(this.autoCommit, that.isAutoCommit())) { this.autoCommit = that.isAutoCommit(); this.isDirty = true; } if (that.isReadOnly() != null && !Objects.equals(this.readOnly, that.isReadOnly())) { this.readOnly = that.isReadOnly(); this.isDirty = true; } if (that.getTransactionIsolation() != null && !Objects.equals(this.transactionIsolation, that.getTransactionIsolation())) { this.transactionIsolation = that.getTransactionIsolation(); this.isDirty = true; } if (that.getCatalog() != null && !that.getCatalog().equalsIgnoreCase(this.catalog)) { this.catalog = that.getCatalog(); this.isDirty = true; } if (that.getSchema() != null && !that.getSchema().equalsIgnoreCase(this.schema)) { this.schema = that.getSchema(); this.isDirty = true; } return this; } ConnectionPropertiesImpl(); ConnectionPropertiesImpl(Connection conn); @JsonCreator ConnectionPropertiesImpl(
@JsonProperty("autoCommit") Boolean autoCommit,
@JsonProperty("readOnly") Boolean readOnly,
@JsonProperty("transactionIsolation") Integer transactionIsolation,
@JsonProperty("catalog") String catalog,
@JsonProperty("schema") String schema); ConnectionPropertiesImpl setDirty(boolean val); boolean isDirty(); @Override boolean isEmpty(); @Override ConnectionPropertiesImpl merge(Meta.ConnectionProperties that); @Override Meta.ConnectionProperties setAutoCommit(boolean val); @Override Boolean isAutoCommit(); @Override Meta.ConnectionProperties setReadOnly(boolean val); @Override Boolean isReadOnly(); @Override Meta.ConnectionProperties setTransactionIsolation(int val); Integer getTransactionIsolation(); @Override Meta.ConnectionProperties setCatalog(String val); @Override String getCatalog(); @Override Meta.ConnectionProperties setSchema(String val); String getSchema(); @Override int hashCode(); @Override boolean equals(Object o); Common.ConnectionProperties toProto(); static ConnectionPropertiesImpl fromProto(Common.ConnectionProperties proto); } | @Test public void testMerge() { ConnectionPropertiesImpl connectionProperties1 = new ConnectionPropertiesImpl( Boolean.FALSE, Boolean.TRUE, Integer.MAX_VALUE, "catalog", "schema"); ConnectionPropertiesImpl connectionProperties2 = new ConnectionPropertiesImpl( Boolean.FALSE, Boolean.TRUE, Integer.MAX_VALUE, "catalog", "schema"); assertThat( Objects.equals(connectionProperties1.isReadOnly(), connectionProperties2.isReadOnly()), is(true)); assertThat( Objects.equals(connectionProperties1.isAutoCommit(), connectionProperties2.isAutoCommit()), is(true)); assertThat( Objects.equals(connectionProperties1.getTransactionIsolation(), connectionProperties2.getTransactionIsolation()), is(true)); ConnectionPropertiesImpl merged = connectionProperties1.merge(connectionProperties2); assertThat(merged.isDirty(), is(false)); assertThat(Objects.equals(merged, connectionProperties1), is(true)); ConnectionPropertiesImpl connectionProperties3 = new ConnectionPropertiesImpl( null, null, null, "catalog", "schema"); assertThat( Objects.equals(connectionProperties1.isReadOnly(), connectionProperties3.isReadOnly()), is(false)); assertThat( Objects.equals(connectionProperties1.isAutoCommit(), connectionProperties3.isAutoCommit()), is(false)); assertThat( Objects.equals(connectionProperties1.getTransactionIsolation(), connectionProperties3.getTransactionIsolation()), is(false)); ConnectionPropertiesImpl merged1 = connectionProperties3.merge(connectionProperties1); assertThat(merged1.isDirty(), is(true)); assertThat(Objects.equals(merged1, connectionProperties1), is(false)); } |
ConnectionConfigImpl implements ConnectionConfig { public File truststore() { String filename = BuiltInConnectionProperty.TRUSTSTORE.wrap(properties).getString(); if (null == filename) { return null; } return new File(filename); } ConnectionConfigImpl(Properties properties); String schema(); String timeZone(); Service.Factory factory(); String url(); String serialization(); String authentication(); String avaticaUser(); String avaticaPassword(); AvaticaHttpClientFactory httpClientFactory(); String httpClientClass(); String kerberosPrincipal(); File kerberosKeytab(); File truststore(); String truststorePassword(); File keystore(); String keystorePassword(); String keyPassword(); HostnameVerification hostnameVerification(); static Map<ConnectionProperty, String> parse(Properties properties,
Map<String, ? extends ConnectionProperty> nameToProps); static Converter<E> enumConverter(
final Class<E> enumClass); static Converter<T> pluginConverter(final Class<T> pluginClass,
final T defaultInstance); static final Converter<Boolean> BOOLEAN_CONVERTER; static final Converter<Number> NUMBER_CONVERTER; static final Converter<String> IDENTITY_CONVERTER; } | @Test public void testTrustStore() { final String trustStore = "/my/truststore.jks"; final String windowsTrustStore = "my\\truststore.jks"; final String pw = "supremelysecret"; Properties props = new Properties(); props.setProperty(BuiltInConnectionProperty.TRUSTSTORE.name(), trustStore); props.setProperty(BuiltInConnectionProperty.TRUSTSTORE_PASSWORD.name(), pw); ConnectionConfigImpl config = new ConnectionConfigImpl(props); assertThat(config.truststore().getAbsolutePath(), File.separatorChar == '/' ? is(trustStore) : is(Paths.get(".").toAbsolutePath().getRoot() + windowsTrustStore)); assertThat(config.truststorePassword(), is(pw)); } |
TypedValue { public static TypedValue ofLocal(ColumnMetaData.Rep rep, Object value) { return new TypedValue(rep, localToSerial(rep, value)); } private TypedValue(ColumnMetaData.Rep rep, Object value); private TypedValue(ColumnMetaData.Rep rep, ColumnMetaData.Rep componentType, Object value); @JsonCreator static TypedValue create(@JsonProperty("type") String type,
@JsonProperty("value") Object value); static TypedValue ofLocal(ColumnMetaData.Rep rep, Object value); static TypedValue ofSerial(ColumnMetaData.Rep rep, Object value); static TypedValue ofJdbc(ColumnMetaData.Rep rep, Object value,
Calendar calendar); static TypedValue ofJdbc(Object value, Calendar calendar); Object toLocal(); Object toJdbc(Calendar calendar); static List<Object> values(List<TypedValue> typedValues); Common.TypedValue toProto(); static TypedValue fromProto(Common.TypedValue proto); static Object getSerialFromProto(Common.TypedValue protoValue); static Common.Rep toProto(Common.TypedValue.Builder builder, Object o); static Object protoToJdbc(Common.TypedValue protoValue, Calendar calendar); @Override int hashCode(); @Override boolean equals(Object o); static final TypedValue EXPLICIT_NULL; static final Common.TypedValue PROTO_IMPLICIT_NULL; final ColumnMetaData.Rep type; final Object value; final ColumnMetaData.Rep componentType; } | @Test public void testBoolean() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_BOOLEAN, true)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.BOOLEAN, Boolean.TRUE)); }
@Test public void testByte() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_BYTE, (byte) 4)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.BYTE, Byte.valueOf((byte) 4))); }
@Test public void testShort() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_SHORT, (short) 42)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.SHORT, Short.valueOf((short) 42))); }
@Test public void testInteger() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_INT, (int) 42000)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.INTEGER, Integer.valueOf((int) 42000))); }
@Test public void testLong() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_LONG, Long.MAX_VALUE)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.LONG, Long.valueOf(Long.MAX_VALUE))); }
@Test public void testFloat() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_FLOAT, 3.14159f)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.FLOAT, Float.valueOf(3.14159f))); }
@Test public void testDouble() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_DOUBLE, Double.MAX_VALUE)); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.DOUBLE, Double.valueOf(Double.MAX_VALUE))); }
@Test public void testChar() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.PRIMITIVE_CHAR, 'c')); serializeAndEqualityCheck(TypedValue.ofLocal(Rep.CHARACTER, Character.valueOf('c'))); }
@Test public void testString() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.STRING, "qwertyasdf")); }
@Test public void testByteString() { serializeAndEqualityCheck( TypedValue.ofLocal(Rep.BYTE_STRING, new ByteString("qwertyasdf".getBytes(UTF_8)))); }
@Test public void testSqlDate() { serializeAndEqualityCheck(TypedValue.ofLocal(Rep.JAVA_SQL_DATE, 25)); }
@Test public void testUtilDate() { serializeAndEqualityCheck( TypedValue.ofLocal(Rep.JAVA_UTIL_DATE, System.currentTimeMillis())); }
@Test public void testSqlTime() { serializeAndEqualityCheck( TypedValue.ofLocal(Rep.JAVA_SQL_TIME, 42 * 1024 * 1024)); }
@Test public void testSqlTimestamp() { serializeAndEqualityCheck( TypedValue.ofLocal(Rep.JAVA_SQL_TIMESTAMP, 42L * 1024 * 1024 * 1024)); } |
UnsynchronizedBuffer extends OutputStream { public static int nextArraySize(int i) { if (i < 0) { throw new IllegalArgumentException(); } if (i > (1 << 30)) { return Integer.MAX_VALUE; } if (i == 0) { return 1; } int ret = i; ret--; ret |= ret >> 1; ret |= ret >> 2; ret |= ret >> 4; ret |= ret >> 8; ret |= ret >> 16; ret++; return ret; } UnsynchronizedBuffer(); UnsynchronizedBuffer(int initialCapacity); void write(byte[] bytes, int off, int length); @Override void write(int b); byte[] toArray(); void reset(); int getOffset(); long getSize(); static int nextArraySize(int i); } | @Test public void testArrayResizing() { int size = 64; int expected = 128; for (int i = 0; i < 10; i++) { int next = UnsynchronizedBuffer.nextArraySize(size + 1); assertEquals(expected, next); size = next; expected *= 2; } } |
TypedValue { public static TypedValue fromProto(Common.TypedValue proto) { ColumnMetaData.Rep rep = ColumnMetaData.Rep.fromProto(proto.getType()); ColumnMetaData.Rep componentRep = ColumnMetaData.Rep.fromProto(proto.getComponentType()); Object value = getSerialFromProto(proto); return new TypedValue(rep, componentRep, value); } private TypedValue(ColumnMetaData.Rep rep, Object value); private TypedValue(ColumnMetaData.Rep rep, ColumnMetaData.Rep componentType, Object value); @JsonCreator static TypedValue create(@JsonProperty("type") String type,
@JsonProperty("value") Object value); static TypedValue ofLocal(ColumnMetaData.Rep rep, Object value); static TypedValue ofSerial(ColumnMetaData.Rep rep, Object value); static TypedValue ofJdbc(ColumnMetaData.Rep rep, Object value,
Calendar calendar); static TypedValue ofJdbc(Object value, Calendar calendar); Object toLocal(); Object toJdbc(Calendar calendar); static List<Object> values(List<TypedValue> typedValues); Common.TypedValue toProto(); static TypedValue fromProto(Common.TypedValue proto); static Object getSerialFromProto(Common.TypedValue protoValue); static Common.Rep toProto(Common.TypedValue.Builder builder, Object o); static Object protoToJdbc(Common.TypedValue protoValue, Calendar calendar); @Override int hashCode(); @Override boolean equals(Object o); static final TypedValue EXPLICIT_NULL; static final Common.TypedValue PROTO_IMPLICIT_NULL; final ColumnMetaData.Rep type; final Object value; final ColumnMetaData.Rep componentType; } | @Test public void testLegacyBase64StringEncodingForBytes() { final byte[] bytes = "asdf".getBytes(UTF_8); final String base64Str = Base64.encodeBytes(bytes); Common.TypedValue.Builder builder = Common.TypedValue.newBuilder(); builder.setStringValue(base64Str); builder.setType(Common.Rep.BYTE_STRING); Common.TypedValue protoTv = builder.build(); TypedValue tv = TypedValue.fromProto(protoTv); assertEquals(Rep.BYTE_STRING, tv.type); assertEquals(base64Str, tv.value); } |
StructImpl implements Struct { @Override public Object[] getAttributes() throws SQLException { return list.toArray(); } StructImpl(List list); @Override String toString(); @Override String getSQLTypeName(); @Override Object[] getAttributes(); @Override Object[] getAttributes(Map<String, Class<?>> map); } | @Test public void testStructAccessor() throws Exception { List<List<Object>> rows = new ArrayList<>(); for (Object o : columnInputBundle.inputValues) { rows.add(Collections.singletonList(o)); } try (Cursor cursor = new ListIteratorCursor(rows.iterator())) { List<Accessor> accessors = cursor.createAccessors( Collections.singletonList(columnInputBundle.metaData), Unsafe.localCalendar(), null); Accessor accessor = accessors.get(0); int i = 0; while (cursor.next()) { Struct s = accessor.getObject(Struct.class); Object[] expectedStructAttributes = columnInputBundle.expectedValues.get(i).getAttributes(); Object[] actualStructAttributes = s.getAttributes(); assertArrayEquals(expectedStructAttributes, actualStructAttributes); i++; } } } |
AbstractHandler implements Handler<T> { ErrorResponse unwrapException(Exception e) { int errorCode = ErrorResponse.UNKNOWN_ERROR_CODE; String sqlState = ErrorResponse.UNKNOWN_SQL_STATE; AvaticaSeverity severity = AvaticaSeverity.UNKNOWN; String errorMsg = null; if (e instanceof AvaticaRuntimeException) { AvaticaRuntimeException rte = (AvaticaRuntimeException) e; errorCode = rte.getErrorCode(); sqlState = rte.getSqlState(); severity = rte.getSeverity(); errorMsg = rte.getErrorMessage(); } else if (e instanceof NoSuchConnectionException) { errorCode = ErrorResponse.MISSING_CONNECTION_ERROR_CODE; severity = AvaticaSeverity.ERROR; errorMsg = e.getMessage(); } else { errorMsg = getCausalChain(e); } return new ErrorResponse(e, errorMsg, errorCode, sqlState, severity, metadata); } AbstractHandler(Service service); HandlerResponse<T> apply(T serializedRequest); HandlerResponse<T> convertToErrorResponse(Exception e); HandlerResponse<T> unauthenticatedErrorResponse(Exception e); HandlerResponse<T> unauthorizedErrorResponse(Exception e); @Override void setRpcMetadata(RpcMetadataResponse metadata); } | @Test public void testExceptionUnwrappingWithoutContext() { @SuppressWarnings("unchecked") AbstractHandler<String> handler = Mockito.mock(AbstractHandler.class); Mockito.when(handler.unwrapException(Mockito.any(Exception.class))).thenCallRealMethod(); Exception e = new RuntimeException(); Response resp = handler.unwrapException(e); assertTrue("Response should be ErrorResponse, but was " + resp.getClass(), resp instanceof ErrorResponse); ErrorResponse errorResp = (ErrorResponse) resp; assertEquals(ErrorResponse.UNKNOWN_ERROR_CODE, errorResp.errorCode); assertEquals(AvaticaSeverity.UNKNOWN, errorResp.severity); assertEquals(Arrays.asList(exceptionToString(e)), errorResp.exceptions); e = new AvaticaRuntimeException(); resp = handler.unwrapException(e); assertTrue("Response should be ErrorResponse, but was " + resp.getClass(), resp instanceof ErrorResponse); errorResp = (ErrorResponse) resp; assertEquals(ErrorResponse.UNKNOWN_ERROR_CODE, errorResp.errorCode); assertEquals(AvaticaSeverity.UNKNOWN, errorResp.severity); assertEquals(Arrays.asList(exceptionToString(e)), errorResp.exceptions); }
@Test public void testExceptionUnwrappingWithContext() { @SuppressWarnings("unchecked") AbstractHandler<String> handler = Mockito.mock(AbstractHandler.class); Mockito.when(handler.unwrapException(Mockito.any(Exception.class))).thenCallRealMethod(); final String msg = "Something failed!"; AvaticaRuntimeException e = new AvaticaRuntimeException(msg, ErrorResponse.UNKNOWN_ERROR_CODE, ErrorResponse.UNKNOWN_SQL_STATE, AvaticaSeverity.FATAL); Response resp = handler.unwrapException(e); assertTrue("Response should be ErrorResponse, but was " + resp.getClass(), resp instanceof ErrorResponse); ErrorResponse errorResp = (ErrorResponse) resp; assertEquals(ErrorResponse.UNKNOWN_ERROR_CODE, errorResp.errorCode); assertEquals(AvaticaSeverity.FATAL, errorResp.severity); assertEquals(Arrays.asList(exceptionToString(e)), errorResp.exceptions); assertEquals(msg, errorResp.errorMessage); } |
ProtobufService extends AbstractService { public static <T extends Message> T castProtobufMessage(Message msg, Class<T> expectedType) { if (!expectedType.isInstance(msg)) { throw new IllegalArgumentException("Expected instance of " + expectedType.getName() + ", but got " + msg.getClass().getName()); } return expectedType.cast(msg); } abstract Response _apply(Request request); @Override ResultSetResponse apply(CatalogsRequest request); @Override ResultSetResponse apply(SchemasRequest request); @Override ResultSetResponse apply(TablesRequest request); @Override ResultSetResponse apply(TableTypesRequest request); @Override ResultSetResponse apply(TypeInfoRequest request); @Override ResultSetResponse apply(ColumnsRequest request); @Override PrepareResponse apply(PrepareRequest request); @Override ExecuteResponse apply(PrepareAndExecuteRequest request); @Override FetchResponse apply(FetchRequest request); @Override CreateStatementResponse apply(CreateStatementRequest request); @Override CloseStatementResponse apply(CloseStatementRequest request); @Override OpenConnectionResponse apply(OpenConnectionRequest request); @Override CloseConnectionResponse apply(CloseConnectionRequest request); @Override ConnectionSyncResponse apply(ConnectionSyncRequest request); @Override DatabasePropertyResponse apply(DatabasePropertyRequest request); @Override ExecuteResponse apply(ExecuteRequest request); @Override SyncResultsResponse apply(SyncResultsRequest request); @Override CommitResponse apply(CommitRequest request); @Override RollbackResponse apply(RollbackRequest request); @Override ExecuteBatchResponse apply(PrepareAndExecuteBatchRequest request); @Override ExecuteBatchResponse apply(ExecuteBatchRequest request); static T castProtobufMessage(Message msg, Class<T> expectedType); } | @Test public void testCastProtobufMessage() { final Requests.CommitRequest commitReq = Requests.CommitRequest.newBuilder().setConnectionId("cnxn1").build(); final Requests.RollbackRequest rollbackReq = Requests.RollbackRequest.newBuilder().setConnectionId("cnxn1").build(); assertEquals(commitReq, ProtobufService.castProtobufMessage(commitReq, Requests.CommitRequest.class)); assertEquals(rollbackReq, ProtobufService.castProtobufMessage(rollbackReq, Requests.RollbackRequest.class)); try { ProtobufService.castProtobufMessage(commitReq, Requests.RollbackRequest.class); fail("Should have seen IllegalArgumentException casting CommitRequest into RollbackRequest"); } catch (IllegalArgumentException e) { } try { ProtobufService.castProtobufMessage(rollbackReq, Requests.CommitRequest.class); fail("Should have seen IllegalArgumentException casting RollbackRequest into CommitRequest"); } catch (IllegalArgumentException e) { } } |
AvaticaCommonsHttpClientImpl implements AvaticaHttpClient,
UsernamePasswordAuthenticateable, TrustStoreConfigurable,
KeyStoreConfigurable, HostnameVerificationConfigurable { HostnameVerifier getHostnameVerifier(HostnameVerification verification) { if (verification == null) { verification = HostnameVerification.STRICT; } switch (verification) { case STRICT: return SSLConnectionSocketFactory.getDefaultHostnameVerifier(); case NONE: return NoopHostnameVerifier.INSTANCE; default: throw new IllegalArgumentException("Unhandled HostnameVerification: " + hostnameVerification); } } AvaticaCommonsHttpClientImpl(URL url); @Override byte[] send(byte[] request); @Override void setUsernamePassword(AuthenticationType authType, String username,
String password); @Override void setTrustStore(File truststore, String password); @Override void setKeyStore(File keystore, String keystorepassword, String keypassword); @Override void setHostnameVerification(HostnameVerification verification); } | @Test public void testHostnameVerification() throws Exception { AvaticaCommonsHttpClientImpl client = mock(AvaticaCommonsHttpClientImpl.class); when(client.getHostnameVerifier(nullable(HostnameVerification.class))) .thenCallRealMethod(); HostnameVerifier actualVerifier = client.getHostnameVerifier(null); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.STRICT); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof DefaultHostnameVerifier); actualVerifier = client.getHostnameVerifier(HostnameVerification.NONE); assertNotNull(actualVerifier); assertTrue(actualVerifier instanceof NoopHostnameVerifier); } |
ProtobufHandler extends AbstractHandler<byte[]> { @Override public HandlerResponse<byte[]> apply(byte[] requestBytes) { return super.apply(requestBytes); } ProtobufHandler(Service service, ProtobufTranslation translation, MetricsSystem metrics); @Override HandlerResponse<byte[]> apply(byte[] requestBytes); } | @Test public void testFetch() throws Exception { final String connectionId = "cnxn1"; final int statementId = 30; final long offset = 10; final int fetchMaxRowCount = 100; final List<Common.TypedValue> values = new ArrayList<>(); values.add(Common.TypedValue.newBuilder().setType(Common.Rep.BOOLEAN).setBoolValue(true) .build()); values.add(Common.TypedValue.newBuilder().setType(Common.Rep.STRING) .setStringValue("my_string").build()); Requests.FetchRequest protoRequest = Requests.FetchRequest.newBuilder() .setConnectionId(connectionId).setStatementId(statementId) .setOffset(offset).setFetchMaxRowCount(fetchMaxRowCount) .build(); byte[] serializedRequest = protoRequest.toByteArray(); FetchRequest request = new FetchRequest().deserialize(protoRequest); List<Object> frameRows = new ArrayList<>(); frameRows.add(new Object[] {true, "my_string"}); Meta.Frame frame = Frame.create(0, true, frameRows); RpcMetadataResponse metadata = new RpcMetadataResponse("localhost:8765"); FetchResponse response = new FetchResponse(frame, false, false, metadata); when(translation.parseRequest(serializedRequest)).thenReturn(request); when(service.apply(request)).thenReturn(response); when(translation.serializeResponse(response)) .thenReturn(response.serialize().toByteArray()); HandlerResponse<byte[]> handlerResponse = handler.apply(serializedRequest); byte[] serializedResponse = handlerResponse.getResponse(); assertEquals(200, handlerResponse.getStatusCode()); Responses.FetchResponse protoResponse = Responses.FetchResponse.parseFrom(serializedResponse); Common.Frame protoFrame = protoResponse.getFrame(); assertEquals(frame.offset, protoFrame.getOffset()); assertEquals(frame.done, protoFrame.getDone()); List<Common.Row> rows = protoFrame.getRowsList(); assertEquals(1, rows.size()); Common.Row row = rows.get(0); List<Common.ColumnValue> columnValues = row.getValueList(); assertEquals(2, columnValues.size()); Iterator<Common.ColumnValue> iter = columnValues.iterator(); assertTrue(iter.hasNext()); Common.ColumnValue column = iter.next(); assertTrue("The Column should have contained a scalar: " + column, column.hasField(ColumnValue.getDescriptor() .findFieldByNumber(ColumnValue.SCALAR_VALUE_FIELD_NUMBER))); Common.TypedValue value = column.getScalarValue(); assertEquals(Common.Rep.BOOLEAN, value.getType()); assertEquals(true, value.getBoolValue()); assertTrue(iter.hasNext()); column = iter.next(); assertTrue("The Column should have contained a scalar: " + column, column.hasField(ColumnValue.getDescriptor() .findFieldByNumber(ColumnValue.SCALAR_VALUE_FIELD_NUMBER))); value = column.getScalarValue(); assertEquals(Common.Rep.STRING, value.getType()); assertEquals("my_string", value.getStringValue()); } |
KerberosConnection { Entry<RenewalTask, Thread> createRenewalThread(LoginContext originalContext, Subject originalSubject, long renewalPeriod) { RenewalTask task = new RenewalTask(this, originalContext, originalSubject, jaasConf, renewalPeriod); Thread t = new Thread(task); t.setDaemon(true); t.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { LOG.error("Uncaught exception from Kerberos credential renewal thread", e); } }); t.setName(RENEWAL_THREAD_NAME); return new AbstractMap.SimpleEntry<>(task, t); } KerberosConnection(String principal, File keytab); synchronized Subject getSubject(); synchronized void login(); void stopRenewalThread(); static boolean isIbmJava(); static String getKrb5LoginModuleName(); static final float PERCENT_OF_LIFETIME_TO_RENEW; static final long RENEWAL_PERIOD; } | @Test public void testThreadConfiguration() { KerberosConnection krbUtil = new KerberosConnection("foo", new File("/bar.keytab")); Subject subject = new Subject(); LoginContext context = Mockito.mock(LoginContext.class); Entry<RenewalTask, Thread> entry = krbUtil.createRenewalThread(context, subject, 10); assertNotNull("RenewalTask should not be null", entry.getKey()); Thread t = entry.getValue(); assertTrue("Thread name should contain 'Avatica', but is '" + t.getName() + "'", t.getName().contains("Avatica")); assertTrue(t.isDaemon()); assertNotNull(t.getUncaughtExceptionHandler()); } |
AvaticaStatement implements Statement { public boolean getMoreResults() throws SQLException { checkOpen(); return getMoreResults(CLOSE_CURRENT_RESULT); } protected AvaticaStatement(AvaticaConnection connection,
Meta.StatementHandle h, int resultSetType, int resultSetConcurrency,
int resultSetHoldability); protected AvaticaStatement(AvaticaConnection connection,
Meta.StatementHandle h, int resultSetType, int resultSetConcurrency,
int resultSetHoldability, Meta.Signature signature); Meta.StatementType getStatementType(); int getId(); boolean execute(String sql); ResultSet executeQuery(String sql); final int executeUpdate(String sql); long executeLargeUpdate(String sql); synchronized void close(); int getMaxFieldSize(); void setMaxFieldSize(int max); final int getMaxRows(); long getLargeMaxRows(); final void setMaxRows(int maxRowCount); void setLargeMaxRows(long maxRowCount); void setEscapeProcessing(boolean enable); int getQueryTimeout(); void setQueryTimeout(int seconds); synchronized void cancel(); SQLWarning getWarnings(); void clearWarnings(); void setCursorName(String name); ResultSet getResultSet(); int getUpdateCount(); long getLargeUpdateCount(); boolean getMoreResults(); void setFetchDirection(int direction); int getFetchDirection(); void setFetchSize(int rows); int getFetchSize(); int getResultSetConcurrency(); int getResultSetType(); void addBatch(String sql); void clearBatch(); int[] executeBatch(); long[] executeLargeBatch(); AvaticaConnection getConnection(); boolean getMoreResults(int current); ResultSet getGeneratedKeys(); int executeUpdate(
String sql, int autoGeneratedKeys); int executeUpdate(
String sql, int[] columnIndexes); int executeUpdate(
String sql, String[] columnNames); boolean execute(
String sql, int autoGeneratedKeys); boolean execute(
String sql, int[] columnIndexes); boolean execute(
String sql, String[] columnNames); int getResultSetHoldability(); boolean isClosed(); void setPoolable(boolean poolable); boolean isPoolable(); void closeOnCompletion(); boolean isCloseOnCompletion(); T unwrap(Class<T> iface); boolean isWrapperFor(Class<?> iface); static final int DEFAULT_FETCH_SIZE; final AvaticaConnection connection; public Meta.StatementHandle handle; } | @Test public void testGetMoreResults() throws SQLException { AvaticaResultSet resultSet = mock(AvaticaResultSet.class); statement.openResultSet = resultSet; doCallRealMethod().when(statement).onResultSetClose(any(ResultSet.class)); when(statement.getMoreResults()).thenCallRealMethod(); when(statement.getMoreResults(anyInt())).thenCallRealMethod(); assertFalse(statement.getMoreResults()); verify(resultSet).close(); } |
AvaticaConnection implements Connection { public boolean isValid(int timeout) throws SQLException { if (timeout < 0) { throw HELPER.createException("timeout is less than 0"); } return !isClosed(); } protected AvaticaConnection(UnregisteredDriver driver,
AvaticaFactory factory,
String url,
Properties info); ConnectionConfig config(); void openConnection(); AvaticaStatement createStatement(); PreparedStatement prepareStatement(String sql); CallableStatement prepareCall(String sql); String nativeSQL(String sql); void setAutoCommit(boolean autoCommit); boolean getAutoCommit(); void commit(); void rollback(); void close(); boolean isClosed(); DatabaseMetaData getMetaData(); void setReadOnly(boolean readOnly); boolean isReadOnly(); void setCatalog(String catalog); String getCatalog(); void setTransactionIsolation(int level); int getTransactionIsolation(); SQLWarning getWarnings(); void clearWarnings(); Statement createStatement(
int resultSetType, int resultSetConcurrency); PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency); CallableStatement prepareCall(
String sql,
int resultSetType,
int resultSetConcurrency); Map<String, Class<?>> getTypeMap(); void setTypeMap(Map<String, Class<?>> map); void setHoldability(int holdability); int getHoldability(); Savepoint setSavepoint(); Savepoint setSavepoint(String name); void rollback(Savepoint savepoint); void releaseSavepoint(Savepoint savepoint); AvaticaStatement createStatement(
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); CallableStatement prepareCall(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); PreparedStatement prepareStatement(
String sql, int autoGeneratedKeys); PreparedStatement prepareStatement(
String sql, int[] columnIndexes); PreparedStatement prepareStatement(
String sql, String[] columnNames); Clob createClob(); Blob createBlob(); NClob createNClob(); SQLXML createSQLXML(); boolean isValid(int timeout); void setClientInfo(String name, String value); void setClientInfo(Properties properties); String getClientInfo(String name); Properties getClientInfo(); Array createArrayOf(String typeName, Object[] elements); Struct createStruct(String typeName, Object[] attributes); void setSchema(String schema); String getSchema(); void abort(Executor executor); void setNetworkTimeout(
Executor executor, int milliseconds); int getNetworkTimeout(); T unwrap(Class<T> iface); boolean isWrapperFor(Class<?> iface); TimeZone getTimeZone(); AtomicBoolean getCancelFlag(Meta.StatementHandle h); T invokeWithRetries(CallableWithoutException<T> callable); void setKerberosConnection(KerberosConnection kerberosConnection); KerberosConnection getKerberosConnection(); Service getService(); void setService(Service service); static final String ROWCOUNT_COLUMN_NAME; static final String NUM_EXECUTE_RETRIES_KEY; static final String NUM_EXECUTE_RETRIES_DEFAULT; static final String PLAN_COLUMN_NAME; static final Helper HELPER; final String id; final Meta.ConnectionHandle handle; final Map<InternalProperty, Object> properties; final Map<Integer, AvaticaStatement> statementMap; } | @Test public void testIsValid() throws SQLException { AvaticaConnection connection = Mockito.mock(AvaticaConnection.class, Mockito.CALLS_REAL_METHODS); try { connection.isValid(-1); Assert.fail("Connection isValid should throw SQLException on negative timeout"); } catch (SQLException expected) { Assert.assertEquals("timeout is less than 0", expected.getMessage()); } Mockito.when(connection.isClosed()).thenReturn(false); Assert.assertTrue(connection.isValid(0)); Mockito.when(connection.isClosed()).thenReturn(true); Assert.assertFalse(connection.isValid(0)); } |
AvaticaConnection implements Connection { long getNumStatementRetries(Properties props) { return Long.parseLong(Objects.requireNonNull(props) .getProperty(NUM_EXECUTE_RETRIES_KEY, NUM_EXECUTE_RETRIES_DEFAULT)); } protected AvaticaConnection(UnregisteredDriver driver,
AvaticaFactory factory,
String url,
Properties info); ConnectionConfig config(); void openConnection(); AvaticaStatement createStatement(); PreparedStatement prepareStatement(String sql); CallableStatement prepareCall(String sql); String nativeSQL(String sql); void setAutoCommit(boolean autoCommit); boolean getAutoCommit(); void commit(); void rollback(); void close(); boolean isClosed(); DatabaseMetaData getMetaData(); void setReadOnly(boolean readOnly); boolean isReadOnly(); void setCatalog(String catalog); String getCatalog(); void setTransactionIsolation(int level); int getTransactionIsolation(); SQLWarning getWarnings(); void clearWarnings(); Statement createStatement(
int resultSetType, int resultSetConcurrency); PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency); CallableStatement prepareCall(
String sql,
int resultSetType,
int resultSetConcurrency); Map<String, Class<?>> getTypeMap(); void setTypeMap(Map<String, Class<?>> map); void setHoldability(int holdability); int getHoldability(); Savepoint setSavepoint(); Savepoint setSavepoint(String name); void rollback(Savepoint savepoint); void releaseSavepoint(Savepoint savepoint); AvaticaStatement createStatement(
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); PreparedStatement prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); CallableStatement prepareCall(
String sql,
int resultSetType,
int resultSetConcurrency,
int resultSetHoldability); PreparedStatement prepareStatement(
String sql, int autoGeneratedKeys); PreparedStatement prepareStatement(
String sql, int[] columnIndexes); PreparedStatement prepareStatement(
String sql, String[] columnNames); Clob createClob(); Blob createBlob(); NClob createNClob(); SQLXML createSQLXML(); boolean isValid(int timeout); void setClientInfo(String name, String value); void setClientInfo(Properties properties); String getClientInfo(String name); Properties getClientInfo(); Array createArrayOf(String typeName, Object[] elements); Struct createStruct(String typeName, Object[] attributes); void setSchema(String schema); String getSchema(); void abort(Executor executor); void setNetworkTimeout(
Executor executor, int milliseconds); int getNetworkTimeout(); T unwrap(Class<T> iface); boolean isWrapperFor(Class<?> iface); TimeZone getTimeZone(); AtomicBoolean getCancelFlag(Meta.StatementHandle h); T invokeWithRetries(CallableWithoutException<T> callable); void setKerberosConnection(KerberosConnection kerberosConnection); KerberosConnection getKerberosConnection(); Service getService(); void setService(Service service); static final String ROWCOUNT_COLUMN_NAME; static final String NUM_EXECUTE_RETRIES_KEY; static final String NUM_EXECUTE_RETRIES_DEFAULT; static final String PLAN_COLUMN_NAME; static final Helper HELPER; final String id; final Meta.ConnectionHandle handle; final Map<InternalProperty, Object> properties; final Map<Integer, AvaticaStatement> statementMap; } | @Test public void testNumExecuteRetries() { AvaticaConnection connection = Mockito.mock(AvaticaConnection.class, Mockito.CALLS_REAL_METHODS); try { connection.getNumStatementRetries(null); Assert.fail("Calling getNumStatementRetries with a null object should throw an exception"); } catch (NullPointerException e) { } Properties props = new Properties(); Assert.assertEquals(Long.parseLong(AvaticaConnection.NUM_EXECUTE_RETRIES_DEFAULT), connection.getNumStatementRetries(props)); props.setProperty(AvaticaConnection.NUM_EXECUTE_RETRIES_KEY, "10"); Assert.assertEquals(10, connection.getNumStatementRetries(props)); } |
AvaticaResultSet extends ArrayFactoryImpl implements ResultSet { public int getRow() throws SQLException { checkOpen(); return row; } AvaticaResultSet(AvaticaStatement statement,
QueryState state,
Meta.Signature signature,
ResultSetMetaData resultSetMetaData,
TimeZone timeZone,
Meta.Frame firstFrame); void close(); AvaticaResultSet execute2(Cursor cursor,
List<ColumnMetaData> columnMetaDataList); Calendar getLocalCalendar(); boolean next(); int findColumn(String columnLabel); boolean wasNull(); String getString(int columnIndex); boolean getBoolean(int columnIndex); byte getByte(int columnIndex); short getShort(int columnIndex); int getInt(int columnIndex); long getLong(int columnIndex); float getFloat(int columnIndex); double getDouble(int columnIndex); @SuppressWarnings("deprecation") BigDecimal getBigDecimal(
int columnIndex, int scale); byte[] getBytes(int columnIndex); Date getDate(int columnIndex); Time getTime(int columnIndex); Timestamp getTimestamp(int columnIndex); InputStream getAsciiStream(int columnIndex); @SuppressWarnings("deprecation") InputStream getUnicodeStream(int columnIndex); InputStream getBinaryStream(int columnIndex); String getString(String columnLabel); boolean getBoolean(String columnLabel); byte getByte(String columnLabel); short getShort(String columnLabel); int getInt(String columnLabel); long getLong(String columnLabel); float getFloat(String columnLabel); double getDouble(String columnLabel); @SuppressWarnings("deprecation") BigDecimal getBigDecimal(
String columnLabel, int scale); byte[] getBytes(String columnLabel); Date getDate(String columnLabel); Time getTime(String columnLabel); Timestamp getTimestamp(String columnLabel); InputStream getAsciiStream(String columnLabel); @SuppressWarnings("deprecation") InputStream getUnicodeStream(String columnLabel); InputStream getBinaryStream(String columnLabel); SQLWarning getWarnings(); void clearWarnings(); String getCursorName(); ResultSetMetaData getMetaData(); Object getObject(int columnIndex); Object getObject(String columnLabel); Reader getCharacterStream(int columnIndex); Reader getCharacterStream(String columnLabel); BigDecimal getBigDecimal(int columnIndex); BigDecimal getBigDecimal(String columnLabel); boolean isBeforeFirst(); boolean isAfterLast(); boolean isFirst(); boolean isLast(); void beforeFirst(); void afterLast(); boolean first(); boolean last(); int getRow(); boolean absolute(int row); boolean relative(int rows); boolean previous(); void setFetchDirection(int direction); int getFetchDirection(); void setFetchSize(int fetchSize); int getFetchSize(); int getType(); int getConcurrency(); boolean rowUpdated(); boolean rowInserted(); boolean rowDeleted(); void updateNull(int columnIndex); void updateBoolean(int columnIndex, boolean x); void updateByte(int columnIndex, byte x); void updateShort(int columnIndex, short x); void updateInt(int columnIndex, int x); void updateLong(int columnIndex, long x); void updateFloat(int columnIndex, float x); void updateDouble(int columnIndex, double x); void updateBigDecimal(
int columnIndex, BigDecimal x); void updateString(int columnIndex, String x); void updateBytes(int columnIndex, byte[] x); void updateDate(int columnIndex, Date x); void updateTime(int columnIndex, Time x); void updateTimestamp(
int columnIndex, Timestamp x); void updateAsciiStream(
int columnIndex, InputStream x, int length); void updateBinaryStream(
int columnIndex, InputStream x, int length); void updateCharacterStream(
int columnIndex, Reader x, int length); void updateObject(
int columnIndex, Object x, int scaleOrLength); void updateObject(int columnIndex, Object x); void updateNull(String columnLabel); void updateBoolean(
String columnLabel, boolean x); void updateByte(String columnLabel, byte x); void updateShort(String columnLabel, short x); void updateInt(String columnLabel, int x); void updateLong(String columnLabel, long x); void updateFloat(String columnLabel, float x); void updateDouble(String columnLabel, double x); void updateBigDecimal(
String columnLabel, BigDecimal x); void updateString(String columnLabel, String x); void updateBytes(String columnLabel, byte[] x); void updateDate(String columnLabel, Date x); void updateTime(String columnLabel, Time x); void updateTimestamp(
String columnLabel, Timestamp x); void updateAsciiStream(
String columnLabel, InputStream x, int length); void updateBinaryStream(
String columnLabel, InputStream x, int length); void updateCharacterStream(
String columnLabel, Reader reader, int length); void updateObject(
String columnLabel, Object x, int scaleOrLength); void updateObject(String columnLabel, Object x); void insertRow(); void updateRow(); void deleteRow(); void refreshRow(); void cancelRowUpdates(); void moveToInsertRow(); void moveToCurrentRow(); AvaticaStatement getStatement(); Object getObject(
int columnIndex, Map<String, Class<?>> map); Ref getRef(int columnIndex); Blob getBlob(int columnIndex); Clob getClob(int columnIndex); Array getArray(int columnIndex); Object getObject(
String columnLabel, Map<String, Class<?>> map); Ref getRef(String columnLabel); Blob getBlob(String columnLabel); Clob getClob(String columnLabel); Array getArray(String columnLabel); Date getDate(int columnIndex, Calendar cal); Date getDate(String columnLabel, Calendar cal); Time getTime(int columnIndex, Calendar cal); Time getTime(String columnLabel, Calendar cal); Timestamp getTimestamp(
int columnIndex, Calendar cal); Timestamp getTimestamp(
String columnLabel, Calendar cal); URL getURL(int columnIndex); URL getURL(String columnLabel); void updateRef(int columnIndex, Ref x); void updateRef(String columnLabel, Ref x); void updateBlob(int columnIndex, Blob x); void updateBlob(String columnLabel, Blob x); void updateClob(int columnIndex, Clob x); void updateClob(String columnLabel, Clob x); void updateArray(int columnIndex, Array x); void updateArray(String columnLabel, Array x); RowId getRowId(int columnIndex); RowId getRowId(String columnLabel); void updateRowId(int columnIndex, RowId x); void updateRowId(String columnLabel, RowId x); int getHoldability(); boolean isClosed(); void updateNString(
int columnIndex, String nString); void updateNString(
String columnLabel, String nString); void updateNClob(int columnIndex, NClob nClob); void updateNClob(
String columnLabel, NClob nClob); NClob getNClob(int columnIndex); NClob getNClob(String columnLabel); SQLXML getSQLXML(int columnIndex); SQLXML getSQLXML(String columnLabel); void updateSQLXML(
int columnIndex, SQLXML xmlObject); void updateSQLXML(
String columnLabel, SQLXML xmlObject); String getNString(int columnIndex); String getNString(String columnLabel); Reader getNCharacterStream(int columnIndex); Reader getNCharacterStream(String columnLabel); void updateNCharacterStream(
int columnIndex, Reader x, long length); void updateNCharacterStream(
String columnLabel, Reader reader, long length); void updateAsciiStream(
int columnIndex, InputStream x, long length); void updateBinaryStream(
int columnIndex, InputStream x, long length); void updateCharacterStream(
int columnIndex, Reader x, long length); void updateAsciiStream(
String columnLabel, InputStream x, long length); void updateBinaryStream(
String columnLabel, InputStream x, long length); void updateCharacterStream(
String columnLabel, Reader reader, long length); void updateBlob(
int columnIndex,
InputStream inputStream,
long length); void updateBlob(
String columnLabel,
InputStream inputStream,
long length); void updateClob(
int columnIndex, Reader reader, long length); void updateClob(
String columnLabel, Reader reader, long length); void updateNClob(
int columnIndex, Reader reader, long length); void updateNClob(
String columnLabel, Reader reader, long length); void updateNCharacterStream(
int columnIndex, Reader x); void updateNCharacterStream(
String columnLabel, Reader reader); void updateAsciiStream(
int columnIndex, InputStream x); void updateBinaryStream(
int columnIndex, InputStream x); void updateCharacterStream(
int columnIndex, Reader x); void updateAsciiStream(
String columnLabel, InputStream x); void updateBinaryStream(
String columnLabel, InputStream x); void updateCharacterStream(
String columnLabel, Reader reader); void updateBlob(
int columnIndex, InputStream inputStream); void updateBlob(
String columnLabel, InputStream inputStream); void updateClob(int columnIndex, Reader reader); void updateClob(
String columnLabel, Reader reader); void updateNClob(
int columnIndex, Reader reader); void updateNClob(
String columnLabel, Reader reader); T getObject(int columnIndex, Class<T> type); T getObject(
String columnLabel, Class<T> type); T unwrap(Class<T> iface); boolean isWrapperFor(Class<?> iface); } | @Test public void testGetRow() throws SQLException { Properties properties = new Properties(); properties.setProperty("timeZone", "GMT"); final TestDriver driver = new TestDriver(); try (Connection connection = driver.connect("jdbc:test", properties); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM TABLE")) { assertEquals(0, resultSet.getRow()); assertTrue(resultSet.next()); assertEquals(1, resultSet.getRow()); assertFalse(resultSet.next()); assertEquals(0, resultSet.getRow()); } } |
DateTimeUtils { public static int digitCount(int v) { for (int n = 1;; n++) { v /= 10; if (v == 0) { return n; } } } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testEasyLog10() { assertEquals(1, digitCount(0)); assertEquals(1, digitCount(1)); assertEquals(1, digitCount(9)); assertEquals(2, digitCount(10)); assertEquals(2, digitCount(11)); assertEquals(2, digitCount(99)); assertEquals(3, digitCount(100)); } |
DropwizardGauge implements Gauge<T> { @Override public T getValue() { return gauge.getValue(); } DropwizardGauge(org.apache.calcite.avatica.metrics.Gauge<T> gauge); @Override T getValue(); } | @Test public void test() { SimpleGauge gauge = new SimpleGauge(); DropwizardGauge<Long> dwGauge = new DropwizardGauge<>(gauge); assertEquals(gauge.getValue(), dwGauge.getValue()); gauge.setValue(1000L); assertEquals(gauge.getValue(), dwGauge.getValue()); } |
DropwizardMetricsSystemFactory implements MetricsSystemFactory { @Override public DropwizardMetricsSystem create(MetricsSystemConfiguration<?> config) { if (config instanceof DropwizardMetricsSystemConfiguration) { DropwizardMetricsSystemConfiguration typedConfig = (DropwizardMetricsSystemConfiguration) config; return new DropwizardMetricsSystem(typedConfig.get()); } throw new IllegalStateException("Expected instance of " + DropwizardMetricsSystemConfiguration.class.getName() + " but got " + (null == config ? "null" : config.getClass().getName())); } @Override DropwizardMetricsSystem create(MetricsSystemConfiguration<?> config); } | @Test(expected = IllegalStateException.class) public void testNullConfigurationFails() { factory.create(null); }
@Test(expected = IllegalStateException.class) public void testUnhandledConfigurationType() { factory.create(NoopMetricsSystemConfiguration.getInstance()); }
@Test public void testHandledConfigurationType() { DropwizardMetricsSystem metrics = factory.create(new DropwizardMetricsSystemConfiguration(new MetricRegistry())); assertNotNull("Expected DropwizardMetricsSystem to be non-null", metrics); } |
DropwizardMeter implements org.apache.calcite.avatica.metrics.Meter { @Override public void mark() { this.meter.mark(); } DropwizardMeter(Meter meter); @Override void mark(); @Override void mark(long count); } | @Test public void test() { DropwizardMeter dwMeter = new DropwizardMeter(this.meter); dwMeter.mark(); dwMeter.mark(10L); dwMeter.mark(); dwMeter.mark(); Mockito.verify(meter, Mockito.times(3)).mark(); Mockito.verify(meter).mark(10L); } |
DropwizardTimer implements org.apache.calcite.avatica.metrics.Timer { @Override public DropwizardContext start() { return new DropwizardContext(timer.time()); } DropwizardTimer(Timer timer); @Override DropwizardContext start(); } | @Test public void test() { DropwizardTimer dwTimer = new DropwizardTimer(timer); Mockito.when(timer.time()).thenReturn(context); DropwizardContext dwContext = dwTimer.start(); dwContext.close(); Mockito.verify(timer).time(); Mockito.verify(context).stop(); } |
DropwizardMetricsSystem implements MetricsSystem { @Override public <T> void register(String name, Gauge<T> gauge) { registry.register(name, new DropwizardGauge<T>(gauge)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testGauge() { final long gaugeValue = 42L; final String name = "gauge"; metrics.register(name, new Gauge<Long>() { @Override public Long getValue() { return gaugeValue; } }); verify(mockRegistry, times(1)).register(eq(name), any(com.codahale.metrics.Gauge.class)); } |
DropwizardMetricsSystem implements MetricsSystem { @Override public Meter getMeter(String name) { return new DropwizardMeter(registry.meter(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testMeter() { final String name = "meter"; final com.codahale.metrics.Meter mockMeter = mock(com.codahale.metrics.Meter.class); when(mockRegistry.meter(name)).thenReturn(mockMeter); Meter meter = metrics.getMeter(name); final long count = 5; meter.mark(count); verify(mockMeter, times(1)).mark(count); meter.mark(); verify(mockMeter, times(1)).mark(); } |
DropwizardMetricsSystem implements MetricsSystem { @Override public Histogram getHistogram(String name) { return new DropwizardHistogram(registry.histogram(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testHistogram() { final String name = "histogram"; final com.codahale.metrics.Histogram mockHistogram = mock(com.codahale.metrics.Histogram.class); when(mockRegistry.histogram(name)).thenReturn(mockHistogram); Histogram histogram = metrics.getHistogram(name); long[] long_values = new long[] {1L, 5L, 15L, 30L, 60L}; for (long value : long_values) { histogram.update(value); } for (long value : long_values) { verify(mockHistogram).update(value); } int[] int_values = new int[] {2, 6, 16, 31, 61}; for (int value : int_values) { histogram.update(value); } for (int value : int_values) { verify(mockHistogram).update(value); } } |
DropwizardMetricsSystem implements MetricsSystem { @Override public Counter getCounter(String name) { return new DropwizardCounter(registry.counter(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testCounter() { final String name = "counter"; final com.codahale.metrics.Counter mockCounter = mock(com.codahale.metrics.Counter.class); when(mockRegistry.counter(name)).thenReturn(mockCounter); Counter counter = metrics.getCounter(name); long[] updates = new long[] {1L, 5L, -2L, 4L, -8L, 0}; for (long update : updates) { if (update < 0) { counter.decrement(Math.abs(update)); } else { counter.increment(update); } } for (long update : updates) { if (update < 0) { verify(mockCounter).dec(Math.abs(update)); } else { verify(mockCounter).inc(update); } } int numSingleUpdates = 3; for (int i = 0; i < numSingleUpdates; i++) { counter.increment(); counter.decrement(); } verify(mockCounter, times(numSingleUpdates)).inc(); verify(mockCounter, times(numSingleUpdates)).dec(); } |
DateTimeUtils { public static long floorDiv(long x, long y) { long r = x / y; if ((x ^ y) < 0 && (r * y != x)) { r--; } return r; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testFloorDiv() { assertThat(floorDiv(13, 3), equalTo(4L)); assertThat(floorDiv(12, 3), equalTo(4L)); assertThat(floorDiv(11, 3), equalTo(3L)); assertThat(floorDiv(-13, 3), equalTo(-5L)); assertThat(floorDiv(-12, 3), equalTo(-4L)); assertThat(floorDiv(-11, 3), equalTo(-4L)); assertThat(floorDiv(0, 3), equalTo(0L)); assertThat(floorDiv(1, 3), equalTo(0L)); assertThat(floorDiv(-1, 3), is(-1L)); } |
DropwizardMetricsSystem implements MetricsSystem { @Override public Timer getTimer(String name) { return new DropwizardTimer(registry.timer(name)); } DropwizardMetricsSystem(MetricRegistry registry); @Override Timer getTimer(String name); @Override Histogram getHistogram(String name); @Override Meter getMeter(String name); @Override Counter getCounter(String name); @Override void register(String name, Gauge<T> gauge); } | @Test public void testTimer() { final String name = "timer"; final com.codahale.metrics.Timer mockTimer = mock(com.codahale.metrics.Timer.class); final com.codahale.metrics.Timer.Context mockContext = mock(com.codahale.metrics.Timer.Context.class); when(mockRegistry.timer(name)).thenReturn(mockTimer); when(mockTimer.time()).thenReturn(mockContext); Timer timer = metrics.getTimer(name); Context context = timer.start(); context.close(); verify(mockTimer).time(); verify(mockContext).stop(); } |
DropwizardHistogram implements org.apache.calcite.avatica.metrics.Histogram { @Override public void update(int value) { histogram.update(value); } DropwizardHistogram(Histogram histogram); @Override void update(int value); @Override void update(long value); } | @Test public void test() { DropwizardHistogram dwHistogram = new DropwizardHistogram(histogram); dwHistogram.update(10); dwHistogram.update(100L); Mockito.verify(histogram).update(10); Mockito.verify(histogram).update(100L); } |
JdbcMeta implements ProtobufMeta { RuntimeException propagate(Throwable e) { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else if (e instanceof Error) { throw (Error) e; } else { throw new RuntimeException(e); } } JdbcMeta(String url); JdbcMeta(final String url, final String user, final String password); JdbcMeta(String url, Properties info); JdbcMeta(String url, Properties info, MetricsSystem metrics); Map<DatabaseProperty, Object> getDatabaseProperties(ConnectionHandle ch); MetaResultSet getTables(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat tableNamePattern, List<String> typeList); MetaResultSet getColumns(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat tableNamePattern, Pat columnNamePattern); MetaResultSet getSchemas(ConnectionHandle ch, String catalog, Pat schemaPattern); MetaResultSet getCatalogs(ConnectionHandle ch); MetaResultSet getTableTypes(ConnectionHandle ch); MetaResultSet getProcedures(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat procedureNamePattern); MetaResultSet getProcedureColumns(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat procedureNamePattern, Pat columnNamePattern); MetaResultSet getColumnPrivileges(ConnectionHandle ch, String catalog, String schema,
String table, Pat columnNamePattern); MetaResultSet getTablePrivileges(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat tableNamePattern); MetaResultSet getBestRowIdentifier(ConnectionHandle ch, String catalog, String schema,
String table, int scope, boolean nullable); MetaResultSet getVersionColumns(ConnectionHandle ch, String catalog, String schema,
String table); MetaResultSet getPrimaryKeys(ConnectionHandle ch, String catalog, String schema,
String table); MetaResultSet getImportedKeys(ConnectionHandle ch, String catalog, String schema,
String table); MetaResultSet getExportedKeys(ConnectionHandle ch, String catalog, String schema,
String table); MetaResultSet getCrossReference(ConnectionHandle ch, String parentCatalog,
String parentSchema, String parentTable, String foreignCatalog,
String foreignSchema, String foreignTable); MetaResultSet getTypeInfo(ConnectionHandle ch); MetaResultSet getIndexInfo(ConnectionHandle ch, String catalog, String schema,
String table, boolean unique, boolean approximate); MetaResultSet getUDTs(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat typeNamePattern, int[] types); MetaResultSet getSuperTypes(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat typeNamePattern); MetaResultSet getSuperTables(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat tableNamePattern); MetaResultSet getAttributes(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat typeNamePattern, Pat attributeNamePattern); MetaResultSet getClientInfoProperties(ConnectionHandle ch); MetaResultSet getFunctions(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat functionNamePattern); MetaResultSet getFunctionColumns(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat functionNamePattern, Pat columnNamePattern); MetaResultSet getPseudoColumns(ConnectionHandle ch, String catalog, Pat schemaPattern,
Pat tableNamePattern, Pat columnNamePattern); Iterable<Object> createIterable(StatementHandle handle, QueryState state,
Signature signature, List<TypedValue> parameterValues, Frame firstFrame); StatementHandle createStatement(ConnectionHandle ch); @Override void closeStatement(StatementHandle h); @Override void openConnection(ConnectionHandle ch,
Map<String, String> info); @Override void closeConnection(ConnectionHandle ch); @Override ConnectionProperties connectionSync(ConnectionHandle ch,
ConnectionProperties connProps); StatementHandle prepare(ConnectionHandle ch, String sql,
long maxRowCount); @SuppressWarnings("deprecation") ExecuteResult prepareAndExecute(StatementHandle h, String sql,
long maxRowCount, PrepareCallback callback); ExecuteResult prepareAndExecute(StatementHandle h, String sql, long maxRowCount,
int maxRowsInFirstFrame, PrepareCallback callback); boolean syncResults(StatementHandle sh, QueryState state, long offset); Frame fetch(StatementHandle h, long offset, int fetchMaxRowCount); @SuppressWarnings("deprecation") @Override ExecuteResult execute(StatementHandle h, List<TypedValue> parameterValues,
long maxRowCount); @Override ExecuteResult execute(StatementHandle h,
List<TypedValue> parameterValues, int maxRowsInFirstFrame); @Override void commit(ConnectionHandle ch); @Override void rollback(ConnectionHandle ch); @Override ExecuteBatchResult prepareAndExecuteBatch(StatementHandle h,
List<String> sqlCommands); @Override ExecuteBatchResult executeBatch(StatementHandle h,
List<List<TypedValue>> updateBatches); @Override ExecuteBatchResult executeBatchProtobuf(StatementHandle h,
List<Requests.UpdateBatch> updateBatches); static final int UNLIMITED_COUNT; } | @Test public void testExceptionPropagation() throws SQLException { JdbcMeta meta = new JdbcMeta("url"); final Throwable e = new Exception(); final RuntimeException rte; try { meta.propagate(e); fail("Expected an exception to be thrown"); } catch (RuntimeException caughtException) { rte = caughtException; assertThat(rte.getCause(), is(e)); } } |
HandlerFactory { public AvaticaHandler getHandler(Service service, Driver.Serialization serialization) { return getHandler(service, serialization, NoopMetricsSystemConfiguration.getInstance()); } AvaticaHandler getHandler(Service service, Driver.Serialization serialization); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
AvaticaServerConfiguration serverConfig); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
MetricsSystemConfiguration<?> metricsConfig); AvaticaHandler getHandler(Service service, Driver.Serialization serialization,
MetricsSystemConfiguration<?> metricsConfig, AvaticaServerConfiguration serverConfig); } | @Test public void testJson() { Handler handler = factory.getHandler(service, Serialization.JSON); assertTrue("Expected an implementation of the AvaticaHandler, " + "but got " + handler.getClass(), handler instanceof AvaticaJsonHandler); }
@Test public void testProtobuf() { Handler handler = factory.getHandler(service, Serialization.PROTOBUF); assertTrue("Expected an implementation of the AvaticaProtobufHandler, " + "but got " + handler.getClass(), handler instanceof AvaticaProtobufHandler); } |
AvaticaSpnegoAuthenticator extends
org.eclipse.jetty.security.authentication.SpnegoAuthenticator { Authentication sendChallengeIfNecessary(Authentication computedAuth, ServletRequest request, ServletResponse response) throws IOException { if (computedAuth == Authentication.UNAUTHENTICATED) { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse res = (HttpServletResponse) response; String header = req.getHeader(HttpHeader.AUTHORIZATION.asString()); if (header != null && !header.startsWith(HttpHeader.NEGOTIATE.asString())) { LOG.debug("Client sent Authorization header that was not for Negotiate," + " sending challenge anyways."); if (DeferredAuthentication.isDeferred(res)) { return Authentication.UNAUTHENTICATED; } res.setHeader(HttpHeader.WWW_AUTHENTICATE.asString(), HttpHeader.NEGOTIATE.asString()); res.sendError(HttpServletResponse.SC_UNAUTHORIZED); return Authentication.SEND_CONTINUE; } } else if (computedAuth == Authentication.SEND_CONTINUE) { HttpServletRequest req = (HttpServletRequest) request; AvaticaUtils.skipFully(req.getInputStream()); } return computedAuth; } @Override Authentication validateRequest(ServletRequest request,
ServletResponse response, boolean mandatory); } | @Test public void testAuthenticatedDoesNothingExtra() throws IOException { List<Authentication> authsNotRequiringUpdate = Arrays.asList(Authentication.NOT_CHECKED, Authentication.SEND_FAILURE, Authentication.SEND_SUCCESS); for (Authentication auth : authsNotRequiringUpdate) { assertEquals(auth, authenticator.sendChallengeIfNecessary(auth, request, response)); verifyZeroInteractions(request); verifyZeroInteractions(response); } }
@Test public void testChallengeSendOnBasicAuthorization() throws IOException { when(request.getHeader("Authorization")).thenReturn("Basic asdf"); assertEquals(Authentication.SEND_CONTINUE, authenticator.sendChallengeIfNecessary(Authentication.UNAUTHENTICATED, request, response)); verify(response).setHeader(HttpHeader.WWW_AUTHENTICATE.toString(), HttpHeader.NEGOTIATE.asString()); verify(response).sendError(HttpServletResponse.SC_UNAUTHORIZED); }
@Test public void testConsumeClientBufferOnChallenge() throws IOException { when(requestInput.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1); assertEquals(Authentication.SEND_CONTINUE, authenticator.sendChallengeIfNecessary(Authentication.SEND_CONTINUE, request, response)); verify(request).getInputStream(); verify(requestInput).skip(anyLong()); verify(requestInput).read(any(byte[].class), anyInt(), anyInt()); } |
AbstractAvaticaHandler extends AbstractHandler implements MetricsAwareAvaticaHandler { public boolean isUserPermitted(AvaticaServerConfiguration serverConfig, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException { if (null != serverConfig) { if (AuthenticationType.SPNEGO == serverConfig.getAuthenticationType()) { String remoteUser = request.getRemoteUser(); if (null == remoteUser) { ServletInputStream input = request.getInputStream(); if (request.getContentLengthLong() < 0) { AvaticaUtils.skipFully(input); } response.setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); response.getOutputStream().write(UNAUTHORIZED_ERROR.serialize().toByteArray()); baseRequest.setHandled(true); return false; } } } return true; } boolean isUserPermitted(AvaticaServerConfiguration serverConfig, Request baseRequest,
HttpServletRequest request, HttpServletResponse response); } | @Test public void disallowUnauthenticatedUsers() throws Exception { ServletOutputStream os = mock(ServletOutputStream.class); ServletInputStream is = mock(ServletInputStream.class); when(is.read(any(byte[].class), anyInt(), anyInt())).thenReturn(-1); when(config.getAuthenticationType()).thenReturn(AuthenticationType.SPNEGO); when(request.getRemoteUser()).thenReturn(null); when(request.getInputStream()).thenReturn(is); when(response.getOutputStream()).thenReturn(os); assertFalse(handler.isUserPermitted(config, baseRequest, request, response)); assertTrue(baseRequest.isHandled()); verify(response).setStatus(HttpURLConnection.HTTP_UNAUTHORIZED); verify(os).write(argThat(new BaseMatcher<byte[]>() { @Override public void describeTo(Description description) { String desc = "A serialized ErrorMessage which contains 'User is not authenticated'"; description.appendText(desc); } @Override public boolean matches(Object item) { String msg = new String((byte[]) item, StandardCharsets.UTF_8); return msg.contains("User is not authenticated"); } @Override public void describeMismatch(Object item, Description mismatchDescription) { mismatchDescription.appendText("The message should contain 'User is not authenticated'"); } })); }
@Test public void allowAuthenticatedUsers() throws Exception { when(config.getAuthenticationType()).thenReturn(AuthenticationType.SPNEGO); when(request.getRemoteUser()).thenReturn("user1"); assertTrue(handler.isUserPermitted(config, baseRequest, request, response)); }
@Test public void allowAllUsersWhenNoAuthenticationIsNeeded() throws Exception { when(config.getAuthenticationType()).thenReturn(AuthenticationType.NONE); when(request.getRemoteUser()).thenReturn(null); assertTrue(handler.isUserPermitted(config, baseRequest, request, response)); when(request.getRemoteUser()).thenReturn("user1"); assertTrue(handler.isUserPermitted(config, baseRequest, request, response)); } |
DateTimeUtils { public static long floorMod(long x, long y) { return x - floorDiv(x, y) * y; } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testFloorMod() { assertThat(floorMod(13, 3), is(1L)); assertThat(floorMod(12, 3), is(0L)); assertThat(floorMod(11, 3), is(2L)); assertThat(floorMod(-13, 3), is(2L)); assertThat(floorMod(-12, 3), is(0L)); assertThat(floorMod(-11, 3), is(1L)); assertThat(floorMod(0, 3), is(0L)); assertThat(floorMod(1, 3), is(1L)); assertThat(floorMod(-1, 3), is(2L)); } |
DateTimeUtils { public static String unixDateToString(int date) { final StringBuilder buf = new StringBuilder(10); unixDateToString(buf, date); return buf.toString(); } private DateTimeUtils(); @Deprecated // to be removed before 2.0 static Calendar parseDateFormat(String s, String pattern,
TimeZone tz); static Calendar parseDateFormat(String s, DateFormat dateFormat,
TimeZone tz); @Deprecated // to be removed before 2.0 static PrecisionTime parsePrecisionDateTimeLiteral(
String s,
String pattern,
TimeZone tz); static PrecisionTime parsePrecisionDateTimeLiteral(String s,
DateFormat dateFormat, TimeZone tz, int maxPrecision); static TimeZone getTimeZone(Calendar cal); static void checkDateFormat(String pattern); static SimpleDateFormat newDateFormat(String format); static String unixTimestampToString(long timestamp); static String unixTimestampToString(long timestamp, int precision); static String unixTimeToString(int time); static String unixTimeToString(int time, int precision); static String unixDateToString(int date); static String intervalYearMonthToString(int v, TimeUnitRange range); static StringBuilder number(StringBuilder buf, int v, int n); static int digitCount(int v); static long powerX(long a, long b); static String intervalDayTimeToString(long v, TimeUnitRange range,
int scale); static int dateStringToUnixDate(String s); static int timeStringToUnixDate(String v); static int timeStringToUnixDate(String v, int start); static long timestampStringToUnixDate(String s); static long unixDateExtract(TimeUnitRange range, long date); static int unixTimestampExtract(TimeUnitRange range,
long timestamp); static int unixTimeExtract(TimeUnitRange range, int time); static long resetTime(long timestamp); static long resetDate(long timestamp); static long unixTimestampFloor(TimeUnitRange range, long timestamp); static long unixDateFloor(TimeUnitRange range, long date); static long unixTimestampCeil(TimeUnitRange range, long timestamp); static long unixDateCeil(TimeUnitRange range, long date); static int ymdToUnixDate(int year, int month, int day); static int ymdToJulian(int year, int month, int day); static long unixTimestamp(int year, int month, int day, int hour,
int minute, int second); static long addMonths(long timestamp, int m); static int addMonths(int date, int m); static int subtractMonths(int date0, int date1); static int subtractMonths(long t0, long t1); static long floorDiv(long x, long y); static long floorMod(long x, long y); static Calendar calendar(); static boolean isOffsetDateTime(Object o); static String offsetDateTimeValue(Object o); static final int EPOCH_JULIAN; static final String DATE_FORMAT_STRING; static final String TIME_FORMAT_STRING; static final String TIMESTAMP_FORMAT_STRING; @Deprecated // to be removed before 2.0
static final TimeZone GMT_ZONE; static final TimeZone UTC_ZONE; static final TimeZone DEFAULT_ZONE; static final long MILLIS_PER_SECOND; static final long MILLIS_PER_MINUTE; static final long MILLIS_PER_HOUR; static final long MILLIS_PER_DAY; static final long SECONDS_PER_DAY; static final Calendar ZERO_CALENDAR; } | @Test public void testUnixDateToString() { assertEquals("2000-01-01", unixDateToString(10957)); assertEquals("1970-01-01", unixDateToString(0)); assertEquals("1970-01-02", unixDateToString(1)); assertEquals("1971-01-01", unixDateToString(365)); assertEquals("1972-01-01", unixDateToString(730)); assertEquals("1972-02-28", unixDateToString(788)); assertEquals("1972-02-29", unixDateToString(789)); assertEquals("1972-03-01", unixDateToString(790)); assertEquals("1969-01-01", unixDateToString(-365)); assertEquals("2000-01-01", unixDateToString(10957)); assertEquals("2000-02-28", unixDateToString(11015)); assertEquals("2000-02-29", unixDateToString(11016)); assertEquals("2000-03-01", unixDateToString(11017)); assertEquals("1900-01-01", unixDateToString(-25567)); assertEquals("1900-02-28", unixDateToString(-25509)); assertEquals("1900-03-01", unixDateToString(-25508)); assertEquals("1945-02-24", unixDateToString(-9077)); } |
UTF8Util { public static final long skipUntilEOF(InputStream in) throws IOException { return internalSkip(in, Long.MAX_VALUE).charsSkipped(); } private UTF8Util(); static final long skipUntilEOF(InputStream in); static final long skipFully(InputStream in, long charsToSkip); } | @Test public void testSkipUntilEOFOnZeroLengthStream() throws IOException { TestCase.assertEquals(0, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(0))); }
@Test public void testSkipUntilEOFOnShortStreamASCII() throws IOException { TestCase.assertEquals(5, UTF8Util.skipUntilEOF(new LoopingAlphabetStream(5))); }
@Test public void testSkipUntilEOFOnShortStreamCJK() throws IOException { final int charLength = 5; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new CharStreamHeaderGenerator()); in.skip(HEADER_LENGTH); TestCase.assertEquals(charLength, UTF8Util.skipUntilEOF(in)); }
@Test public void testSkipUntilEOFOnLongStreamASCII() throws IOException { TestCase.assertEquals(127019, UTF8Util.skipUntilEOF( new LoopingAlphabetStream(127019))); }
@Test public void testSkipUntilEOFOnLongStreamCJK() throws IOException { final int charLength = 127019; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new ClobStreamHeaderGenerator(true)); in.skip(HEADER_LENGTH); TestCase.assertEquals(charLength, UTF8Util.skipUntilEOF(in)); } |
ByteSlice implements Externalizable,Comparable<ByteSlice>,Cloneable { public byte[] getByteCopy() { if(length<=0) return EMPTY_BYTE_ARRAY; return Bytes.slice(buffer, offset, length); } ByteSlice(); ByteSlice(ByteSlice other); protected ByteSlice(byte[] buffer, int offset, int length); static ByteSlice cachedEmpty(); static ByteSlice empty(); static ByteSlice wrap(ByteBuffer buffer); static ByteSlice cachedWrap(byte[] data); static ByteSlice cachedWrap(byte[] data, int offset,int length); static ByteSlice wrap(byte[] data, int offset, int length); static ByteSlice wrap(byte[] rowKey); int offset(); int length(); byte[] getByteCopy(); ByteBuffer asBuffer(); void get(byte[] destination, int destOffset); void get(byte[] destination, int destOffset,int destLength); void set(byte[] bytes); @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") void set(byte[] buffer, int offset, int length); void updateSlice(ByteSlice slice, boolean reverse); void set(ByteSlice rowSlice, boolean reverse); byte[] data(boolean reverse); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") byte[] array(); void reset(); @Override boolean equals(Object o); @Override String toString(); boolean equals(ByteSlice currentData, int equalsLength); boolean equals(byte[] data, int offset, int length); @Override int compareTo(ByteSlice o); int compareTo(byte[] bytes,int offset, int length); @Override int hashCode(); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); void reverse(); int find(byte toFind, int startOffset); @Override @SuppressWarnings("CloneDoesntCallSuperClone") //intentionally doesn't call it @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL",justification = "Intentional") ByteSlice clone(); void set(ByteSlice newData); String toHexString(); } | @Test public void getByteCopy() { byte[] bytes = new byte[]{0, 1, 2, 3, 4, 5}; ByteSlice byteSlice = ByteSlice.wrap(bytes); byte[] copy = byteSlice.getByteCopy(); assertNotSame("should not be the same", bytes, copy); assertArrayEquals("but should be equal", bytes, copy); } |
ByteSlice implements Externalizable,Comparable<ByteSlice>,Cloneable { public String toHexString() { if(this.length<=0) return ""; return Bytes.toHex(buffer,offset,length); } ByteSlice(); ByteSlice(ByteSlice other); protected ByteSlice(byte[] buffer, int offset, int length); static ByteSlice cachedEmpty(); static ByteSlice empty(); static ByteSlice wrap(ByteBuffer buffer); static ByteSlice cachedWrap(byte[] data); static ByteSlice cachedWrap(byte[] data, int offset,int length); static ByteSlice wrap(byte[] data, int offset, int length); static ByteSlice wrap(byte[] rowKey); int offset(); int length(); byte[] getByteCopy(); ByteBuffer asBuffer(); void get(byte[] destination, int destOffset); void get(byte[] destination, int destOffset,int destLength); void set(byte[] bytes); @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") void set(byte[] buffer, int offset, int length); void updateSlice(ByteSlice slice, boolean reverse); void set(ByteSlice rowSlice, boolean reverse); byte[] data(boolean reverse); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") byte[] array(); void reset(); @Override boolean equals(Object o); @Override String toString(); boolean equals(ByteSlice currentData, int equalsLength); boolean equals(byte[] data, int offset, int length); @Override int compareTo(ByteSlice o); int compareTo(byte[] bytes,int offset, int length); @Override int hashCode(); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); void reverse(); int find(byte toFind, int startOffset); @Override @SuppressWarnings("CloneDoesntCallSuperClone") //intentionally doesn't call it @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL",justification = "Intentional") ByteSlice clone(); void set(ByteSlice newData); String toHexString(); } | @Test public void toHexString() { ByteSlice byteSlice = new ByteSlice(); byteSlice.set(new byte[]{18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}); assertEquals("1211100F0E0D0C0B0A09080706050403020100", byteSlice.toHexString()); } |
ByteSlice implements Externalizable,Comparable<ByteSlice>,Cloneable { public int find(byte toFind, int startOffset){ if(startOffset<0 || startOffset>=length) return -1; int finalOffset = offset+length; int position = 0; for(int i=offset+startOffset;i<finalOffset;i++){ if(buffer[i]==toFind) { return position; } position++; } return -1; } ByteSlice(); ByteSlice(ByteSlice other); protected ByteSlice(byte[] buffer, int offset, int length); static ByteSlice cachedEmpty(); static ByteSlice empty(); static ByteSlice wrap(ByteBuffer buffer); static ByteSlice cachedWrap(byte[] data); static ByteSlice cachedWrap(byte[] data, int offset,int length); static ByteSlice wrap(byte[] data, int offset, int length); static ByteSlice wrap(byte[] rowKey); int offset(); int length(); byte[] getByteCopy(); ByteBuffer asBuffer(); void get(byte[] destination, int destOffset); void get(byte[] destination, int destOffset,int destLength); void set(byte[] bytes); @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") void set(byte[] buffer, int offset, int length); void updateSlice(ByteSlice slice, boolean reverse); void set(ByteSlice rowSlice, boolean reverse); byte[] data(boolean reverse); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") byte[] array(); void reset(); @Override boolean equals(Object o); @Override String toString(); boolean equals(ByteSlice currentData, int equalsLength); boolean equals(byte[] data, int offset, int length); @Override int compareTo(ByteSlice o); int compareTo(byte[] bytes,int offset, int length); @Override int hashCode(); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); void reverse(); int find(byte toFind, int startOffset); @Override @SuppressWarnings("CloneDoesntCallSuperClone") //intentionally doesn't call it @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL",justification = "Intentional") ByteSlice clone(); void set(ByteSlice newData); String toHexString(); } | @Test public void find() { byte[] sourceBytes = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9}; ByteSlice byteSlice = ByteSlice.wrap(sourceBytes); assertEquals(0, byteSlice.find((byte) 1, 0)); assertEquals(1, byteSlice.find((byte) 2, 0)); assertEquals(2, byteSlice.find((byte) 3, 0)); sourceBytes = new byte[]{-1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, 120}; byteSlice = ByteSlice.wrap(sourceBytes, 4, 10); assertEquals(0, byteSlice.find((byte) 0, 0)); assertEquals(1, byteSlice.find((byte) 1, 0)); assertEquals(2, byteSlice.find((byte) 2, 0)); assertEquals(-1, byteSlice.find((byte) 120, 0)); } |
ByteSlice implements Externalizable,Comparable<ByteSlice>,Cloneable { public void reverse() { for(int i=offset;i<offset+length;i++){ buffer[i]^=0xff; } } ByteSlice(); ByteSlice(ByteSlice other); protected ByteSlice(byte[] buffer, int offset, int length); static ByteSlice cachedEmpty(); static ByteSlice empty(); static ByteSlice wrap(ByteBuffer buffer); static ByteSlice cachedWrap(byte[] data); static ByteSlice cachedWrap(byte[] data, int offset,int length); static ByteSlice wrap(byte[] data, int offset, int length); static ByteSlice wrap(byte[] rowKey); int offset(); int length(); byte[] getByteCopy(); ByteBuffer asBuffer(); void get(byte[] destination, int destOffset); void get(byte[] destination, int destOffset,int destLength); void set(byte[] bytes); @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") void set(byte[] buffer, int offset, int length); void updateSlice(ByteSlice slice, boolean reverse); void set(ByteSlice rowSlice, boolean reverse); byte[] data(boolean reverse); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") byte[] array(); void reset(); @Override boolean equals(Object o); @Override String toString(); boolean equals(ByteSlice currentData, int equalsLength); boolean equals(byte[] data, int offset, int length); @Override int compareTo(ByteSlice o); int compareTo(byte[] bytes,int offset, int length); @Override int hashCode(); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); void reverse(); int find(byte toFind, int startOffset); @Override @SuppressWarnings("CloneDoesntCallSuperClone") //intentionally doesn't call it @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL",justification = "Intentional") ByteSlice clone(); void set(ByteSlice newData); String toHexString(); } | @Test public void reverse() { byte[] bytes = new byte[]{0, 1, 2, 3}; ByteSlice byteSlice = ByteSlice.wrap(bytes); byteSlice.reverse(); assertSame(bytes, byteSlice.array()); assertArrayEquals(new byte[]{-1, -2, -3, -4}, byteSlice.array()); } |
ByteSlice implements Externalizable,Comparable<ByteSlice>,Cloneable { public static ByteSlice wrap(ByteBuffer buffer){ byte[] data = new byte[buffer.remaining()]; buffer.get(data); return new ByteSlice(data,0,data.length); } ByteSlice(); ByteSlice(ByteSlice other); protected ByteSlice(byte[] buffer, int offset, int length); static ByteSlice cachedEmpty(); static ByteSlice empty(); static ByteSlice wrap(ByteBuffer buffer); static ByteSlice cachedWrap(byte[] data); static ByteSlice cachedWrap(byte[] data, int offset,int length); static ByteSlice wrap(byte[] data, int offset, int length); static ByteSlice wrap(byte[] rowKey); int offset(); int length(); byte[] getByteCopy(); ByteBuffer asBuffer(); void get(byte[] destination, int destOffset); void get(byte[] destination, int destOffset,int destLength); void set(byte[] bytes); @SuppressFBWarnings(value = "EI_EXPOSE_REP2",justification = "Intentional") void set(byte[] buffer, int offset, int length); void updateSlice(ByteSlice slice, boolean reverse); void set(ByteSlice rowSlice, boolean reverse); byte[] data(boolean reverse); @SuppressFBWarnings(value = "EI_EXPOSE_REP",justification = "Intentional") byte[] array(); void reset(); @Override boolean equals(Object o); @Override String toString(); boolean equals(ByteSlice currentData, int equalsLength); boolean equals(byte[] data, int offset, int length); @Override int compareTo(ByteSlice o); int compareTo(byte[] bytes,int offset, int length); @Override int hashCode(); @Override void readExternal(ObjectInput in); @Override void writeExternal(ObjectOutput out); void reverse(); int find(byte toFind, int startOffset); @Override @SuppressWarnings("CloneDoesntCallSuperClone") //intentionally doesn't call it @SuppressFBWarnings(value = "CN_IDIOM_NO_SUPER_CALL",justification = "Intentional") ByteSlice clone(); void set(ByteSlice newData); String toHexString(); } | @Test public void byteSliceBufferTooSmall() { ByteSlice.wrap(new byte[]{0}, 0, 1); ByteSlice.wrap(new byte[]{0}, 1, 0); try { ByteSlice.wrap(new byte[] {0}, 1, 1); fail("Expected too small exception"); } catch (Throwable e) { assertTrue(e.getMessage().contains("is too short for")); } try { ByteSlice.wrap(new byte[0], 0, 1); fail("Expected too small exception"); } catch (Throwable e) { assertTrue(e.getMessage().contains("is too short for")); } try { ByteSlice.wrap(new byte[0], 1, 0); fail("Expected too small exception"); } catch (Throwable e) { assertTrue(e.getMessage().contains("is too short for")); } } |
IntArrays { public static int[] complementMap(int[] filterMap, int size) { HashSet<Integer> columnsToFilter = new HashSet<Integer>(filterMap.length); int numMissingFields = 0; for (int i=0; i<filterMap.length; i++) { if (filterMap[i] >= 0) numMissingFields++; columnsToFilter.add(filterMap[i]); } int mapSize = size - numMissingFields; assert mapSize >= 0 : "Cannot construct a complement with more missing fields than present!"; if (mapSize == 0) return new int[]{}; int[] finalData = new int[mapSize]; int index = 0; int filter = 0; while (index < mapSize) { if (! columnsToFilter.contains(filter)) { finalData[index++] = filter; } filter++; } return finalData; } private IntArrays(); static int[] complement(int[] map,int size); static int[] complementMap(int[] filterMap, int size); static int[] intersect(int[] map,int size); static int[] count(int size); static int[] negativeInitialize(int size); } | @Test public void testComplementMap() throws Exception { int[] expected = new int[] {0,3,4,5}; int[] input = new int[] {1,2}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap1() throws Exception { int[] expected = new int[] {3,4,5}; int[] input = new int[] {0,1,2}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap2() throws Exception { int[] expected = new int[] {0,1,2}; int[] input = new int[] {3,4,5}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap3() throws Exception { int[] expected = new int[] {}; int[] input = new int[] {0,1,2,3,4,5}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap4() throws Exception { int[] expected = new int[] {0,1,2,3,4,5}; int[] input = new int[] {}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap5() throws Exception { int[] expected = new int[] {1,2,3,4}; int[] input = new int[] {0}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap6() throws Exception { int[] expected = new int[] {0,1,2,3}; int[] input = new int[] {4}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap6a() throws Exception { int[] expected = new int[] {0,1,2,3,5}; int[] input = new int[] {4}; int size = 6; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap7() throws Exception { int[] expected = new int[] {1,2,3,4}; int[] input = new int[] {0}; int size = expected.length + input.length-1; try { IntArrays.complementMap(input,size); Assert.fail("Should have been an Assertion error - more missing fields than present."); } catch (AssertionError e) { } }
@Test public void testComplementMap8() throws Exception { int[] expected = new int[] {0,1,4,5}; int[] input = new int[] {2,3}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); }
@Test public void testComplementMap9() throws Exception { int[] expected = new int[] {0,1,2,5}; int[] input = new int[] {3,4}; int size = expected.length + input.length; int[] complement = IntArrays.complementMap(input,size); Assert.assertArrayEquals(printArrays(input,size,expected,complement),expected,complement); } |
UTF8Util { public static final long skipFully(InputStream in, long charsToSkip) throws EOFException, IOException { SkipCount skipped = internalSkip(in, charsToSkip); if (skipped.charsSkipped() != charsToSkip) { throw new EOFException("Reached end-of-stream prematurely at " + "character/byte position " + skipped.charsSkipped() + "/" + skipped.bytesSkipped() + ", trying to skip " + charsToSkip); } return skipped.bytesSkipped(); } private UTF8Util(); static final long skipUntilEOF(InputStream in); static final long skipFully(InputStream in, long charsToSkip); } | @Test public void testMissingThirdByteOfThree() throws IOException { byte[] data = {'a', (byte)0xef, (byte)0xb8}; InputStream is = new ByteArrayInputStream(data); try { UTF8Util.skipFully(is, 2); TestCase.fail("Reading invalid UTF-8 should fail"); } catch (UTFDataFormatException udfe) { } }
@Test public void testInvalidUTF8Encoding() throws IOException { byte[] data = {'a', 'b', 'c', (byte)0xf8, 'e', 'f'}; InputStream is = new ByteArrayInputStream(data); try { UTF8Util.skipFully(is, 6); TestCase.fail("Reading invalid UTF-8 should fail"); } catch (UTFDataFormatException udfe) { } }
@Test public void testSkippingInvalidEncodingWorks() throws IOException { byte[] data = {'a', (byte)0xef, (byte)0xb8, 'a', 'a'}; byte[] dataWithLength = {0x0, 0x5, 'a', (byte)0xef, (byte)0xb8, 'a', 'a'}; InputStream is = new ByteArrayInputStream(data); UTF8Util.skipFully(is, 3); DataInputStream dis = new DataInputStream( new ByteArrayInputStream(dataWithLength)); try { dis.readUTF(); TestCase.fail("UTF-8 expected to be invalid, read should fail"); } catch (UTFDataFormatException udfe) { } }
@Test public void testSkipFullyOnValidLongStreamCJK() throws IOException { final int charLength = 161019; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new CharStreamHeaderGenerator()); in.skip(HEADER_LENGTH); TestCase.assertEquals(charLength *3, UTF8Util.skipFully(in, charLength)); }
@Test public void testSkipFullyOnTooShortStreamCJK() throws IOException { final int charLength = 161019; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new ClobStreamHeaderGenerator(true)); in.skip(HEADER_LENGTH); try { UTF8Util.skipFully(in, charLength + 100); TestCase.fail("Should have failed because of too short stream."); } catch (EOFException eofe) { } }
@Test public void testSkipFullyOnInvalidStreamCJK() throws IOException { final int charLength = 10; InputStream in = new ReaderToUTF8Stream( new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new CharStreamHeaderGenerator()); in.skip(HEADER_LENGTH); in.skip(1L); try { UTF8Util.skipFully(in, charLength); TestCase.fail("Should have failed because of UTF error."); } catch (UTFDataFormatException udfe) { } }
@Test public void testMissingSecondByteOfTwo() throws IOException { byte[] data = {'a', (byte)0xdf}; InputStream is = new ByteArrayInputStream(data); try { UTF8Util.skipFully(is, 2); TestCase.fail("Reading invalid UTF-8 should fail"); } catch (UTFDataFormatException udfe) { } }
@Test public void testMissingSecondByteOfThree() throws IOException { byte[] data = {'a', (byte)0xef}; InputStream is = new ByteArrayInputStream(data); try { UTF8Util.skipFully(is, 2); TestCase.fail("Reading invalid UTF-8 should fail"); } catch (UTFDataFormatException udfe) { } } |
SpliceDoNotRetryIOException extends DoNotRetryIOException { @Override public String getMessage() { LOG.trace("getMessage"); return super.getMessage(); } SpliceDoNotRetryIOException(); SpliceDoNotRetryIOException(String message, Throwable cause); SpliceDoNotRetryIOException(String message); @Override String getMessage(); } | @Test public void messageTrimmingTest() { Assert.assertEquals(msg1,exception.getMessage()); } |
OrcDataSourceUtils { public static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize) { List<DiskRange> ranges = new ArrayList<>(diskRanges); Collections.sort(ranges, new Comparator<DiskRange>() { @Override public int compare(DiskRange o1, DiskRange o2) { return Long.compare(o1.getOffset(), o2.getOffset()); } }); long maxReadSizeBytes = maxReadSize.toBytes(); long maxMergeDistanceBytes = maxMergeDistance.toBytes(); ImmutableList.Builder<DiskRange> result = ImmutableList.builder(); DiskRange last = ranges.get(0); for (int i = 1; i < ranges.size(); i++) { DiskRange current = ranges.get(i); DiskRange merged = last.span(current); if (merged.getLength() <= maxReadSizeBytes && last.getEnd() + maxMergeDistanceBytes >= current.getOffset()) { last = merged; } else { result.add(last); last = current; } } result.add(last); return result.build(); } private OrcDataSourceUtils(); static List<DiskRange> mergeAdjacentDiskRanges(Collection<DiskRange> diskRanges, DataSize maxMergeDistance, DataSize maxReadSize); static Slice getDiskRangeSlice(DiskRange diskRange, Map<DiskRange, byte[]> buffers); } | @Test public void testMergeSingle() { List<DiskRange> diskRanges = mergeAdjacentDiskRanges( ImmutableList.of(new DiskRange(100, 100)), new DataSize(0, BYTE), new DataSize(0, BYTE)); assertEquals(diskRanges, ImmutableList.of(new DiskRange(100, 100))); }
@Test public void testMergeAdjacent() { List<DiskRange> diskRanges = mergeAdjacentDiskRanges( ImmutableList.of(new DiskRange(100, 100), new DiskRange(200, 100), new DiskRange(300, 100)), new DataSize(0, BYTE), new DataSize(1, GIGABYTE)); assertEquals(diskRanges, ImmutableList.of(new DiskRange(100, 300))); }
@Test public void testMergeGap() { List<DiskRange> consistent10ByteGap = ImmutableList.of(new DiskRange(100, 90), new DiskRange(200, 90), new DiskRange(300, 90)); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(0, BYTE), new DataSize(1, GIGABYTE)), consistent10ByteGap); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(9, BYTE), new DataSize(1, GIGABYTE)), consistent10ByteGap); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 290))); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(100, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 290))); List<DiskRange> middle10ByteGap = ImmutableList.of(new DiskRange(100, 80), new DiskRange(200, 90), new DiskRange(300, 80), new DiskRange(400, 90)); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(0, BYTE), new DataSize(1, GIGABYTE)), middle10ByteGap); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(9, BYTE), new DataSize(1, GIGABYTE)), middle10ByteGap); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(10, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 80), new DiskRange(200, 180), new DiskRange(400, 90))); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(100, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 390))); }
@Test public void testMergeMaxSize() { List<DiskRange> consistent10ByteGap = ImmutableList.of(new DiskRange(100, 90), new DiskRange(200, 90), new DiskRange(300, 90)); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(0, BYTE)), consistent10ByteGap); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(100, BYTE)), consistent10ByteGap); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(190, BYTE)), ImmutableList.of(new DiskRange(100, 190), new DiskRange(300, 90))); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(200, BYTE)), ImmutableList.of(new DiskRange(100, 190), new DiskRange(300, 90))); assertEquals(mergeAdjacentDiskRanges(consistent10ByteGap, new DataSize(10, BYTE), new DataSize(290, BYTE)), ImmutableList.of(new DiskRange(100, 290))); List<DiskRange> middle10ByteGap = ImmutableList.of(new DiskRange(100, 80), new DiskRange(200, 90), new DiskRange(300, 80), new DiskRange(400, 90)); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(0, BYTE), new DataSize(1, GIGABYTE)), middle10ByteGap); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(9, BYTE), new DataSize(1, GIGABYTE)), middle10ByteGap); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(10, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 80), new DiskRange(200, 180), new DiskRange(400, 90))); assertEquals(mergeAdjacentDiskRanges(middle10ByteGap, new DataSize(100, BYTE), new DataSize(1, GIGABYTE)), ImmutableList.of(new DiskRange(100, 390))); } |
OrcMetadataReader implements MetadataReader { @VisibleForTesting public static Slice getMinSlice(String minimum) { if (minimum == null) { return null; } int index = firstSurrogateCharacter(minimum); if (index == -1) { return Slices.utf8Slice(minimum); } return Slices.utf8Slice(minimum.substring(0, index)); } @Override PostScript readPostScript(byte[] data, int offset, int length); @Override Metadata readMetadata(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override Footer readFooter(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override StripeFooter readStripeFooter(HiveWriterVersion hiveWriterVersion, List<OrcType> types, InputStream inputStream); @Override List<RowGroupIndex> readRowIndexes(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override List<HiveBloomFilter> readBloomFilterIndexes(InputStream inputStream); @VisibleForTesting static Slice getMaxSlice(String maximum); @VisibleForTesting static Slice getMinSlice(String minimum); } | @Test public void testGetMinSlice() throws Exception { int startCodePoint = MIN_CODE_POINT; int endCodePoint = MAX_CODE_POINT; Slice minSlice = Slices.utf8Slice(""); for (int i = startCodePoint; i < endCodePoint; i++) { String value = new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMinSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMinSlice(value), minSlice); } } String prefix = "apple"; for (int i = startCodePoint; i < endCodePoint; i++) { String value = prefix + new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMinSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMinSlice(value), Slices.utf8Slice(prefix)); } } } |
OrcMetadataReader implements MetadataReader { @VisibleForTesting public static Slice getMaxSlice(String maximum) { if (maximum == null) { return null; } int index = firstSurrogateCharacter(maximum); if (index == -1) { return Slices.utf8Slice(maximum); } return concatSlices(Slices.utf8Slice(maximum.substring(0, index)), MAX_BYTE); } @Override PostScript readPostScript(byte[] data, int offset, int length); @Override Metadata readMetadata(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override Footer readFooter(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override StripeFooter readStripeFooter(HiveWriterVersion hiveWriterVersion, List<OrcType> types, InputStream inputStream); @Override List<RowGroupIndex> readRowIndexes(HiveWriterVersion hiveWriterVersion, InputStream inputStream); @Override List<HiveBloomFilter> readBloomFilterIndexes(InputStream inputStream); @VisibleForTesting static Slice getMaxSlice(String maximum); @VisibleForTesting static Slice getMinSlice(String minimum); } | @Test public void testGetMaxSlice() throws Exception { int startCodePoint = MIN_CODE_POINT; int endCodePoint = MAX_CODE_POINT; Slice maxByte = Slices.wrappedBuffer(new byte[] { (byte) 0xFF }); for (int i = startCodePoint; i < endCodePoint; i++) { String value = new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMaxSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMaxSlice(value), maxByte); } } String prefix = "apple"; Slice maxSlice = concatSlices(Slices.utf8Slice(prefix), maxByte); for (int i = startCodePoint; i < endCodePoint; i++) { String value = prefix + new String(new int[] { i }, 0, 1); if (firstSurrogateCharacter(value) == -1) { assertEquals(getMaxSlice(value), Slices.utf8Slice(value)); } else { assertEquals(getMaxSlice(value), maxSlice); } } } |
CachingOrcDataSource implements OrcDataSource { @VisibleForTesting void readCacheAt(long offset) throws IOException { DiskRange newCacheRange = regionFinder.getRangeFor(offset); cachePosition = newCacheRange.getOffset(); cacheLength = newCacheRange.getLength(); if (cache.length < cacheLength) { cache = new byte[cacheLength]; } dataSource.readFully(newCacheRange.getOffset(), cache, 0, cacheLength); } CachingOrcDataSource(OrcDataSource dataSource, RegionFinder regionFinder); @Override long getReadBytes(); @Override long getReadTimeNanos(); @Override long getSize(); @Override void readFully(long position, byte[] buffer); @Override void readFully(long position, byte[] buffer, int bufferOffset, int length); @Override Map<K, FixedLengthSliceInput> readFully(Map<K, DiskRange> diskRanges); @Override void close(); @Override String toString(); } | @Test public void testTinyStripesReadCacheAt() throws IOException { DataSize maxMergeDistance = new DataSize(1, Unit.MEGABYTE); DataSize maxReadSize = new DataSize(8, Unit.MEGABYTE); TestingOrcDataSource testingOrcDataSource = new TestingOrcDataSource(FakeOrcDataSource.INSTANCE); CachingOrcDataSource cachingOrcDataSource = new CachingOrcDataSource( testingOrcDataSource, createTinyStripesRangeFinder( ImmutableList.of(new StripeInformation(123, 3, 10, 10, 10), new StripeInformation(123, 33, 10, 10, 10), new StripeInformation(123, 63, 1048576 * 8 - 20, 10, 10)), maxMergeDistance, maxReadSize)); cachingOrcDataSource.readCacheAt(3); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(3, 60))); cachingOrcDataSource.readCacheAt(63); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(63, 8 * 1048576))); testingOrcDataSource = new TestingOrcDataSource(FakeOrcDataSource.INSTANCE); cachingOrcDataSource = new CachingOrcDataSource( testingOrcDataSource, createTinyStripesRangeFinder( ImmutableList.of(new StripeInformation(123, 3, 10, 10, 10), new StripeInformation(123, 33, 10, 10, 10), new StripeInformation(123, 63, 1048576 * 8 - 20, 10, 10)), maxMergeDistance, maxReadSize)); cachingOrcDataSource.readCacheAt(62); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(3, 60))); cachingOrcDataSource.readCacheAt(63); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(63, 8 * 1048576))); testingOrcDataSource = new TestingOrcDataSource(FakeOrcDataSource.INSTANCE); cachingOrcDataSource = new CachingOrcDataSource( testingOrcDataSource, createTinyStripesRangeFinder( ImmutableList.of(new StripeInformation(123, 3, 1, 0, 0), new StripeInformation(123, 4, 1048576, 1048576, 1048576 * 3), new StripeInformation(123, 4 + 1048576 * 5, 1048576, 1048576, 1048576)), maxMergeDistance, maxReadSize)); cachingOrcDataSource.readCacheAt(3); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(3, 1 + 1048576 * 5))); cachingOrcDataSource.readCacheAt(4 + 1048576 * 5); assertEquals(testingOrcDataSource.getLastReadRanges(), ImmutableList.of(new DiskRange(4 + 1048576 * 5, 3 * 1048576))); } |
DoubleColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendDoubles(size,Double.parseDouble(value)); } DoubleColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { DoubleColumnBlock doubleColumnBlock = new DoubleColumnBlock(null, DataTypes.DoubleType); doubleColumnBlock.setPartitionValue("1.23",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(1.23d,doubleColumnBlock.getTestObject(i)); } } |
IntegerColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendInts(size,Integer.parseInt(value)); } IntegerColumnBlock(DataType type); IntegerColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { IntegerColumnBlock integerColumnBlock = new IntegerColumnBlock(null, DataTypes.IntegerType); integerColumnBlock.setPartitionValue("45",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45,integerColumnBlock.getTestObject(i)); } } |
FloatColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendFloats(size,Float.parseFloat(value)); } FloatColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { FloatColumnBlock longColumnBlock = new FloatColumnBlock(null, DataTypes.FloatType); longColumnBlock.setPartitionValue("45.23",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45.23f,longColumnBlock.getTestObject(i)); } } |
ShortColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendShorts(size,Short.parseShort(value)); } ShortColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { ShortColumnBlock shortColumnBlock = new ShortColumnBlock(null, DataTypes.ShortType); shortColumnBlock.setPartitionValue("5",1000); short value = 5; for (int i = 0; i< 1000; i++) { Assert.assertEquals(value,shortColumnBlock.getTestObject(i)); } } |
LongColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { columnVector = ColumnVector.allocate(size, dataType, MemoryMode.ON_HEAP); columnVector.appendLongs(size,Long.parseLong(value)); } LongColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { LongColumnBlock longColumnBlock = new LongColumnBlock(null, DataTypes.LongType); longColumnBlock.setPartitionValue("45",1000); for (int i = 0; i< 1000; i++) { Assert.assertEquals(45l,longColumnBlock.getTestObject(i)); } } |
StringColumnBlock extends AbstractColumnBlock { @Override public void setPartitionValue(String value, int size) { try { columnVector = ColumnVector.allocate(size, DataTypes.IntegerType, MemoryMode.ON_HEAP); SliceDictionary dictionary = new SliceDictionary(new Slice[]{Slices.wrappedBuffer(value.getBytes("UTF-8"))}); columnVector.setDictionary(dictionary); columnVector.reserveDictionaryIds(size); columnVector.getDictionaryIds().appendInts(size,0); } catch (Exception e) { throw new RuntimeException(e); } } StringColumnBlock(ColumnVector columnVector, DataType type); @Override Object getObject(int i); @Override Object getTestObject(int i); @Override void setPartitionValue(String value, int size); } | @Test public void setPartitionValueTest() { StringColumnBlock stringColumnBlock = new StringColumnBlock(null, DataTypes.StringType); stringColumnBlock.setPartitionValue("foobar",1000); for (int i = 0; i< 1000; i++) { Assert.assertTrue("foobar".equals(stringColumnBlock.getTestObject(i))); } } |
MemstoreAwareObserver implements RegionCoprocessor, RegionObserver, Coprocessor { @Override public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker, CompactionRequest request) throws IOException { try { BlockingProbe.blockPreCompact(); if (!(request instanceof SpliceCompactionRequest)) { SpliceLogUtils.error(LOG,"Compaction request must be a SpliceCompactionRequest"); throw new DoNotRetryIOException(); } SpliceCompactionRequest scr = (SpliceCompactionRequest) request; scr.setMemstoreAware(memstoreAware); HRegion region = (HRegion) c.getEnvironment().getRegion(); scr.setRegion(region); return scanner == null ? DummyScanner.INSTANCE : scanner; } catch (Throwable t) { throw CoprocessorUtils.getIOException(t); } } @Override void start(CoprocessorEnvironment e); @Override void stop(CoprocessorEnvironment e); @Override InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store,
InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker,
CompactionRequest request); @Override void postCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile,
CompactionLifeCycleTracker tracker, CompactionRequest request); @Override InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner,
FlushLifeCycleTracker tracker); @Override void postFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile,
FlushLifeCycleTracker tracker); @Override Optional<RegionObserver> getRegionObserver(); @Override RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s); @Override void preClose(ObserverContext<RegionCoprocessorEnvironment> c, boolean abortRequested); @Override void postClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested); static String displayByteArray(byte[] key); static void main(String...args); MemstoreAware getMemstoreAware(); } | @Test public void preCompactTestScanner() throws Exception { MemstoreAwareObserver mao = new MemstoreAwareObserver(); InternalScanner in = new StubInternalScanner(); InternalScanner out = mao.preCompact(mockCtx, mockStore, in, userScanType, null, mockCompactionReq); assertEquals(in, out); }
@Test public void preCompactTestRequest() throws Exception { MemstoreAwareObserver mao = new MemstoreAwareObserver(); SpliceCompactionRequest compactionRequest = new StubCompactionRequest(); mao.preCompact(mockCtx, mockStore, mockScanner, userScanType, null, compactionRequest); MemstoreAware first = ((StubCompactionRequest)compactionRequest).guinea.get(); mao.preCompact(mockCtx, mockStore, mockScanner, userScanType, null, compactionRequest); MemstoreAware second = ((StubCompactionRequest)compactionRequest).guinea.get(); assertEquals(first, second); SpliceCompactionRequest newCompactionReq = new StubCompactionRequest(); mao.preCompact(mockCtx, mockStore, mockScanner, userScanType, null, newCompactionReq); MemstoreAware turd = ((StubCompactionRequest)newCompactionReq).guinea.get(); assertEquals(first, turd); } |
MemstoreAwareObserver implements RegionCoprocessor, RegionObserver, Coprocessor { @Override public RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException { if (scan.getAttribute(MRConstants.SPLICE_SCAN_MEMSTORE_ONLY) != null && Bytes.equals(scan.getAttribute(MRConstants.SPLICE_SCAN_MEMSTORE_ONLY), SIConstants.TRUE_BYTES)) { if (LOG.isDebugEnabled()) { SpliceLogUtils.debug(LOG, "preStoreScannerOpen in MR mode %s", c.getEnvironment().getRegion()); } HRegion region = (HRegion) c.getEnvironment().getRegion(); HStore store = region.getStore(SIConstants.DEFAULT_FAMILY_BYTES); return postScannerOpenAction(c, store, scan, null, s); } return s; } @Override void start(CoprocessorEnvironment e); @Override void stop(CoprocessorEnvironment e); @Override InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store,
InternalScanner scanner, ScanType scanType, CompactionLifeCycleTracker tracker,
CompactionRequest request); @Override void postCompact(ObserverContext<RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile,
CompactionLifeCycleTracker tracker, CompactionRequest request); @Override InternalScanner preFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, InternalScanner scanner,
FlushLifeCycleTracker tracker); @Override void postFlush(ObserverContext<RegionCoprocessorEnvironment> c, Store store, StoreFile resultFile,
FlushLifeCycleTracker tracker); @Override Optional<RegionObserver> getRegionObserver(); @Override RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s); @Override void preClose(ObserverContext<RegionCoprocessorEnvironment> c, boolean abortRequested); @Override void postClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested); static String displayByteArray(byte[] key); static void main(String...args); MemstoreAware getMemstoreAware(); } | @Test public void preStoreScannerOpen() throws Exception { MemstoreAwareObserver mao = new MemstoreAwareObserver(); byte[] startKey = createByteArray(13); byte[] endKey = createByteArray(24); ObserverContext<RegionCoprocessorEnvironment> fakeCtx = mockRegionEnv(startKey, endKey); RegionScanner preScanner = mock(RegionScanner.class); RegionScanner postScanner = mao.postScannerOpen(fakeCtx, mockScan(startKey, endKey), preScanner); assertNotNull(postScanner); assertNotEquals(preScanner, postScanner); postScanner.close(); }
@Test public void preStoreScannerOpenPartitionMiss() throws Exception { MemstoreAwareObserver mao = new MemstoreAwareObserver(); ObserverContext<RegionCoprocessorEnvironment> fakeCtx = mockRegionEnv(createByteArray(13), createByteArray(24)); RegionScanner preScanner = mock(RegionScanner.class); try { mao.postScannerOpen(fakeCtx, mockScan(createByteArray(14), createByteArray(25)), preScanner); fail("Expected DoNotRetryIOException"); } catch (IOException e) { assertTrue(e instanceof DoNotRetryIOException); } } |
SparkDataSet implements DataSet<V> { @Override public <Op extends SpliceOperation> DataSet< V> filter(SplicePredicateFunction<Op, V> f) { return new SparkDataSet<>(rdd.filter(new SparkSpliceFunctionWrapper<>(f)), f.getSparkName()); } SparkDataSet(JavaRDD<V> rdd); SparkDataSet(JavaRDD<V> rdd, String rddname); @Override int partitions(); @Override Pair<DataSet, Integer> materialize(); @Override Pair<DataSet, Integer> persistIt(); @Override DataSet getClone(); @Override void unpersistIt(); @Override List<V> collect(); @Override Future<List<V>> collectAsync(boolean isLast, OperationContext context, boolean pushScope, String scopeDetail); @Override DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f); @Override DataSet<V> shufflePartitions(); @Override DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f, boolean isLast); @Override DataSet<U> mapPartitions(SpliceFlatMapFunction<Op,Iterator<V>, U> f, boolean isLast, boolean pushScope, String scopeDetail); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet<V> distinct(OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet<V> distinct(String name, boolean isLast, OperationContext context, boolean pushScope, String scopeDetail); @Override PairDataSet<K,U> index(SplicePairFunction<Op,V,K,U> function); @Override PairDataSet<K, U> index(SplicePairFunction<Op, V, K, U> function, OperationContext context); @Override PairDataSet<K, U> index(SplicePairFunction<Op,V,K,U> function, boolean isLast); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override PairDataSet<K, U> index(SplicePairFunction<Op,V,K,U> function, boolean isLast, boolean pushScope, String scopeDetail); @Override DataSet<U> map(SpliceFunction<Op,V,U> function); DataSet<U> map(SpliceFunction<Op,V,U> function, boolean isLast); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet<U> map(SpliceFunction<Op,V,U> function, String name, boolean isLast, boolean pushScope, String scopeDetail); @Override Iterator<V> toLocalIterator(); @Override PairDataSet< K, V> keyBy(SpliceFunction<Op, V, K> f); PairDataSet< K, V> keyBy(SpliceFunction<Op, V, K> f, String name); @Override PairDataSet<K, V> keyBy(SpliceFunction<Op, V, K> function, OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override PairDataSet< K, V> keyBy(
SpliceFunction<Op, V, K> f, String name, boolean pushScope, String scopeDetail); @Override long count(); @Override DataSet<V> union(DataSet<V> dataSet, OperationContext operationContext); @Override DataSet<V> union(List<DataSet<V>> dataSetList, OperationContext operationContext); @Override DataSet<V> orderBy(OperationContext operationContext, int[] keyColumns, boolean[] descColumns, boolean[] nullsOrderedLow); @Override DataSet<V> parallelProbe(List<ScanSetBuilder<ExecRow>> scanSetBuilders, OperationContext<MultiProbeTableScanOperation> operationContext); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet< V> union(DataSet<V> dataSet, OperationContext operationContext, String name, boolean pushScope, String scopeDetail); @Override DataSet< V> filter(SplicePredicateFunction<Op, V> f); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet< V> filter(
SplicePredicateFunction<Op,V> f, boolean isLast, boolean pushScope, String scopeDetail); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet< V> intersect(DataSet<V> dataSet, OperationContext context); DataSet<V> windows(WindowContext windowContext, OperationContext context, boolean pushScope, String scopeDetail); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet< V> intersect(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet<V> subtract(DataSet<V> dataSet, OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) @Override DataSet< V> subtract(DataSet< V> dataSet, String name, OperationContext context, boolean pushScope, String scopeDetail); @Override boolean isEmpty(); @Override DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f); DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f, String name); DataSet< U> flatMap(SpliceFlatMapFunction<Op, V, U> f, boolean isLast); @Override void close(); @Override DataSet<V> take(TakeFunction<Op,V> takeFunction); @Override ExportDataSetWriterBuilder writeToDisk(); @Override KafkaDataSetWriterBuilder writeToKafka(); @Override void saveAsTextFile(String path); @Override PairDataSet<V, Long> zipWithIndex(OperationContext operationContext); @SuppressWarnings("unchecked") @Override ExportDataSetWriterBuilder<String> saveAsTextFile(OperationContext operationContext); @SuppressWarnings({ "rawtypes", "unchecked" }) @Override DataSet<V> coalesce(int numPartitions, boolean shuffle); @SuppressWarnings({ "rawtypes", "unchecked" }) @Override DataSet<V> coalesce(int numPartitions, boolean shuffle, boolean isLast, OperationContext context, boolean pushScope, String scopeDetail); @Override void persist(); @Override void setAttribute(String name, String value); @Override String getAttribute(String name); @SuppressWarnings({ "rawtypes", "unchecked" }) @Override DataSet<V> join(OperationContext context, DataSet<V> rightDataSet, JoinType joinType, boolean isBroadcast); @SuppressWarnings({ "rawtypes", "unchecked" }) @Override DataSet<V> crossJoin(OperationContext context, DataSet<V> rightDataSet, Broadcast type); @SuppressWarnings({ "unchecked", "rawtypes" }) static DataSet toSpliceLocatedRow(Dataset<Row> dataSet, OperationContext context); static DataSet toSpliceLocatedRow(JavaRDD<Row> rdd, OperationContext context); static StructType generateTableSchema(OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) DataSet<ExecRow> writeAvroFile(DataSetProcessor dsp,
int[] partitionBy,
String location,
String compression,
OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) NativeSparkDataSet getNativeSparkDataSet( OperationContext context); static String getAvroCompression(String compression); @Override DataSet<ExecRow> writeParquetFile(DataSetProcessor dsp,
int[] partitionBy,
String location,
String compression,
OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) DataSet<ExecRow> writeORCFile(int[] baseColumnMap, int[] partitionBy, String location, String compression,
OperationContext context); @SuppressWarnings({ "unchecked", "rawtypes" }) DataSet<ExecRow> writeTextFile(int[] partitionBy, String location, CsvOptions csvOptions,
OperationContext context); @Override @SuppressWarnings({ "unchecked", "rawtypes" }) void pin(ExecRow template, long conglomId); @Override DataSet<V> sampleWithoutReplacement(final double fraction); @Override BulkInsertDataSetWriterBuilder bulkInsertData(OperationContext operationContext); @Override BulkLoadIndexDataSetWriterBuilder bulkLoadIndex(OperationContext operationContext); @Override BulkDeleteDataSetWriterBuilder bulkDeleteData(OperationContext operationContext); @Override DataSetWriterBuilder deleteData(OperationContext operationContext); @Override InsertDataSetWriterBuilder insertData(OperationContext operationContext); @Override UpdateDataSetWriterBuilder updateData(OperationContext operationContext); @Override TableSamplerBuilder sample(OperationContext operationContext); @Override DataSet upgradeToSparkNativeDataSet(OperationContext operationContext); @Override DataSet applyNativeSparkAggregation(int[] groupByColumns, SpliceGenericAggregator[] aggregates, boolean isRollup, OperationContext operationContext); @Override boolean isNativeSpark(); List<String> buildNativeSparkExplain(ExplainNode.SparkExplainKind sparkExplainKind); public JavaRDD<V> rdd; } | @Test public void testFoobar() { List<Row> foo = new ArrayList(); for (int i = 0; i< 10; i++) { ValueRow row = new ValueRow(1); row.setColumn(1,new SQLInteger(i)); foo.add(row); } StructType schema = DataTypes.createStructType(new StructField[]{DataTypes.createStructField("col1", DataTypes.IntegerType, true)}); SpliceSpark.getSessionUnsafe().createDataFrame(foo,schema).write().format("orc").mode(SaveMode.Append) .orc("/Users/jleach/Documents/workspace/spliceengine/hbase_sql/target/external/orc_it"); Column filter = (new Column("col1")).gt(1l).and(new Column("col1").lt(1l)); SpliceSpark.getSessionUnsafe().read().schema(schema) .orc("/Users/jleach/Documents/workspace/spliceengine/hbase_sql/target/external/orc_it") .filter(filter).show(); } |
HdfsDirFile implements StorageFile { @Override public boolean deleteAll() { try { FileSystem fs = getFileSystem(); return fs.delete(new Path(path), true); } catch (IOException e) { LOG.error(String.format("An exception occurred while deleting the path '%s'.", path), e); return false; } } HdfsDirFile(String path); HdfsDirFile(String directoryName, String fileName); HdfsDirFile(HdfsDirFile directoryName, String fileName); FileSystem getFileSystem(); void setFileSystem(FileSystem fileSystem); @Override String[] list(); @Override boolean canWrite(); @Override boolean exists(); @Override boolean isDirectory(); @Override boolean delete(); @Override boolean deleteAll(); @Override String getPath(); @Override String getCanonicalPath(); @Override String getName(); @Override URL getURL(); @Override boolean createNewFile(); @Override boolean renameTo(StorageFile newName); @Override boolean mkdir(); @Override boolean mkdirs(); @Override long length(); @Override StorageFile getParentDir(); @Override boolean setReadOnly(); @Override OutputStream getOutputStream(); @Override OutputStream getOutputStream(boolean append); @Override InputStream getInputStream(); @Override int getExclusiveFileLock(); @Override void releaseExclusiveFileLock(); @Override StorageRandomAccessFile getRandomAccessFile(String mode); @Override void limitAccessToOwner(); } | @Test public void testDeleteAll() throws IOException { HdfsDirFile dir = createHdfsDirFile("myfolder3"); Assert.assertTrue("Directory was not created", dir.mkdir()); HdfsDirFile file1 = createHdfsDirFile(dir, "able3.txt"); Assert.assertTrue("File was not created", file1.createNewFile()); HdfsDirFile file2 = createHdfsDirFile(dir, "baker3.txt"); Assert.assertTrue("File was not created", file2.createNewFile()); HdfsDirFile file3 = createHdfsDirFile(dir, "charlie3.txt"); Assert.assertTrue("File was not created", file3.createNewFile()); Assert.assertTrue("File was not deleted", dir.deleteAll()); } |
HdfsDirFile implements StorageFile { @Override public boolean mkdirs() { try { FileSystem fs = getFileSystem(); return fs.mkdirs(new Path(path)); } catch (IOException e) { LOG.error(String.format("An exception occurred while making directories in the path '%s'.", path), e); return false; } } HdfsDirFile(String path); HdfsDirFile(String directoryName, String fileName); HdfsDirFile(HdfsDirFile directoryName, String fileName); FileSystem getFileSystem(); void setFileSystem(FileSystem fileSystem); @Override String[] list(); @Override boolean canWrite(); @Override boolean exists(); @Override boolean isDirectory(); @Override boolean delete(); @Override boolean deleteAll(); @Override String getPath(); @Override String getCanonicalPath(); @Override String getName(); @Override URL getURL(); @Override boolean createNewFile(); @Override boolean renameTo(StorageFile newName); @Override boolean mkdir(); @Override boolean mkdirs(); @Override long length(); @Override StorageFile getParentDir(); @Override boolean setReadOnly(); @Override OutputStream getOutputStream(); @Override OutputStream getOutputStream(boolean append); @Override InputStream getInputStream(); @Override int getExclusiveFileLock(); @Override void releaseExclusiveFileLock(); @Override StorageRandomAccessFile getRandomAccessFile(String mode); @Override void limitAccessToOwner(); } | @Test public void testMkdirs() throws IOException { HdfsDirFile dir = createHdfsDirFile("myfolder5/foo/bar"); Assert.assertTrue("Directories were not created", dir.mkdirs()); HdfsDirFile file1 = createHdfsDirFile(dir, "able5.txt"); Assert.assertTrue("File was not created", file1.createNewFile()); HdfsDirFile file2 = createHdfsDirFile(dir, "baker5.txt"); Assert.assertTrue("File was not created", file2.createNewFile()); HdfsDirFile file3 = createHdfsDirFile(dir, "charlie5.txt"); Assert.assertTrue("File was not created", file3.createNewFile()); String[] files = dir.list(); Assert.assertNotNull("The list method returned null", files); Assert.assertEquals("The list method returned the wrong number of files", 3, files.length); } |
StreamableRDD { public void submit() throws Exception { Exception error = null; try { final JavaRDD<String> streamed = rdd.mapPartitionsWithIndex(new ResultStreamer(context, uuid, host, port, rdd.getNumPartitions(), clientBatches, clientBatchSize), true); int numPartitions = streamed.getNumPartitions(); int partitionsBatchSize = parallelPartitions / 2; int partitionBatches = numPartitions / partitionsBatchSize; if (numPartitions % partitionsBatchSize > 0) partitionBatches++; if (LOG.isTraceEnabled()) LOG.trace("Num partitions " + numPartitions + " clientBatches " + partitionBatches); Properties properties = SerializationUtils.clone(SpliceSpark.getContextUnsafe().sc().getLocalProperties()); submitBatch(0, partitionsBatchSize, numPartitions, streamed, properties); if (partitionBatches > 1) submitBatch(1, partitionsBatchSize, numPartitions, streamed, properties); int received = 0; int submitted = 2; while (received < partitionBatches && error == null) { if (jobStatus != null && !jobStatus.isRunning()) { throw new CancellationException("The olap job is no longer running, cancelling Spark job"); } Future<Object> resultFuture = null; try { resultFuture = completionService.poll(10, TimeUnit.SECONDS); if (resultFuture == null) { continue; } Object result = resultFuture.get(); received++; if ("STOP".equals(result)) { if (LOG.isTraceEnabled()) LOG.trace("Stopping after receiving " + received + " clientBatches of " + partitionBatches); break; } if (submitted < partitionBatches) { submitBatch(submitted, partitionsBatchSize, numPartitions, streamed, properties); submitted++; } } catch (Exception e) { error = e; } } } finally { executor.shutdown(); } if (error != null) { LOG.error(error); throw error; } } StreamableRDD(JavaRDD<T> rdd, UUID uuid, String clientHost, int clientPort); StreamableRDD(JavaRDD<T> rdd, OperationContext<?> context, UUID uuid, String clientHost, int clientPort, int batches, int batchSize); StreamableRDD(JavaRDD<T> rdd, OperationContext<?> context, UUID uuid, String clientHost, int clientPort,
int batches, int batchSize, int parallelPartitions); void submit(); void setJobStatus(OlapStatus jobStatus); static final int DEFAULT_PARALLEL_PARTITIONS; } | @Test public void testBasicStream() throws Exception { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(tenRows, 10); StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); srdd.submit(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; while (it.hasNext()) { ExecRow execRow = it.next(); LOG.trace(execRow); count++; assertNotNull(execRow); assertTrue(execRow.getColumn(1).getInt() < 10); } assertEquals(10, count); }
@Test public void testOrder() throws Exception { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> shuffledRows = new ArrayList<>(tenRows); Collections.shuffle(shuffledRows); JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(shuffledRows, 10); JavaRDD<ExecRow> sorted = rdd.values().sortBy(new Function<ExecRow, Integer>() { @Override public Integer call(ExecRow execRow) throws Exception { return execRow.getColumn(1).getInt(); } }, true, 4); StreamableRDD srdd = new StreamableRDD(sorted, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); srdd.submit(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int last = -1; while (it.hasNext()) { ExecRow execRow = it.next(); LOG.trace(execRow); count++; assertNotNull(execRow); int value = execRow.getColumn(1).getInt(); assertTrue("Results not in order", value > last); last = value; } assertEquals(10, count); }
@Test public void testBlocking() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 10000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 6); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { LOG.error(e); throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; while (it.hasNext()) { ExecRow execRow = it.next(); count++; assertNotNull(execRow); } assertEquals(10000, count); }
@Test public void testBlockingLarge() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 12); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; while (it.hasNext()) { ExecRow execRow = it.next(); count++; assertNotNull(execRow); } assertEquals(100000, count); }
@Test public void testBlockingLargeOddPartitions() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; while (it.hasNext()) { ExecRow execRow = it.next(); count++; assertNotNull(execRow); } assertEquals(100000, count); }
@Test public void testSmallOffsetLimit() throws StandardException { int limit = 100; int offset = 2000; int total = 4000; StreamListener<ExecRow> sl = new StreamListener<>(limit, offset); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < total; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 1); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int first = offset; while (it.hasNext()) { ExecRow execRow = it.next(); assertNotNull(execRow); assertEquals(count+first, execRow.getColumn(1).getInt()); count++; } assertEquals(limit, count); }
@Test public void testSmallLimit() throws StandardException { int limit = 2000; int offset = 0; int total = 4000; int batches = 2; int batchSize = 512; StreamListener<ExecRow> sl = new StreamListener<>(limit, offset, batches, batchSize); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < total; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 1); final StreamableRDD srdd = new StreamableRDD(rdd.values(), null, sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort(), batches, batchSize); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int first = offset; while (it.hasNext()) { ExecRow execRow = it.next(); assertNotNull(execRow); assertEquals(count+first, execRow.getColumn(1).getInt()); count++; } assertEquals(limit, count); }
@Test public void testOffsetLimit() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(400, 30000); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int first = 30000; while (it.hasNext()) { ExecRow execRow = it.next(); assertNotNull(execRow); assertEquals(count+first, execRow.getColumn(1).getInt()); count++; } assertEquals(400, count); }
@Test public void testLimit() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(400, 0); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; while (it.hasNext()) { ExecRow execRow = it.next(); assertNotNull(execRow); assertEquals(count, execRow.getColumn(1).getInt()); count++; } assertEquals(400, count); }
@Test public void testOffset() throws StandardException { StreamListener<ExecRow> sl = new StreamListener<>(-1, 60000); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 13); final StreamableRDD srdd = new StreamableRDD(rdd.values(), sl.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); Iterator<ExecRow> it = sl.getIterator(); int count = 0; int first = 60000; while (it.hasNext()) { ExecRow execRow = it.next(); assertNotNull(execRow); assertEquals(count+first, execRow.getColumn(1).getInt()); count++; } assertEquals(100000-60000, count); }
@Test public void testConcurrentQueries() throws StandardException, ExecutionException, InterruptedException { final StreamListener<ExecRow> sl1 = new StreamListener<>(); final StreamListener<ExecRow> sl2 = new StreamListener<>(); final StreamListener<ExecRow> sl3 = new StreamListener<>(); HostAndPort hostAndPort = server.getHostAndPort(); server.register(sl1); server.register(sl2); server.register(sl3); List<Tuple2<ExecRow,ExecRow>> manyRows = new ArrayList<>(); for(int i = 0; i < 100000; ++i) { manyRows.add(new Tuple2<ExecRow, ExecRow>(getExecRow(i, 1), getExecRow(i, 2))); } JavaPairRDD<ExecRow, ExecRow> rdd = SpliceSpark.getContextUnsafe().parallelizePairs(manyRows, 12); final StreamableRDD srdd1 = new StreamableRDD(rdd.values(), sl1.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); final StreamableRDD srdd2 = new StreamableRDD(rdd.values().map(new Function<ExecRow,ExecRow>() { @Override public ExecRow call(ExecRow o) throws Exception { o.getColumn(1).setValue(0); return o; } }), sl2.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); final StreamableRDD srdd3 = new StreamableRDD(rdd.values(), sl3.getUuid(), hostAndPort.getHostText(), hostAndPort.getPort()); for (final StreamableRDD srdd : Arrays.asList(srdd1, srdd2, srdd3)) { new Thread() { @Override public void run() { try { srdd.submit(); } catch (Exception e) { throw new RuntimeException(e); } } }.start(); } ExecutorService executor = Executors.newFixedThreadPool(3); Future<List<ExecRow>> future1 = executor.submit(new Callable<List<ExecRow>>() { @Override public List<ExecRow> call() throws Exception { return IteratorUtils.toList(sl1.getIterator()); } }); Future<List<ExecRow>> future2 = executor.submit(new Callable<List<ExecRow>>() { @Override public List<ExecRow> call() throws Exception { return IteratorUtils.toList(sl2.getIterator()); } }); Future<List<ExecRow>> future3 = executor.submit(new Callable<List<ExecRow>>() { @Override public List<ExecRow> call() throws Exception { return IteratorUtils.toList(sl3.getIterator()); } }); Iterator<ExecRow> it1 = future1.get().iterator(); Iterator<ExecRow> it2 = future2.get().iterator(); Iterator<ExecRow> it3 = future3.get().iterator(); int count = 0; while (it1.hasNext()) { ExecRow r1 = it1.next(); ExecRow r2 = it2.next(); ExecRow r3 = it3.next(); count++; assertNotNull(r1); assertNotNull(r2); assertNotNull(r3); assertEquals(0, r2.getColumn(1).getInt()); assertEquals(r1.getColumn(1), r3.getColumn(1)); assertEquals(r1.getColumn(2), r2.getColumn(2)); } assertEquals(100000, count); } |
FormatableBitSet implements Formatable, Cloneable { public void grow(int n) { if (SanityManager.DEBUG) { SanityManager.ASSERT(invariantHolds(), "broken invariant"); } if (n < 0) { throw new IllegalArgumentException("Bit set cannot grow from "+ lengthAsBits+" to "+n+" bits"); } if (n <= lengthAsBits) { return; } int newNumBytes = FormatableBitSet.numBytesFromBits(n); if (newNumBytes > value.length) { byte[] newValue = new byte[newNumBytes]; int oldNumBytes = getLengthInBytes(); System.arraycopy(value, 0, newValue, 0, oldNumBytes); value = newValue; } bitsInLastByte = numBitsInLastByte(n); lengthAsBits = n; } FormatableBitSet(); FormatableBitSet(int numBits); FormatableBitSet(byte[] newValue); FormatableBitSet(FormatableBitSet original); Object clone(); boolean invariantHolds(); int getLengthInBytes(); int getLength(); int size(); byte[] getByteArray(); void grow(int n); void shrink(int n); boolean equals(Object other); int compare(FormatableBitSet other); int hashCode(); final boolean isSet(int position); final boolean get(int position); void set(int position); void clear(int position); void clear(); String toString(); static int maxBitsForSpace(int numBytes); int anySetBit(); int anySetBit(int beyondBit); void or(FormatableBitSet otherBit); void and(FormatableBitSet otherBit); void xor(FormatableBitSet otherBit); int getNumBitsSet(); void writeExternal(ObjectOutput out); void readExternal(ObjectInput in); int getTypeFormatId(); } | @Test public void testGrow() { bitset18.grow(25); assertEquals(25, bitset18.getLength()); assertEquals(4, bitset18.getLengthInBytes()); assertEquals(9, bitset18.getNumBitsSet()); assertTrue(bitset18.invariantHolds()); assertEquals(4, bitset18.getByteArray().length); }
@Test public void testGrowNeg() { try { bitset18.grow(-9); fail(); } catch (IllegalArgumentException ignored) { } } |
SpliceDoNotRetryIOExceptionWrapping { public static Exception unwrap(SpliceDoNotRetryIOException spliceException) { String fullMessage = spliceException.getMessage(); int firstColonIndex = fullMessage.indexOf(COLON); int openBraceIndex = fullMessage.indexOf(OPEN_BRACE); String exceptionType; if (firstColonIndex < openBraceIndex) { exceptionType = fullMessage.substring(firstColonIndex + 1, openBraceIndex).trim(); } else { exceptionType = fullMessage.substring(0, openBraceIndex).trim(); } Class exceptionClass; try { exceptionClass = Class.forName(exceptionType); } catch (ClassNotFoundException e1) { exceptionClass = Exception.class; } String json = fullMessage.substring(openBraceIndex, fullMessage.indexOf(CLOSE_BRACE) + 1); return (Exception) GSON.fromJson(json, exceptionClass); } static Exception unwrap(SpliceDoNotRetryIOException spliceException); static SpliceDoNotRetryIOException wrap(StandardException se); } | @Test public void testUnwrap() throws Exception { StandardException stdExceptionIn = StandardException.newException(SQLState.LANG_COLUMN_ID, "arg1", "arg2", "arg3", "arg4"); SpliceDoNotRetryIOException wrapped = SpliceDoNotRetryIOExceptionWrapping.wrap(stdExceptionIn); StandardException stdExceptionOut = (StandardException) SpliceDoNotRetryIOExceptionWrapping.unwrap(wrapped); assertEquals("Column Id", stdExceptionOut.getMessage()); assertArrayEquals(new String[]{"arg1", "arg2", "arg3", "arg4"}, stdExceptionOut.getArguments()); assertEquals("42Z42", stdExceptionOut.getSqlState()); } |
MemstoreKeyValueScanner implements KeyValueScanner, InternalScanner { @Override public KeyValue next() throws IOException{ KeyValue returnValue=peakKeyValue; if(currentResult!=null && advance()) peakKeyValue=(KeyValue)current(); else{ nextResult(); returnValue=peakKeyValue; } return returnValue; } MemstoreKeyValueScanner(ResultScanner resultScanner); Cell current(); boolean advance(); boolean nextResult(); @Override KeyValue peek(); @Override KeyValue next(); @Override boolean next(List<Cell> results); @Override boolean seekToLastRow(); @Override boolean seek(Cell key); @Override boolean reseek(Cell key); @Override boolean requestSeek(Cell kv,boolean forward,boolean useBloom); @Override boolean backwardSeek(Cell key); @Override boolean seekToPreviousRow(Cell key); @Override long getScannerOrder(); @Override void close(); @Override boolean shouldUseScanner(Scan scan, HStore store, long l); @Override boolean realSeekDone(); @Override void enforceSeek(); @Override boolean isFileScanner(); @Override Path getFilePath(); @Override boolean next(List<Cell> result, ScannerContext scannerContext); @Override Cell getNextIndexedKey(); @Override void shipped(); } | @Test public void testExistingResultsAreOrdered() throws IOException { ResultScanner rs = generateResultScanner(SITestUtils.getMockTombstoneCell(10)); MemstoreKeyValueScanner mkvs = new MemstoreKeyValueScanner(rs); List<Cell> results = new ArrayList<>(); results.add(SITestUtils.getMockCommitCell(10, 11)); results.add(SITestUtils.getMockValueCell(10)); mkvs.next(results); assertEquals("Number of results doesn't match", 3, results.size()); assertTrue("Results are not ordered", Ordering.from(KeyValue.COMPARATOR).isOrdered(results)); } |
HConfiguration extends HBaseConfiguration { private SConfiguration init() { SConfiguration config = INSTANCE; if (config == null) { synchronized (this) { config = INSTANCE; if (config == null) { HBaseConfigurationSource configSource = new HBaseConfigurationSource(SpliceConfiguration.create()); ConfigurationBuilder builder = new ConfigurationBuilder(); config = builder.build(new HConfigurationDefaultsList().addConfig(this), configSource); INSTANCE = config; LOG.info("Created Splice configuration."); config.traceConfig(); } } } return config; } private HConfiguration(); static SConfiguration getConfiguration(); static SConfiguration reloadConfiguration(Configuration resetConfiguration); static Configuration unwrapDelegate(); @Override void setDefaults(ConfigurationBuilder builder, ConfigurationSource configurationSource); static final Boolean DEFAULT_IN_MEMORY; static final Boolean DEFAULT_BLOCKCACHE; static final int DEFAULT_TTL; static final String DEFAULT_BLOOMFILTER; } | @Test public void testInit() throws Exception { SConfiguration config = HConfiguration.getConfiguration(); String auth = config.getAuthentication(); assertEquals("NON-NATIVE", auth); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.