method2testcases
stringlengths 118
6.63k
|
---|
### Question:
UpdateParametersRoutine { public void updateParameters(@NonNull UpdateRequest request) { Capabilities capabilities = cameraDevice.getCapabilities(); cameraDevice.updateParameters( combineParameters(asList( flashModeParameters(request, capabilities), focusModeParameters(request, capabilities) )) ); } UpdateParametersRoutine(CameraDevice cameraDevice); void updateParameters(@NonNull UpdateRequest request); }### Answer:
@Test public void updateParameters() throws Exception { UpdateRequest request = UpdateRequest.builder() .flash(torch()) .focusMode(autoFocus()) .build(); testee.updateParameters(request); verify(cameraDevice).updateParameters( new Parameters() .putValue( Parameters.Type.FLASH, Flash.TORCH ) .putValue( Parameters.Type.FOCUS_MODE, FocusMode.AUTO ) ); }
|
### Question:
FotoapparatBuilder { public Fotoapparat build() { validate(); return Fotoapparat.create(this); } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void onlyMandatoryParameters() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments(); Fotoapparat result = builder.build(); assertNotNull(result); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider) { this.cameraProvider = cameraProvider; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void cameraProvider_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .cameraProvider(cameraProvider); assertEquals( cameraProvider, builder.cameraProvider ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder logger(@NonNull Logger logger) { this.logger = logger; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void logger_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .logger(logger); assertEquals( logger, builder.logger ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector) { focusModeSelector = selector; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void focusMode_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .focusMode(focusModeSelector); assertEquals( focusModeSelector, builder.focusModeSelector ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector) { previewFpsRangeSelector = selector; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void previewFpsRange_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .previewFpsRange(previewFpsRangeSelector); assertEquals( previewFpsRangeSelector, builder.previewFpsRangeSelector ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector) { flashSelector = selector; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void flashMode_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .flash(flashSelector); assertEquals( flashSelector, builder.flashSelector ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor) { this.frameProcessor = frameProcessor; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void frameProcessor_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .frameProcessor(frameProcessor); assertEquals( frameProcessor, builder.frameProcessor ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector) { photoSizeSelector = selector; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void photoSize_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .photoSize(photoSizeSelector); assertEquals( photoSizeSelector, builder.photoSizeSelector ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector) { previewSizeSelector = selector; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void previewSize_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .previewSize(previewSizeSelector); assertEquals( previewSizeSelector, builder.previewSizeSelector ); }
|
### Question:
PhotoResult { public PendingResult<Photo> toPendingResult() { return pendingResult; } PhotoResult(PendingResult<Photo> pendingResult); static PhotoResult fromFuture(Future<Photo> photoFuture); PendingResult<BitmapPhoto> toBitmap(); PendingResult<BitmapPhoto> toBitmap(Transformer<Size, Size> sizeTransformer); PendingResult<Void> saveToFile(File file); PendingResult<Photo> toPendingResult(); }### Answer:
@Test public void toPendingResult() throws Exception { PhotoResult photoResult = new PhotoResult(PENDING_RESULT); PendingResult<Photo> pendingResult = photoResult.toPendingResult(); assertSame( PENDING_RESULT, pendingResult ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder previewScaleType(ScaleType scaleType) { this.scaleType = scaleType; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void previewStyle_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .previewScaleType(ScaleType.CENTER_INSIDE); assertEquals( ScaleType.CENTER_INSIDE, builder.scaleType ); }
|
### Question:
FotoapparatBuilder { public FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback) { this.cameraErrorCallback = callback; return this; } FotoapparatBuilder(@NonNull Context context); FotoapparatBuilder cameraProvider(@NonNull CameraProvider cameraProvider); FotoapparatBuilder photoSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewSize(@NonNull SelectorFunction<Collection<Size>, Size> selector); FotoapparatBuilder previewScaleType(ScaleType scaleType); FotoapparatBuilder focusMode(@NonNull SelectorFunction<Collection<FocusMode>, FocusMode> selector); FotoapparatBuilder flash(@NonNull SelectorFunction<Collection<Flash>, Flash> selector); FotoapparatBuilder lensPosition(@NonNull SelectorFunction<Collection<LensPosition>, LensPosition> selector); FotoapparatBuilder previewFpsRange(@NonNull SelectorFunction<Collection<Range<Integer>>, Range<Integer>> selector); FotoapparatBuilder sensorSensitivity(@NonNull SelectorFunction<Range<Integer>, Integer> selector); FotoapparatBuilder jpegQuality(@IntRange(from=0,to=100) @NonNull Integer jpegQuality); FotoapparatBuilder frameProcessor(@NonNull FrameProcessor frameProcessor); FotoapparatBuilder logger(@NonNull Logger logger); FotoapparatBuilder cameraErrorCallback(@NonNull CameraErrorCallback callback); FotoapparatBuilder into(@NonNull CameraRenderer renderer); Fotoapparat build(); }### Answer:
@Test public void cameraErrorCallback_IsConfigurable() throws Exception { FotoapparatBuilder builder = builderWithMandatoryArguments() .cameraErrorCallback(cameraErrorCallback); assertEquals( cameraErrorCallback, builder.cameraErrorCallback ); }
|
### Question:
DefaultProvider implements CameraProvider { @Override public CameraDevice get(Logger logger) { return sdkInfo.isBellowLollipop() ? v1Provider.get(logger) : v2Provider.get(logger); } DefaultProvider(CameraProvider v1Provider,
CameraProvider v2Provider); DefaultProvider(CameraProvider v1Provider,
CameraProvider v2Provider,
SDKInfo sdkInfo); @Override CameraDevice get(Logger logger); }### Answer:
@Test public void bellowLollipop_V1CameraProvider() throws Exception { givenBelowLollipop(); CameraDevice device = testee.get(logger); assertSame(camera1, device); }
@Test public void lollipopOrHigher_V2CameraProvider() throws Exception { givenLollipopOrHigher(); CameraDevice device = testee.get(logger); assertSame(camera2, device); }
|
### Question:
GetCharacteristicsTask { public Characteristics execute(String cameraId) { try { return new Characteristics( manager.getCameraCharacteristics(cameraId) ); } catch (CameraAccessException e) { throw new CameraException(e); } } GetCharacteristicsTask(CameraManager manager); Characteristics execute(String cameraId); }### Answer:
@Test public void getCharacteristics() throws Exception { Characteristics call = testee.execute("0"); assertNotNull(call); }
@Test(expected = CameraException.class) public void managerException_exception() throws Exception { given(manager.getCameraCharacteristics(anyString())) .willThrow(CameraAccessException.class); Characteristics call = testee.execute("0"); }
|
### Question:
SetTextureBufferSizeTask implements Runnable { @Override public void run() { surfaceTexture.setDefaultBufferSize(previewSize.width, previewSize.height); } SetTextureBufferSizeTask(SurfaceTexture surfaceTexture, Size previewSize); @Override void run(); }### Answer:
@Test public void setBufferSize() throws Exception { Size previewSize = new Size(1920, 1080); SetTextureBufferSizeTask testee = new SetTextureBufferSizeTask(surfaceTexture, previewSize); testee.run(); verify(surfaceTexture).setDefaultBufferSize(previewSize.width, previewSize.height); }
|
### Question:
Camera2 implements CameraDevice { @Override public void open(LensPosition lensPosition) { recordMethod(); connectionOperator.open(lensPosition); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void open() throws Exception { testee.open(LensPosition.FRONT); verify(logger).log(anyString()); verify(connectionOperator).open(LensPosition.FRONT); }
|
### Question:
Camera2 implements CameraDevice { @Override public void close() { recordMethod(); connectionOperator.close(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void close() throws Exception { testee.close(); verify(logger).log(anyString()); verify(connectionOperator).close(); }
|
### Question:
Camera2 implements CameraDevice { @Override public void startPreview() { recordMethod(); previewOperator.startPreview(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void startPreview() throws Exception { testee.startPreview(); verify(logger).log(anyString()); verify(previewOperator).startPreview(); }
|
### Question:
PhotoResult { public PendingResult<BitmapPhoto> toBitmap() { return toBitmap(originalSize()); } PhotoResult(PendingResult<Photo> pendingResult); static PhotoResult fromFuture(Future<Photo> photoFuture); PendingResult<BitmapPhoto> toBitmap(); PendingResult<BitmapPhoto> toBitmap(Transformer<Size, Size> sizeTransformer); PendingResult<Void> saveToFile(File file); PendingResult<Photo> toPendingResult(); }### Answer:
@Test public void toBitmap() throws Exception { PendingResult<Photo> pendingResult = spy(PENDING_RESULT); PhotoResult photoResult = new PhotoResult(pendingResult); PendingResult<BitmapPhoto> result = photoResult.toBitmap(); assertNotNull(result); verify(pendingResult).transform( isA(BitmapPhotoTransformer.class) ); }
|
### Question:
Camera2 implements CameraDevice { @Override public void stopPreview() { recordMethod(); previewOperator.stopPreview(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void stopPreview() throws Exception { testee.stopPreview(); verify(logger).log(anyString()); verify(previewOperator).stopPreview(); }
|
### Question:
Camera2 implements CameraDevice { @Override public void setDisplaySurface(Object displaySurface) { recordMethod(); surfaceOperator.setDisplaySurface(displaySurface); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void setDisplaySurface() throws Exception { TextureView textureView = Mockito.mock(TextureView.class); testee.setDisplaySurface(textureView); verify(logger).log(anyString()); verify(surfaceOperator).setDisplaySurface(textureView); }
|
### Question:
Camera2 implements CameraDevice { @Override public void setDisplayOrientation(int degrees) { recordMethod(); orientationOperator.setDisplayOrientation(degrees); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void setDisplayOrientation() throws Exception { testee.setDisplayOrientation(90); verify(logger).log(anyString()); verify(orientationOperator).setDisplayOrientation(90); }
|
### Question:
Camera2 implements CameraDevice { @Override public void updateParameters(Parameters parameters) { recordMethod(); parametersOperator.updateParameters(parameters); currentParameters = parameters; currentParametersLatch.countDown(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void updateParameters() throws Exception { Parameters parameters = new Parameters(); testee.updateParameters(parameters); verify(logger).log(anyString()); verify(parametersOperator).updateParameters(parameters); }
|
### Question:
Camera2 implements CameraDevice { @Override public Capabilities getCapabilities() { recordMethod(); return capabilitiesOperator.getCapabilities(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void getCapabilities() throws Exception { Capabilities capabilities = new Capabilities( Collections.<Size>emptySet(), Collections.<Size>emptySet(), singleton(FocusMode.MACRO), Collections.<Flash>emptySet(), Collections.<Range<Integer>>emptySet(), Ranges.<Integer>emptyRange(), false ); given(capabilitiesOperator.getCapabilities()) .willReturn(capabilities); Capabilities returnedCapabilities = testee.getCapabilities(); verify(logger).log(anyString()); assertEquals(capabilities, returnedCapabilities); }
|
### Question:
Camera2 implements CameraDevice { @Override public Photo takePicture() { recordMethod(); return captureOperator.takePicture(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void takePicture() throws Exception { Photo photo = new Photo(new byte[0], 0); given(captureOperator.takePicture()) .willReturn(photo); Photo returnedPhoto = testee.takePicture(); verify(logger).log(anyString()); assertEquals(photo, returnedPhoto); }
|
### Question:
Camera2 implements CameraDevice { @Override public PreviewStream getPreviewStream() { recordMethod(); return previewStream; } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void previewStream() throws Exception { PreviewStream previewStream = testee.getPreviewStream(); verify(logger).log(anyString()); assertEquals(this.previewStream, previewStream); }
|
### Question:
Camera2 implements CameraDevice { @Override public FocusResult autoFocus() { recordMethod(); return autoFocusOperator.autoFocus(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void autoFocus() throws Exception { given(autoFocusOperator.autoFocus()) .willReturn(successNoMeasurement()); FocusResult resultState = testee.autoFocus(); verify(logger).log(anyString()); assertEquals(successNoMeasurement(), resultState); }
|
### Question:
Camera2 implements CameraDevice { @Override public void measureExposure() { recordMethod(); exposureMeasurementOperator.measureExposure(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void measureExposure() throws Exception { testee.measureExposure(); verify(logger).log(anyString()); verify(exposureMeasurementOperator).measureExposure(); }
|
### Question:
Camera2 implements CameraDevice { @Override public RendererParameters getRendererParameters() { recordMethod(); return rendererParametersOperator.getRendererParameters(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void getRendererParameters() throws Exception { RendererParameters rendererParameters = new RendererParameters(new Size(1920, 1080), 0); given(rendererParametersOperator.getRendererParameters()) .willReturn(rendererParameters); RendererParameters resultRendererParameters = testee.getRendererParameters(); verify(logger).log(anyString()); assertEquals(rendererParameters, resultRendererParameters); }
|
### Question:
PhotoResult { public PendingResult<Void> saveToFile(File file) { return pendingResult .transform(SaveToFileTransformer.create(file)); } PhotoResult(PendingResult<Photo> pendingResult); static PhotoResult fromFuture(Future<Photo> photoFuture); PendingResult<BitmapPhoto> toBitmap(); PendingResult<BitmapPhoto> toBitmap(Transformer<Size, Size> sizeTransformer); PendingResult<Void> saveToFile(File file); PendingResult<Photo> toPendingResult(); }### Answer:
@Test public void saveToFile() throws Exception { PendingResult<Photo> pendingResult = spy(PENDING_RESULT); PhotoResult photoResult = new PhotoResult(pendingResult); PendingResult<?> result = photoResult.saveToFile(new File("")); assertNotNull(result); verify(pendingResult).transform( isA(SaveToFileTransformer.class) ); }
|
### Question:
Camera2 implements CameraDevice { @Override public List<LensPosition> getAvailableLensPositions() { recordMethod(); return availableLensPositionsProvider.getAvailableLensPositions(); } Camera2(Logger logger,
ConnectionOperator connectionOperator,
PreviewOperator previewOperator,
SurfaceOperator surfaceOperator,
OrientationOperator orientationOperator,
ParametersOperator parametersOperator,
CapabilitiesOperator capabilitiesOperator,
PreviewStream previewStream,
RendererParametersOperator rendererParametersOperator,
AutoFocusOperator autoFocusOperator,
ExposureMeasurementOperator exposureMeasurementOperator,
CaptureOperator captureOperator,
AvailableLensPositionsProvider availableLensPositionsProvider); @Override void open(LensPosition lensPosition); @Override void close(); @Override void startPreview(); @Override void stopPreview(); @Override void setDisplaySurface(Object displaySurface); @Override void setDisplayOrientation(int degrees); @Override void updateParameters(Parameters parameters); @Override Capabilities getCapabilities(); @Override Parameters getCurrentParameters(); @Override FocusResult autoFocus(); @Override void measureExposure(); @Override Photo takePicture(); @Override PreviewStream getPreviewStream(); @Override RendererParameters getRendererParameters(); @Override List<LensPosition> getAvailableLensPositions(); @Override void setZoom(@FloatRange(from = 0f, to = 1f) float level); }### Answer:
@Test public void getAvailableLensPositions() throws Exception { given(availableLensPositionsProvider.getAvailableLensPositions()) .willReturn(singletonList(LensPosition.EXTERNAL)); List<LensPosition> lensPositions = testee.getAvailableLensPositions(); verify(logger).log(anyString()); assertEquals(singletonList(LensPosition.EXTERNAL), lensPositions); }
|
### Question:
CapabilitiesFactory implements CapabilitiesOperator { @Override public Capabilities getCapabilities() { return new Capabilities( availableJpegSizes(), availablePreviewSizes(), availableFocusModes(), availableFlashModes(), availablePreviewFpsRanges(), availableSensorSensitivity(), false ); } CapabilitiesFactory(CameraConnection cameraConnection); @Override Capabilities getCapabilities(); }### Answer:
@Test public void supportedFlashModes_FlashAvailable() throws Exception { given(characteristics.isFlashAvailable()) .willReturn(true); given(characteristics.autoExposureModes()) .willReturn(new int[]{ CameraMetadata.CONTROL_AE_MODE_ON_ALWAYS_FLASH, CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH, CameraMetadata.CONTROL_AE_MODE_ON_AUTO_FLASH_REDEYE }); Capabilities capabilities = testee.getCapabilities(); assertEquals(FLASH_SET, capabilities.supportedFlashModes()); }
@Test public void supportedFlashModes_FlashNotAvailable() throws Exception { given(characteristics.isFlashAvailable()) .willReturn(false); Capabilities capabilities = testee.getCapabilities(); assertEquals( asSet(Flash.OFF), capabilities.supportedFlashModes() ); }
@Test public void supportedFocusModes() throws Exception { given(characteristics.autoFocusModes()) .willReturn( new int[]{ CameraMetadata.CONTROL_AF_MODE_OFF, CameraMetadata.CONTROL_AF_MODE_AUTO, CameraMetadata.CONTROL_AF_MODE_MACRO, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_VIDEO, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE, CameraMetadata.CONTROL_AF_MODE_EDOF } ); Capabilities capabilities = testee.getCapabilities(); assertEquals(FOCUS_MODE_SET, capabilities.supportedFocusModes()); }
@Test public void supportedPictureSizes() throws Exception { given(characteristics.getJpegOutputSizes()) .willReturn(SIZE_SET); Capabilities capabilities = testee.getCapabilities(); assertEquals(SIZE_SET, capabilities.supportedPictureSizes()); }
@Test public void supportedPreviewSizes_Below_1080p() throws Exception { given(characteristics.getSurfaceOutputSizes()) .willReturn(asSet( new Size(1000, 1000), new Size(1080, 1920), new Size(1920, 1080), new Size(1920, 1920), new Size(1440, 1920) )); Capabilities capabilities = testee.getCapabilities(); assertEquals( asSet( new Size(1000, 1000), new Size(1920, 1080) ), capabilities.supportedPreviewSizes() ); }
@Test public void supportedPreviewFpsRanges() throws Exception { given(characteristics.getTargetFpsRanges()) .willReturn(PREVIEW_FPS_RANGE_SET); Capabilities capabilities = testee.getCapabilities(); assertEquals( PREVIEW_FPS_RANGE_SET, capabilities.supportedPreviewFpsRanges() ); }
|
### Question:
Characteristics { public boolean isFrontFacingLens() { return cameraCharacteristics.get(CameraCharacteristics.LENS_FACING) == CameraMetadata.LENS_FACING_FRONT; } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void isFrontFacingLens() throws Exception { given(cameraCharacteristics.get(CameraCharacteristics.LENS_FACING)) .willReturn(CameraMetadata.LENS_FACING_FRONT); boolean flashAvailable = testee.isFrontFacingLens(); assertTrue(flashAvailable); }
|
### Question:
Characteristics { public boolean isFlashAvailable() { return cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE); } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void isFlashAvailable() throws Exception { given(cameraCharacteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) .willReturn(true); boolean flashAvailable = testee.isFlashAvailable(); assertTrue(flashAvailable); }
|
### Question:
Characteristics { public boolean isFixedFocusLens() { Float focusDistance = cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE); return focusDistance == 0f; } Characteristics(CameraCharacteristics cameraCharacteristics); boolean isFrontFacingLens(); boolean isFlashAvailable(); boolean isFixedFocusLens(); boolean isLegacyDevice(); int getSensorOrientation(); int[] autoExposureModes(); int[] autoFocusModes(); Set<Size> getJpegOutputSizes(); Set<Size> getSurfaceOutputSizes(); Set<Range<Integer>> getTargetFpsRanges(); Range<Integer> getSensorSensitivityRange(); }### Answer:
@Test public void isFixedFocus() throws Exception { given(cameraCharacteristics.get(CameraCharacteristics.LENS_INFO_MINIMUM_FOCUS_DISTANCE)) .willReturn(0f); boolean fixedFocusLens = testee.isFixedFocusLens(); assertTrue(fixedFocusLens); }
|
### Question:
CapabilitiesResult { public PendingResult<Capabilities> toPendingResult() { return pendingResult; } CapabilitiesResult(PendingResult<Capabilities> pendingResult); static CapabilitiesResult fromFuture(Future<Capabilities> capabilitiesFuture); PendingResult<Capabilities> toPendingResult(); }### Answer:
@Test public void toPendingResult() throws Exception { CapabilitiesResult photoResult = new CapabilitiesResult(PENDING_RESULT); PendingResult<Capabilities> pendingResult = photoResult.toPendingResult(); assertSame( PENDING_RESULT, pendingResult ); }
|
### Question:
LoggingCallAdapterFactory extends CallAdapter.Factory { public static String errorMessage(ResponseBody errorBody) throws IOException { if (errorBody.contentLength() == 0) { return ""; } Buffer buffer = new Buffer(); buffer.writeAll(errorBody.source().peek()); if (!isPlaintext(buffer)) { return "Error body is not plain text."; } return ResponseBody.create(errorBody.contentType(), buffer.size(), buffer).string(); } LoggingCallAdapterFactory(Logger logger); static String errorMessage(ResponseBody errorBody); @Override CallAdapter<?, ?> get(Type returnType, Annotation[] annotations, Retrofit retrofit); }### Answer:
@Test public void errorMessageHelperDoesNotConsumeErrorBody() throws IOException { ResponseBody errorBody = ResponseBody.create(null, "This request failed."); BufferedSource source = errorBody.source(); assertThat(LoggingCallAdapterFactory.errorMessage(errorBody)).isEqualTo("This request failed."); assertThat(source.getBuffer().size()).isEqualTo(20); assertThat(source.exhausted()).isFalse(); String errorBodyUtf8 = source.readUtf8(); assertThat(errorBodyUtf8).isEqualTo("This request failed."); assertThat(source.exhausted()).isTrue(); }
@Test public void errorMessageHelperReturnsEmptyStringForEmptyBody() throws IOException { ResponseBody errorBody = ResponseBody.create(null, new byte[0]); assertThat(LoggingCallAdapterFactory.errorMessage(errorBody)).isEmpty(); }
@Test public void errorMessageHelperChecksForPlainText() throws IOException { ResponseBody errorBody = ResponseBody.create(null, String.valueOf((char) 0x9F)); assertThat(LoggingCallAdapterFactory.errorMessage(errorBody)) .isEqualTo("Error body is not plain text."); }
|
### Question:
HRegionLocation implements Comparable<HRegionLocation> { @Override public synchronized String toString() { if (this.cachedString == null) { this.cachedString = "region=" + this.regionInfo.getRegionNameAsString() + ", hostname=" + this.hostname + ", port=" + this.port; } return this.cachedString; } HRegionLocation(HRegionInfo regionInfo, final String hostname,
final int port); @Override synchronized String toString(); @Override boolean equals(Object o); @Override int hashCode(); HRegionInfo getRegionInfo(); HServerAddress getServerAddress(); String getHostname(); int getPort(); synchronized String getHostnamePort(); int compareTo(HRegionLocation o); }### Answer:
@Test public void testToString() { ServerName hsa1 = new ServerName("localhost", 1234, -1L); HRegionLocation hrl1 = new HRegionLocation(HRegionInfo.FIRST_META_REGIONINFO, hsa1.getHostname(), hsa1.getPort()); System.out.println(hrl1.toString()); }
|
### Question:
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { public static void configureIncrementalLoad(Job job, HTable table) throws IOException { Configuration conf = job.getConfiguration(); Class<? extends Partitioner> topClass; try { topClass = getTotalOrderPartitionerClass(); } catch (ClassNotFoundException e) { throw new IOException("Failed getting TotalOrderPartitioner", e); } job.setPartitionerClass(topClass); job.setOutputKeyClass(ImmutableBytesWritable.class); job.setOutputValueClass(KeyValue.class); job.setOutputFormatClass(HFileOutputFormat.class); if (KeyValue.class.equals(job.getMapOutputValueClass())) { job.setReducerClass(KeyValueSortReducer.class); } else if (Put.class.equals(job.getMapOutputValueClass())) { job.setReducerClass(PutSortReducer.class); } else { LOG.warn("Unknown map output value type:" + job.getMapOutputValueClass()); } LOG.info("Looking up current regions for table " + table); List<ImmutableBytesWritable> startKeys = getRegionStartKeys(table); LOG.info("Configuring " + startKeys.size() + " reduce partitions " + "to match current region count"); job.setNumReduceTasks(startKeys.size()); Path partitionsPath = new Path(job.getWorkingDirectory(), "partitions_" + UUID.randomUUID()); LOG.info("Writing partition information to " + partitionsPath); FileSystem fs = partitionsPath.getFileSystem(conf); writePartitions(conf, partitionsPath, startKeys); partitionsPath.makeQualified(fs); URI cacheUri; try { cacheUri = new URI(partitionsPath.toString() + "#" + org.apache.hadoop.hbase.mapreduce.hadoopbackport.TotalOrderPartitioner.DEFAULT_PATH); } catch (URISyntaxException e) { throw new IOException(e); } DistributedCache.addCacheFile(cacheUri, conf); DistributedCache.createSymlink(conf); configureCompression(table, conf); configureBloomType(table, conf); TableMapReduceUtil.addDependencyJars(job); LOG.info("Incremental table output configured."); } RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter(final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); }### Answer:
@Test public void testJobConfiguration() throws Exception { Job job = new Job(); HTable table = Mockito.mock(HTable.class); setupMockStartKeys(table); HFileOutputFormat.configureIncrementalLoad(job, table); assertEquals(job.getNumReduceTasks(), 4); }
|
### Question:
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { static Map<byte[], String> createFamilyCompressionMap(Configuration conf) { return createFamilyConfValueMap(conf, COMPRESSION_CONF_KEY); } RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter(final TaskAttemptContext context); static void configureIncrementalLoad(Job job, HTable table); }### Answer:
@Test public void testCreateFamilyCompressionMap() throws IOException { for (int numCfs = 0; numCfs <= 3; numCfs++) { Configuration conf = new Configuration(this.util.getConfiguration()); Map<String, Compression.Algorithm> familyToCompression = getMockColumnFamilies(numCfs); HTable table = Mockito.mock(HTable.class); setupMockColumnFamilies(table, familyToCompression); HFileOutputFormat.configureCompression(table, conf); Map<byte[], String> retrievedFamilyToCompressionMap = HFileOutputFormat.createFamilyCompressionMap(conf); for (Entry<String, Algorithm> entry : familyToCompression.entrySet()) { assertEquals("Compression configuration incorrect for column family:" + entry.getKey(), entry.getValue() .getName(), retrievedFamilyToCompressionMap.get(entry.getKey().getBytes())); } } }
|
### Question:
Get extends OperationWithAttributes implements Writable, Row, Comparable<Row> { public Get() {} Get(); Get(byte [] row); Get(byte [] row, RowLock rowLock); Get addFamily(byte [] family); Get addColumn(byte [] family, byte [] qualifier); Get setTimeRange(long minStamp, long maxStamp); Get setTimeStamp(long timestamp); Get setMaxVersions(); Get setMaxVersions(int maxVersions); Get setFilter(Filter filter); Filter getFilter(); void setCacheBlocks(boolean cacheBlocks); boolean getCacheBlocks(); byte [] getRow(); @SuppressWarnings("deprecation") RowLock getRowLock(); long getLockId(); int getMaxVersions(); TimeRange getTimeRange(); Set<byte[]> familySet(); int numFamilies(); boolean hasFamilies(); Map<byte[],NavigableSet<byte[]>> getFamilyMap(); @Override Map<String, Object> getFingerprint(); @Override Map<String, Object> toMap(int maxCols); int compareTo(Row other); void readFields(final DataInput in); void write(final DataOutput out); }### Answer:
@Test public void testGetAttributes() { Get get = new Get(); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttribute("absent")); get.setAttribute("absent", null); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttribute("absent")); get.setAttribute("attribute1", Bytes.toBytes("value1")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), get.getAttribute("attribute1"))); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value1"), get.getAttributesMap().get("attribute1"))); get.setAttribute("attribute1", Bytes.toBytes("value12")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), get.getAttribute("attribute1"))); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value12"), get.getAttributesMap().get("attribute1"))); get.setAttribute("attribute2", Bytes.toBytes("value2")); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), get.getAttribute("attribute2"))); Assert.assertEquals(2, get.getAttributesMap().size()); Assert.assertTrue(Arrays.equals(Bytes.toBytes("value2"), get.getAttributesMap().get("attribute2"))); get.setAttribute("attribute2", null); Assert.assertNull(get.getAttribute("attribute2")); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertNull(get.getAttributesMap().get("attribute2")); get.setAttribute("attribute2", null); Assert.assertNull(get.getAttribute("attribute2")); Assert.assertEquals(1, get.getAttributesMap().size()); Assert.assertNull(get.getAttributesMap().get("attribute2")); get.setAttribute("attribute1", null); Assert.assertNull(get.getAttribute("attribute1")); Assert.assertTrue(get.getAttributesMap().isEmpty()); Assert.assertNull(get.getAttributesMap().get("attribute1")); }
|
### Question:
HTableUtil { public static void bucketRsPut(HTable htable, List<Put> puts) throws IOException { Map<String, List<Put>> putMap = createRsPutMap(htable, puts); for (List<Put> rsPuts: putMap.values()) { htable.put( rsPuts ); } htable.flushCommits(); } static void bucketRsPut(HTable htable, List<Put> puts); static void bucketRsBatch(HTable htable, List<Row> rows); }### Answer:
@Test public void testBucketPut() throws Exception { byte [] TABLE = Bytes.toBytes("testBucketPut"); HTable ht = TEST_UTIL.createTable(TABLE, FAMILY); ht.setAutoFlush( false ); List<Put> puts = new ArrayList<Put>(); puts.add( createPut("row1") ); puts.add( createPut("row2") ); puts.add( createPut("row3") ); puts.add( createPut("row4") ); HTableUtil.bucketRsPut( ht, puts ); Scan scan = new Scan(); scan.addColumn(FAMILY, QUALIFIER); int count = 0; for(Result result : ht.getScanner(scan)) { count++; } LOG.info("bucket put count=" + count); assertEquals(count, puts.size()); ht.close(); }
|
### Question:
HTableUtil { public static void bucketRsBatch(HTable htable, List<Row> rows) throws IOException { try { Map<String, List<Row>> rowMap = createRsRowMap(htable, rows); for (List<Row> rsRows: rowMap.values()) { htable.batch( rsRows ); } } catch (InterruptedException e) { throw new IOException(e); } } static void bucketRsPut(HTable htable, List<Put> puts); static void bucketRsBatch(HTable htable, List<Row> rows); }### Answer:
@Test public void testBucketBatch() throws Exception { byte [] TABLE = Bytes.toBytes("testBucketBatch"); HTable ht = TEST_UTIL.createTable(TABLE, FAMILY); List<Row> rows = new ArrayList<Row>(); rows.add( createPut("row1") ); rows.add( createPut("row2") ); rows.add( createPut("row3") ); rows.add( createPut("row4") ); HTableUtil.bucketRsBatch( ht, rows ); Scan scan = new Scan(); scan.addColumn(FAMILY, QUALIFIER); int count = 0; for(Result result : ht.getScanner(scan)) { count++; } LOG.info("bucket batch count=" + count); assertEquals(count, rows.size()); ht.close(); }
|
### Question:
Operation { public String toJSON(int maxCols) throws IOException { ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(toMap(maxCols)); } abstract Map<String, Object> getFingerprint(); abstract Map<String, Object> toMap(int maxCols); Map<String, Object> toMap(); String toJSON(int maxCols); String toJSON(); String toString(int maxCols); @Override String toString(); }### Answer:
@Test public void testOperationJSON() throws IOException { Scan scan = new Scan(ROW); scan.addColumn(FAMILY, QUALIFIER); String json = scan.toJSON(); Map<String, Object> parsedJSON = mapper.readValue(json, HashMap.class); assertEquals("startRow incorrect in Scan.toJSON()", Bytes.toStringBinary(ROW), parsedJSON.get("startRow")); List familyInfo = (List) ((Map) parsedJSON.get("families")).get( Bytes.toStringBinary(FAMILY)); assertNotNull("Family absent in Scan.toJSON()", familyInfo); assertEquals("Qualifier absent in Scan.toJSON()", 1, familyInfo.size()); assertEquals("Qualifier incorrect in Scan.toJSON()", Bytes.toStringBinary(QUALIFIER), familyInfo.get(0)); Get get = new Get(ROW); get.addColumn(FAMILY, QUALIFIER); json = get.toJSON(); parsedJSON = mapper.readValue(json, HashMap.class); assertEquals("row incorrect in Get.toJSON()", Bytes.toStringBinary(ROW), parsedJSON.get("row")); familyInfo = (List) ((Map) parsedJSON.get("families")).get( Bytes.toStringBinary(FAMILY)); assertNotNull("Family absent in Get.toJSON()", familyInfo); assertEquals("Qualifier absent in Get.toJSON()", 1, familyInfo.size()); assertEquals("Qualifier incorrect in Get.toJSON()", Bytes.toStringBinary(QUALIFIER), familyInfo.get(0)); Put put = new Put(ROW); put.add(FAMILY, QUALIFIER, VALUE); json = put.toJSON(); parsedJSON = mapper.readValue(json, HashMap.class); assertEquals("row absent in Put.toJSON()", Bytes.toStringBinary(ROW), parsedJSON.get("row")); familyInfo = (List) ((Map) parsedJSON.get("families")).get( Bytes.toStringBinary(FAMILY)); assertNotNull("Family absent in Put.toJSON()", familyInfo); assertEquals("KeyValue absent in Put.toJSON()", 1, familyInfo.size()); Map kvMap = (Map) familyInfo.get(0); assertEquals("Qualifier incorrect in Put.toJSON()", Bytes.toStringBinary(QUALIFIER), kvMap.get("qualifier")); assertEquals("Value length incorrect in Put.toJSON()", VALUE.length, kvMap.get("vlen")); Delete delete = new Delete(ROW); delete.deleteColumn(FAMILY, QUALIFIER); json = delete.toJSON(); parsedJSON = mapper.readValue(json, HashMap.class); assertEquals("row absent in Delete.toJSON()", Bytes.toStringBinary(ROW), parsedJSON.get("row")); familyInfo = (List) ((Map) parsedJSON.get("families")).get( Bytes.toStringBinary(FAMILY)); assertNotNull("Family absent in Delete.toJSON()", familyInfo); assertEquals("KeyValue absent in Delete.toJSON()", 1, familyInfo.size()); kvMap = (Map) familyInfo.get(0); assertEquals("Qualifier incorrect in Delete.toJSON()", Bytes.toStringBinary(QUALIFIER), kvMap.get("qualifier")); }
|
### Question:
MetaScanner { public static void metaScan(Configuration configuration, MetaScannerVisitor visitor) throws IOException { metaScan(configuration, visitor, null); } static void metaScan(Configuration configuration,
MetaScannerVisitor visitor); static void metaScan(Configuration configuration,
MetaScannerVisitor visitor, byte [] userTableName); static void metaScan(Configuration configuration,
MetaScannerVisitor visitor, byte [] userTableName, byte[] row,
int rowLimit); static void metaScan(Configuration configuration,
final MetaScannerVisitor visitor, final byte[] tableName,
final byte[] row, final int rowLimit, final byte[] metaTableName); static List<HRegionInfo> listAllRegions(Configuration conf); static List<HRegionInfo> listAllRegions(Configuration conf, final boolean offlined); static NavigableMap<HRegionInfo, ServerName> allTableRegions(Configuration conf,
final byte [] tablename, final boolean offlined); }### Answer:
@Test public void testMetaScanner() throws Exception { LOG.info("Starting testMetaScanner"); final byte[] TABLENAME = Bytes.toBytes("testMetaScanner"); final byte[] FAMILY = Bytes.toBytes("family"); TEST_UTIL.createTable(TABLENAME, FAMILY); Configuration conf = TEST_UTIL.getConfiguration(); HTable table = new HTable(conf, TABLENAME); TEST_UTIL.createMultiRegions(conf, table, FAMILY, new byte[][]{ HConstants.EMPTY_START_ROW, Bytes.toBytes("region_a"), Bytes.toBytes("region_b")}); TEST_UTIL.countRows(table); MetaScanner.MetaScannerVisitor visitor = mock(MetaScanner.MetaScannerVisitor.class); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME); verify(visitor, times(3)).processRow((Result)anyObject()); reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, HConstants.EMPTY_BYTE_ARRAY, 1000); verify(visitor, times(3)).processRow((Result)anyObject()); reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1000); verify(visitor, times(2)).processRow((Result)anyObject()); reset(visitor); doReturn(true).when(visitor).processRow((Result)anyObject()); MetaScanner.metaScan(conf, visitor, TABLENAME, Bytes.toBytes("region_ac"), 1); verify(visitor, times(1)).processRow((Result)anyObject()); table.close(); }
|
### Question:
ConnectionUtils { public static long getPauseTime(final long pause, final int tries) { int ntries = tries; if (ntries >= HConstants.RETRY_BACKOFF.length) { ntries = HConstants.RETRY_BACKOFF.length - 1; } long normalPause = pause * HConstants.RETRY_BACKOFF[ntries]; long jitter = (long)(normalPause * RANDOM.nextFloat() * 0.01f); return normalPause + jitter; } static long getPauseTime(final long pause, final int tries); }### Answer:
@Test public void testRetryTimeJitter() { long[] retries = new long[200]; long baseTime = 1000000; long maxTimeExpected = (long) (baseTime * 1.01f); for (int i = 0; i < retries.length; i++) { retries[i] = ConnectionUtils.getPauseTime(baseTime, 0); } Set<Long> retyTimeSet = new TreeSet<Long>(); for (long l : retries) { assertTrue(l >= baseTime); assertTrue(l <= maxTimeExpected); retyTimeSet.add(l); } assertTrue(retyTimeSet.size() > (retries.length * 0.80)); }
|
### Question:
ZooKeeperMainServerArg { public String parse(final Configuration c) { Properties zkProps = ZKConfig.makeZKProps(c); String host = null; String clientPort = null; List<String> hosts = new ArrayList<String>(); for (Entry<Object, Object> entry: zkProps.entrySet()) { String key = entry.getKey().toString().trim(); String value = entry.getValue().toString().trim(); if (key.startsWith("server.")) { String[] parts = value.split(":"); hosts.add(parts[0]); } else if (key.endsWith("clientPort")) { clientPort = value; } } if (hosts.isEmpty() || clientPort == null) return null; for (int i = 0; i < hosts.size(); i++) { if (i > 0) host += "," + hosts.get(i); else host = hosts.get(i); } return host != null ? host + ":" + clientPort : null; } String parse(final Configuration c); static void main(String args[]); }### Answer:
@Test public void test() { Configuration c = HBaseConfiguration.create(); assertEquals("localhost:" + c.get(HConstants.ZOOKEEPER_CLIENT_PORT), parser.parse(c)); final String port = "1234"; c.set(HConstants.ZOOKEEPER_CLIENT_PORT, port); c.set("hbase.zookeeper.quorum", "example.com"); assertEquals("example.com:" + port, parser.parse(c)); c.set("hbase.zookeeper.quorum", "example1.com,example2.com,example3.com"); assertTrue(port, parser.parse(c).matches("(example[1-3]\\.com,){2}example[1-3]\\.com:" + port)); }
|
### Question:
ActiveMasterManager extends ZooKeeperListener { boolean blockUntilBecomingActiveMaster(MonitoredTask startupStatus, ClusterStatusTracker clusterStatusTracker) { while (true) { startupStatus.setStatus("Trying to register in ZK as active master"); try { String backupZNode = ZKUtil.joinZNode( this.watcher.backupMasterAddressesZNode, this.sn.toString()); if (ZKUtil.createEphemeralNodeAndWatch(this.watcher, this.watcher.masterAddressZNode, this.sn.getVersionedBytes())) { LOG.info("Deleting ZNode for " + backupZNode + " from backup master directory"); ZKUtil.deleteNodeFailSilent(this.watcher, backupZNode); startupStatus.setStatus("Successfully registered as active master."); this.clusterHasActiveMaster.set(true); LOG.info("Master=" + this.sn); return true; } this.clusterHasActiveMaster.set(true); LOG.info("Adding ZNode for " + backupZNode + " in backup master directory"); ZKUtil.createEphemeralNodeAndWatch(this.watcher, backupZNode, this.sn.getVersionedBytes()); String msg; byte [] bytes = ZKUtil.getDataAndWatch(this.watcher, this.watcher.masterAddressZNode); if (bytes == null) { msg = ("A master was detected, but went down before its address " + "could be read. Attempting to become the next active master"); } else { ServerName currentMaster = ServerName.parseVersionedServerName(bytes); if (ServerName.isSameHostnameAndPort(currentMaster, this.sn)) { msg = ("Current master has this master's address, " + currentMaster + "; master was restarted? Deleting node."); ZKUtil.deleteNode(this.watcher, this.watcher.masterAddressZNode); } else { msg = "Another master is the active master, " + currentMaster + "; waiting to become the next active master"; } } LOG.info(msg); startupStatus.setStatus(msg); } catch (KeeperException ke) { master.abort("Received an unexpected KeeperException, aborting", ke); return false; } synchronized (this.clusterHasActiveMaster) { while (this.clusterHasActiveMaster.get() && !this.master.isStopped()) { try { this.clusterHasActiveMaster.wait(); } catch (InterruptedException e) { LOG.debug("Interrupted waiting for master to die", e); } } if (!clusterStatusTracker.isClusterUp()) { this.master.stop("Cluster went down before this master became active"); } if (this.master.isStopped()) { return false; } } } } ActiveMasterManager(ZooKeeperWatcher watcher, ServerName sn, Server master); @Override void nodeCreated(String path); @Override void nodeDeleted(String path); boolean isActiveMaster(); void stop(); }### Answer:
@Test public void testRestartMaster() throws IOException, KeeperException { ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), "testActiveMasterManagerFromZK", null, true); try { ZKUtil.deleteNode(zk, zk.masterAddressZNode); ZKUtil.deleteNode(zk, zk.clusterStateZNode); } catch(KeeperException.NoNodeException nne) {} ServerName master = new ServerName("localhost", 1, System.currentTimeMillis()); DummyMaster dummyMaster = new DummyMaster(zk,master); ClusterStatusTracker clusterStatusTracker = dummyMaster.getClusterStatusTracker(); ActiveMasterManager activeMasterManager = dummyMaster.getActiveMasterManager(); assertFalse(activeMasterManager.clusterHasActiveMaster.get()); MonitoredTask status = Mockito.mock(MonitoredTask.class); clusterStatusTracker.setClusterUp(); activeMasterManager.blockUntilBecomingActiveMaster(status,clusterStatusTracker); assertTrue(activeMasterManager.clusterHasActiveMaster.get()); assertMaster(zk, master); DummyMaster secondDummyMaster = new DummyMaster(zk,master); ActiveMasterManager secondActiveMasterManager = secondDummyMaster.getActiveMasterManager(); assertFalse(secondActiveMasterManager.clusterHasActiveMaster.get()); activeMasterManager.blockUntilBecomingActiveMaster(status,clusterStatusTracker); assertTrue(activeMasterManager.clusterHasActiveMaster.get()); assertMaster(zk, master); }
|
### Question:
AssignmentManager extends ZooKeeperListener { void processDeadServersAndRegionsInTransition() throws KeeperException, IOException, InterruptedException { processDeadServersAndRegionsInTransition(null); } AssignmentManager(Server master, ServerManager serverManager,
CatalogTracker catalogTracker, final LoadBalancer balancer,
final ExecutorService service); ZKTable getZKTable(); ServerName getRegionServerOfRegion(HRegionInfo hri); boolean isRegionAssigned(HRegionInfo hri); List<HRegionInfo> getEnablingTableRegions(String tableName); void addPlan(String encodedName, RegionPlan plan); void addPlans(Map<String, RegionPlan> plans); void setRegionsToReopen(List <HRegionInfo> regions); Pair<Integer, Integer> getReopenStatus(byte[] tableName); void removeClosedRegion(HRegionInfo hri); @Override void nodeCreated(String path); @Override void nodeDataChanged(String path); @Override void nodeDeleted(final String path); @Override void nodeChildrenChanged(String path); void regionOffline(final HRegionInfo regionInfo); void setOffline(HRegionInfo regionInfo); void offlineDisabledRegion(HRegionInfo regionInfo); void assign(HRegionInfo region, boolean setOfflineInZK); void assign(HRegionInfo region, boolean setOfflineInZK,
boolean forceNewPlan); void assign(HRegionInfo region, boolean setOfflineInZK,
boolean forceNewPlan, boolean hijack); void removeDeadNotExpiredServers(List<ServerName> servers); void unassign(List<HRegionInfo> regions); void unassign(HRegionInfo region); void unassign(HRegionInfo region, boolean force); void deleteClosingOrClosedNode(HRegionInfo region); void waitForAssignment(HRegionInfo regionInfo); void assignRoot(); void assignMeta(); void assignUserRegionsToOnlineServers(List<HRegionInfo> regions); void assignUserRegions(List<HRegionInfo> regions, List<ServerName> servers); void assignAllUserRegions(); NavigableMap<String, RegionState> getRegionsInTransition(); boolean isRegionsInTransition(); RegionState isRegionInTransition(final HRegionInfo hri); void clearRegionFromTransition(HRegionInfo hri); void waitOnRegionToClearRegionsInTransition(final HRegionInfo hri); List<HRegionInfo> getRegionsOfTable(byte[] tableName); boolean isCarryingRoot(ServerName serverName); boolean isCarryingMeta(ServerName serverName); boolean isCarryingRegion(ServerName serverName, HRegionInfo hri); Pair<Set<HRegionInfo>, List<RegionState>> processServerShutdown(final ServerName sn); void handleSplitReport(final ServerName sn, final HRegionInfo parent,
final HRegionInfo a, final HRegionInfo b); void stop(); boolean isServerOnline(ServerName serverName); void shutdown(); }### Answer:
@Test(timeout = 5000) public void testProcessDeadServersAndRegionsInTransitionShouldNotFailWithNPE() throws IOException, KeeperException, InterruptedException, ServiceException { final RecoverableZooKeeper recoverableZk = Mockito .mock(RecoverableZooKeeper.class); AssignmentManagerWithExtrasForTesting am = setUpMockedAssignmentManager( this.server, this.serverManager); Watcher zkw = new ZooKeeperWatcher(HBaseConfiguration.create(), "unittest", null) { public RecoverableZooKeeper getRecoverableZooKeeper() { return recoverableZk; } }; ((ZooKeeperWatcher) zkw).registerListener(am); Mockito.doThrow(new InterruptedException()).when(recoverableZk) .getChildren("/hbase/unassigned", zkw); am.setWatcher((ZooKeeperWatcher) zkw); try { am.processDeadServersAndRegionsInTransition(); fail("Expected to abort"); } catch (NullPointerException e) { fail("Should not throw NPE"); } catch (RuntimeException e) { assertEquals("Aborted", e.getLocalizedMessage()); } }
|
### Question:
TableDeleteFamilyHandler extends TableEventHandler { @Override public String toString() { String name = "UnknownServerName"; if(server != null && server.getServerName() != null) { name = server.getServerName().toString(); } String family = "UnknownFamily"; if(familyName != null) { family = Bytes.toString(familyName); } return getClass().getSimpleName() + "-" + name + "-" + getSeqid() + "-" + tableNameStr + "-" + family; } TableDeleteFamilyHandler(byte[] tableName, byte [] familyName,
Server server, final MasterServices masterServices); @Override String toString(); }### Answer:
@Test public void deleteColumnFamilyWithMultipleRegions() throws Exception { HBaseAdmin admin = TEST_UTIL.getHBaseAdmin(); HTableDescriptor beforehtd = admin.getTableDescriptor(Bytes .toBytes(TABLENAME)); FileSystem fs = TEST_UTIL.getDFSCluster().getFileSystem(); assertTrue(admin.isTableAvailable(TABLENAME)); assertEquals(3, beforehtd.getColumnFamilies().length); HColumnDescriptor[] families = beforehtd.getColumnFamilies(); for (int i = 0; i < families.length; i++) { assertTrue(families[i].getNameAsString().equals("cf" + (i + 1))); } Path tableDir = new Path(TEST_UTIL.getDefaultRootDirPath().toString() + "/" + TABLENAME); assertTrue(fs.exists(tableDir)); FileStatus[] fileStatus = fs.listStatus(tableDir); for (int i = 0; i < fileStatus.length; i++) { if (fileStatus[i].isDir() == true) { FileStatus[] cf = fs.listStatus(fileStatus[i].getPath()); int k = 1; for (int j = 0; j < cf.length; j++) { if (cf[j].isDir() == true && cf[j].getPath().getName().startsWith(".") == false) { assertTrue(cf[j].getPath().getName().equals("cf" + k)); k++; } } } } admin.disableTable(TABLENAME); admin.deleteColumn(TABLENAME, "cf2"); HTableDescriptor afterhtd = admin.getTableDescriptor(Bytes .toBytes(TABLENAME)); assertEquals(2, afterhtd.getColumnFamilies().length); HColumnDescriptor[] newFamilies = afterhtd.getColumnFamilies(); assertTrue(newFamilies[0].getNameAsString().equals("cf1")); assertTrue(newFamilies[1].getNameAsString().equals("cf3")); fileStatus = fs.listStatus(tableDir); for (int i = 0; i < fileStatus.length; i++) { if (fileStatus[i].isDir() == true) { FileStatus[] cf = fs.listStatus(fileStatus[i].getPath()); for (int j = 0; j < cf.length; j++) { if (cf[j].isDir() == true) { assertFalse(cf[j].getPath().getName().equals("cf2")); } } } } }
|
### Question:
DefaultLoadBalancer implements LoadBalancer { public Map<HRegionInfo, ServerName> immediateAssignment( List<HRegionInfo> regions, List<ServerName> servers) { Map<HRegionInfo,ServerName> assignments = new TreeMap<HRegionInfo,ServerName>(); for(HRegionInfo region : regions) { assignments.put(region, servers.get(RANDOM.nextInt(servers.size()))); } return assignments; } void setClusterStatus(ClusterStatus st); void setMasterServices(MasterServices masterServices); @Override void setConf(Configuration conf); @Override Configuration getConf(); List<RegionPlan> balanceCluster(
Map<ServerName, List<HRegionInfo>> clusterState); Map<ServerName, List<HRegionInfo>> roundRobinAssignment(
List<HRegionInfo> regions, List<ServerName> servers); Map<ServerName, List<HRegionInfo>> retainAssignment(
Map<HRegionInfo, ServerName> regions, List<ServerName> servers); Map<HRegionInfo, ServerName> immediateAssignment(
List<HRegionInfo> regions, List<ServerName> servers); ServerName randomAssignment(List<ServerName> servers); }### Answer:
@Test public void testImmediateAssignment() throws Exception { for(int [] mock : regionsAndServersMocks) { LOG.debug("testImmediateAssignment with " + mock[0] + " regions and " + mock[1] + " servers"); List<HRegionInfo> regions = randomRegions(mock[0]); List<ServerAndLoad> servers = randomServers(mock[1], 0); List<ServerName> list = getListOfServerNames(servers); Map<HRegionInfo,ServerName> assignments = loadBalancer.immediateAssignment(regions, list); assertImmediateAssignment(regions, list, assignments); returnRegions(regions); returnServers(list); } }
|
### Question:
DefaultLoadBalancer implements LoadBalancer { public Map<ServerName, List<HRegionInfo>> roundRobinAssignment( List<HRegionInfo> regions, List<ServerName> servers) { if (regions.isEmpty() || servers.isEmpty()) { return null; } Map<ServerName, List<HRegionInfo>> assignments = new TreeMap<ServerName,List<HRegionInfo>>(); int numRegions = regions.size(); int numServers = servers.size(); int max = (int)Math.ceil((float)numRegions/numServers); int serverIdx = 0; if (numServers > 1) { serverIdx = RANDOM.nextInt(numServers); } int regionIdx = 0; for (int j = 0; j < numServers; j++) { ServerName server = servers.get((j + serverIdx) % numServers); List<HRegionInfo> serverRegions = new ArrayList<HRegionInfo>(max); for (int i=regionIdx; i<numRegions; i += numServers) { serverRegions.add(regions.get(i % numRegions)); } assignments.put(server, serverRegions); regionIdx++; } return assignments; } void setClusterStatus(ClusterStatus st); void setMasterServices(MasterServices masterServices); @Override void setConf(Configuration conf); @Override Configuration getConf(); List<RegionPlan> balanceCluster(
Map<ServerName, List<HRegionInfo>> clusterState); Map<ServerName, List<HRegionInfo>> roundRobinAssignment(
List<HRegionInfo> regions, List<ServerName> servers); Map<ServerName, List<HRegionInfo>> retainAssignment(
Map<HRegionInfo, ServerName> regions, List<ServerName> servers); Map<HRegionInfo, ServerName> immediateAssignment(
List<HRegionInfo> regions, List<ServerName> servers); ServerName randomAssignment(List<ServerName> servers); }### Answer:
@Test public void testBulkAssignment() throws Exception { for(int [] mock : regionsAndServersMocks) { LOG.debug("testBulkAssignment with " + mock[0] + " regions and " + mock[1] + " servers"); List<HRegionInfo> regions = randomRegions(mock[0]); List<ServerAndLoad> servers = randomServers(mock[1], 0); List<ServerName> list = getListOfServerNames(servers); Map<ServerName, List<HRegionInfo>> assignments = loadBalancer.roundRobinAssignment(regions, list); float average = (float)regions.size()/servers.size(); int min = (int)Math.floor(average); int max = (int)Math.ceil(average); if(assignments != null && !assignments.isEmpty()) { for(List<HRegionInfo> regionList : assignments.values()) { assertTrue(regionList.size() == min || regionList.size() == max); } } returnRegions(regions); returnServers(list); } }
|
### Question:
CleanerChore extends Chore { public boolean checkAndDeleteDirectory(Path toCheck) throws IOException { if (LOG.isTraceEnabled()) { LOG.trace("Checking directory: " + toCheck); } FileStatus[] children = FSUtils.listStatus(fs, toCheck, null); if (children == null) { try { return HBaseFileSystem.deleteFileFromFileSystem(fs, toCheck); } catch (IOException e) { if (LOG.isTraceEnabled()) { LOG.trace("Couldn't delete directory: " + toCheck, e); } } return false; } boolean canDeleteThis = true; for (FileStatus child : children) { Path path = child.getPath(); if (child.isDir()) { if (!checkAndDeleteDirectory(path)) { canDeleteThis = false; } } else if (!checkAndDelete(path)) { canDeleteThis = false; } } if (!canDeleteThis) return false; try { return HBaseFileSystem.deleteFileFromFileSystem(fs, toCheck); } catch (IOException e) { if (LOG.isTraceEnabled()) { LOG.trace("Couldn't delete directory: " + toCheck, e); } } return false; } CleanerChore(String name, final int sleepPeriod, final Stoppable s, Configuration conf,
FileSystem fs, Path oldFileDir, String confKey); T newFileCleaner(String className, Configuration conf); boolean checkAndDeleteDirectory(Path toCheck); @Override void cleanup(); }### Answer:
@Test public void testNoExceptionFromDirectoryWithRacyChildren() throws Exception { Stoppable stop = new StoppableImplementation(); HBaseTestingUtility localUtil = new HBaseTestingUtility(); Configuration conf = localUtil.getConfiguration(); final Path testDir = UTIL.getDataTestDir(); final FileSystem fs = UTIL.getTestFileSystem(); LOG.debug("Writing test data to: " + testDir); String confKey = "hbase.test.cleaner.delegates"; conf.set(confKey, AlwaysDelete.class.getName()); AllValidPaths chore = new AllValidPaths("test-file-cleaner", stop, conf, fs, testDir, confKey); AlwaysDelete delegate = (AlwaysDelete) chore.cleanersChain.get(0); AlwaysDelete spy = Mockito.spy(delegate); chore.cleanersChain.set(0, spy); final Path parent = new Path(testDir, "parent"); Path file = new Path(parent, "someFile"); fs.mkdirs(parent); fs.create(file).close(); assertTrue("Test file didn't get created.", fs.exists(file)); final Path racyFile = new Path(parent, "addedFile"); Mockito.doAnswer(new Answer<Boolean>() { @Override public Boolean answer(InvocationOnMock invocation) throws Throwable { fs.create(racyFile).close(); FSUtils.logFileSystemState(fs, testDir, LOG); return (Boolean) invocation.callRealMethod(); } }).when(spy).isFileDeletable(Mockito.any(Path.class)); if (chore.checkAndDeleteDirectory(parent)) { throw new Exception( "Reported success deleting directory, should have failed when adding file mid-iteration"); } assertTrue("Added file unexpectedly deleted", fs.exists(racyFile)); assertTrue("Parent directory deleted unexpectedly", fs.exists(parent)); assertFalse("Original file unexpectedly retained", fs.exists(file)); Mockito.verify(spy, Mockito.times(1)).isFileDeletable(Mockito.any(Path.class)); }
|
### Question:
SnapshotLogCleaner extends BaseLogCleanerDelegate { @Override public void setConf(Configuration conf) { super.setConf(conf); try { long cacheRefreshPeriod = conf.getLong( HLOG_CACHE_REFRESH_PERIOD_CONF_KEY, DEFAULT_HLOG_CACHE_REFRESH_PERIOD); final FileSystem fs = FSUtils.getCurrentFileSystem(conf); Path rootDir = FSUtils.getRootDir(conf); cache = new SnapshotFileCache(fs, rootDir, cacheRefreshPeriod, cacheRefreshPeriod, "snapshot-log-cleaner-cache-refresher", new SnapshotFileCache.SnapshotFileInspector() { public Collection<String> filesUnderSnapshot(final Path snapshotDir) throws IOException { return SnapshotReferenceUtil.getHLogNames(fs, snapshotDir); } }); } catch (IOException e) { LOG.error("Failed to create snapshot log cleaner", e); } } @Override synchronized boolean isLogDeletable(Path filePath); @Override void setConf(Configuration conf); @Override void stop(String why); @Override boolean isStopped(); }### Answer:
@Test public void testFindsSnapshotFilesWhenCleaning() throws IOException { Configuration conf = TEST_UTIL.getConfiguration(); FSUtils.setRootDir(conf, TEST_UTIL.getDataTestDir()); Path rootDir = FSUtils.getRootDir(conf); FileSystem fs = FileSystem.get(conf); SnapshotLogCleaner cleaner = new SnapshotLogCleaner(); cleaner.setConf(conf); String snapshotName = "snapshot"; byte[] snapshot = Bytes.toBytes(snapshotName); Path snapshotDir = SnapshotDescriptionUtils.getCompletedSnapshotDir(snapshotName, rootDir); Path snapshotLogDir = new Path(snapshotDir, HConstants.HREGION_LOGDIR_NAME); String timestamp = "1339643343027"; String hostFromMaster = "localhost%2C59648%2C1339643336601"; Path hostSnapshotLogDir = new Path(snapshotLogDir, hostFromMaster); String snapshotlogfile = hostFromMaster + "." + timestamp + ".hbase"; fs.create(new Path(hostSnapshotLogDir, snapshotlogfile)); Path oldlogDir = new Path(rootDir, ".oldlogs"); Path logFile = new Path(oldlogDir, snapshotlogfile); fs.create(logFile); assertFalse(cleaner.isFileDeletable(logFile)); }
|
### Question:
SplitTransaction { public boolean prepare() { if (!this.parent.isSplittable()) return false; if (this.splitrow == null) return false; HRegionInfo hri = this.parent.getRegionInfo(); parent.prepareToSplit(); byte [] startKey = hri.getStartKey(); byte [] endKey = hri.getEndKey(); if (Bytes.equals(startKey, splitrow) || !this.parent.getRegionInfo().containsRow(splitrow)) { LOG.info("Split row is not inside region key range or is equal to " + "startkey: " + Bytes.toStringBinary(this.splitrow)); return false; } long rid = getDaughterRegionIdTimestamp(hri); this.hri_a = new HRegionInfo(hri.getTableName(), startKey, this.splitrow, false, rid); this.hri_b = new HRegionInfo(hri.getTableName(), this.splitrow, endKey, false, rid); return true; } SplitTransaction(final HRegion r, final byte [] splitrow); boolean prepare(); PairOfSameType<HRegion> execute(final Server server,
final RegionServerServices services); boolean rollback(final Server server, final RegionServerServices services); }### Answer:
@Test public void testPrepare() throws IOException { prepareGOOD_SPLIT_ROW(); }
@Test public void testPrepareWithRegionsWithReference() throws IOException { StoreFile storeFileMock = Mockito.mock(StoreFile.class); when(storeFileMock.isReference()).thenReturn(true); Store storeMock = Mockito.mock(Store.class); List<StoreFile> storeFileList = new ArrayList<StoreFile>(1); storeFileList.add(storeFileMock); when(storeMock.getStorefiles()).thenReturn(storeFileList); when(storeMock.close()).thenReturn(ImmutableList.copyOf(storeFileList)); this.parent.stores.put(Bytes.toBytes(""), storeMock); SplitTransaction st = new SplitTransaction(this.parent, GOOD_SPLIT_ROW); assertFalse("a region should not be splittable if it has instances of store file references", st.prepare()); }
@Test public void testPrepareWithBadSplitRow() throws IOException { SplitTransaction st = new SplitTransaction(this.parent, STARTROW); assertFalse(st.prepare()); st = new SplitTransaction(this.parent, HConstants.EMPTY_BYTE_ARRAY); assertFalse(st.prepare()); st = new SplitTransaction(this.parent, new byte [] {'A', 'A', 'A'}); assertFalse(st.prepare()); st = new SplitTransaction(this.parent, ENDROW); assertFalse(st.prepare()); }
@Test public void testPrepareWithClosedRegion() throws IOException { this.parent.close(); SplitTransaction st = new SplitTransaction(this.parent, GOOD_SPLIT_ROW); assertFalse(st.prepare()); }
|
### Question:
SplitTransaction { public boolean rollback(final Server server, final RegionServerServices services) throws IOException { boolean result = true; FileSystem fs = this.parent.getFilesystem(); ListIterator<JournalEntry> iterator = this.journal.listIterator(this.journal.size()); while (iterator.hasPrevious()) { JournalEntry je = iterator.previous(); switch(je) { case SET_SPLITTING_IN_ZK: if (server != null && server.getZooKeeper() != null) { cleanZK(server, this.parent.getRegionInfo()); } break; case CREATE_SPLIT_DIR: this.parent.writestate.writesEnabled = true; cleanupSplitDir(fs, this.splitdir); break; case CLOSED_PARENT_REGION: try { this.parent.initialize(); } catch (IOException e) { LOG.error("Failed rollbacking CLOSED_PARENT_REGION of region " + this.parent.getRegionNameAsString(), e); throw new RuntimeException(e); } break; case STARTED_REGION_A_CREATION: cleanupDaughterRegion(fs, this.parent.getTableDir(), this.hri_a.getEncodedName()); break; case STARTED_REGION_B_CREATION: cleanupDaughterRegion(fs, this.parent.getTableDir(), this.hri_b.getEncodedName()); break; case OFFLINED_PARENT: if (services != null) services.addToOnlineRegions(this.parent); break; case PONR: return false; default: throw new RuntimeException("Unhandled journal entry: " + je); } } return result; } SplitTransaction(final HRegion r, final byte [] splitrow); boolean prepare(); PairOfSameType<HRegion> execute(final Server server,
final RegionServerServices services); boolean rollback(final Server server, final RegionServerServices services); }### Answer:
@Test public void testRollback() throws IOException { final int rowcount = TEST_UTIL.loadRegion(this.parent, CF); assertTrue(rowcount > 0); int parentRowCount = countRows(this.parent); assertEquals(rowcount, parentRowCount); SplitTransaction st = prepareGOOD_SPLIT_ROW(); SplitTransaction spiedUponSt = spy(st); when(spiedUponSt.createDaughterRegion(spiedUponSt.getSecondDaughter(), null)). thenThrow(new MockedFailedDaughterCreation()); boolean expectedException = false; Server mockServer = Mockito.mock(Server.class); when(mockServer.getConfiguration()).thenReturn(TEST_UTIL.getConfiguration()); try { spiedUponSt.execute(mockServer, null); } catch (MockedFailedDaughterCreation e) { expectedException = true; } assertTrue(expectedException); assertTrue(spiedUponSt.rollback(null, null)); int parentRowCount2 = countRows(this.parent); assertEquals(parentRowCount, parentRowCount2); assertTrue(!this.fs.exists(HRegion.getRegionDir(this.testdir, st.getFirstDaughter()))); assertTrue(!this.fs.exists(HRegion.getRegionDir(this.testdir, st.getSecondDaughter()))); assertTrue(!this.parent.lock.writeLock().isHeldByCurrentThread()); assertTrue(st.prepare()); PairOfSameType<HRegion> daughters = st.execute(mockServer, null); int daughtersRowCount = 0; for (HRegion r: daughters) { HRegion openRegion = HRegion.openHRegion(this.testdir, r.getRegionInfo(), r.getTableDesc(), r.getLog(), r.getConf()); try { int count = countRows(openRegion); assertTrue(count > 0 && count != rowcount); daughtersRowCount += count; } finally { openRegion.close(); openRegion.getLog().closeAndDelete(); } } assertEquals(rowcount, daughtersRowCount); assertTrue(!this.parent.lock.writeLock().isHeldByCurrentThread()); }
|
### Question:
SchemaMetrics { public static String generateSchemaMetricsPrefix(String tableName, final String cfName) { tableName = getEffectiveTableName(tableName); String schemaMetricPrefix = tableName.equals(TOTAL_KEY) ? "" : TABLE_PREFIX + tableName + "."; schemaMetricPrefix += cfName.equals(TOTAL_KEY) ? "" : CF_PREFIX + cfName + "."; return schemaMetricPrefix; } private SchemaMetrics(final String tableName, final String cfName); static SchemaMetrics getInstance(String tableName, String cfName); String getBlockMetricName(BlockCategory blockCategory,
boolean isCompaction, BlockMetricType metricType); String getBloomMetricName(boolean isInBloom); void accumulateStoreMetric(final Map<String, MutableDouble> tmpMap,
StoreMetricType storeMetricType, double val); String getStoreMetricName(StoreMetricType storeMetricType); String getStoreMetricNameMax(StoreMetricType storeMetricType); void updatePersistentStoreMetric(StoreMetricType storeMetricType,
long value); void updateOnCacheHit(BlockCategory blockCategory,
boolean isCompaction); void updateOnCacheHit(BlockCategory blockCategory,
boolean isCompaction, long count); void flushMetrics(); void updateOnCacheMiss(BlockCategory blockCategory,
boolean isCompaction, long timeMs); void addToCacheSize(BlockCategory category, long cacheSizeDelta); void updateOnCachePutOrEvict(BlockCategory blockCategory,
long cacheSizeDelta, boolean isEviction); void updateBloomMetrics(boolean isInBloom); static void configureGlobally(Configuration conf); static String generateSchemaMetricsPrefix(String tableName,
final String cfName); static String generateSchemaMetricsPrefix(byte[] tableName,
byte[] cfName); static String generateSchemaMetricsPrefix(String tableName,
Set<byte[]> families); static Map<String, Long> getMetricsSnapshot(); static long getLong(Map<String, Long> m, String k); static Map<String, Long> diffMetrics(Map<String, Long> a,
Map<String, Long> b); static void validateMetricChanges(Map<String, Long> oldMetrics); static SchemaMetrics getUnknownInstanceForTest(); static void setUseTableNameInTest(final boolean useTableNameNew); static String formatMetrics(Map<String, Long> metrics); static final String UNKNOWN; static final String TABLE_PREFIX; static final String CF_PREFIX; static final String BLOCK_TYPE_PREFIX; static final String REGION_PREFIX; static final String CF_UNKNOWN_PREFIX; static final String CF_BAD_FAMILY_PREFIX; static final boolean NO_COMPACTION; static final String METRIC_GETSIZE; static final String METRIC_NEXTSIZE; static final String TOTAL_KEY; static final SchemaMetrics ALL_SCHEMA_METRICS; }### Answer:
@Test public void testGenerateSchemaMetricsPrefix() { String tableName = "table1"; int numCF = 3; StringBuilder expected = new StringBuilder(); if (useTableName) { expected.append("tbl."); expected.append(tableName); expected.append("."); } expected.append("cf."); Set<byte[]> families = new HashSet<byte[]>(); for (int i = 1; i <= numCF; i++) { String cf = "cf" + i; families.add(Bytes.toBytes(cf)); expected.append(cf); if (i == numCF) { expected.append("."); } else { expected.append("~"); } } String result = SchemaMetrics.generateSchemaMetricsPrefix(tableName, families); assertEquals(expected.toString(), result); }
|
### Question:
SchemaConfigured implements HeapSize, SchemaAware { public String schemaConfAsJSON() { return "{\"tableName\":\"" + tableName + "\",\"cfName\":\"" + cfName + "\"}"; } private SchemaConfigured(Configuration conf); SchemaConfigured(); SchemaConfigured(Configuration conf, Path path); SchemaConfigured(Path path); SchemaConfigured(Configuration conf, String tableName, String cfName); SchemaConfigured(SchemaAware that); static SchemaConfigured createUnknown(); @Override String getTableName(); @Override String getColumnFamilyName(); @Override SchemaMetrics getSchemaMetrics(); void passSchemaMetricsTo(SchemaConfigured target); static void resetSchemaMetricsConf(SchemaConfigured target); @Override long heapSize(); String schemaConfAsJSON(); static final int SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE; }### Answer:
@Test public void testToString() throws JSONException { SchemaConfigured sc = new SchemaConfigured(null, TABLE_NAME, CF_NAME); JSONStringer json = new JSONStringer(); json.object(); json.key("tableName"); json.value(TABLE_NAME); json.key("cfName"); json.value(CF_NAME); json.endObject(); assertEquals(json.toString(), sc.schemaConfAsJSON()); }
|
### Question:
SchemaConfigured implements HeapSize, SchemaAware { public void passSchemaMetricsTo(SchemaConfigured target) { if (isNull()) { resetSchemaMetricsConf(target); return; } if (!isSchemaConfigured()) { throw new IllegalStateException("Table name/CF not initialized: " + schemaConfAsJSON()); } if (conflictingWith(target)) { throw new IllegalArgumentException("Trying to change table name to \"" + tableName + "\", CF name to \"" + cfName + "\" from " + target.schemaConfAsJSON()); } target.tableName = tableName.intern(); target.cfName = cfName.intern(); target.schemaMetrics = schemaMetrics; target.schemaConfigurationChanged(); } private SchemaConfigured(Configuration conf); SchemaConfigured(); SchemaConfigured(Configuration conf, Path path); SchemaConfigured(Path path); SchemaConfigured(Configuration conf, String tableName, String cfName); SchemaConfigured(SchemaAware that); static SchemaConfigured createUnknown(); @Override String getTableName(); @Override String getColumnFamilyName(); @Override SchemaMetrics getSchemaMetrics(); void passSchemaMetricsTo(SchemaConfigured target); static void resetSchemaMetricsConf(SchemaConfigured target); @Override long heapSize(); String schemaConfAsJSON(); static final int SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE; }### Answer:
@Test(expected=IllegalStateException.class) public void testConfigureWithUnconfigured1() { SchemaConfigured unconfigured = new SchemaConfigured(null, "t1", null); SchemaConfigured target = new SchemaConfigured(); unconfigured.passSchemaMetricsTo(target); }
@Test(expected=IllegalStateException.class) public void testConfigureWithUnconfigured2() { SchemaConfigured unconfigured = new SchemaConfigured(null, null, "cf1"); SchemaConfigured target = new SchemaConfigured(); unconfigured.passSchemaMetricsTo(target); }
@Test(expected=IllegalArgumentException.class) public void testConflictingConf() { SchemaConfigured sc = new SchemaConfigured(null, "t1", "cf1"); SchemaConfigured target = new SchemaConfigured(null, "t2", "cf1"); sc.passSchemaMetricsTo(target); }
@Test public void testTmpPath() { SchemaConfigured sc = new SchemaConfigured(null, "myTable", "myCF"); SchemaConfigured target = new SchemaConfigured(TMP_HFILE_PATH); sc.passSchemaMetricsTo(target); }
@Test(expected=IllegalArgumentException.class) public void testTmpPathButInvalidTable() { SchemaConfigured sc = new SchemaConfigured(null, "anotherTable", "myCF"); SchemaConfigured target = new SchemaConfigured(TMP_HFILE_PATH); sc.passSchemaMetricsTo(target); }
|
### Question:
SchemaConfigured implements HeapSize, SchemaAware { public static void resetSchemaMetricsConf(SchemaConfigured target) { target.tableName = null; target.cfName = null; target.schemaMetrics = null; target.schemaConfigurationChanged(); } private SchemaConfigured(Configuration conf); SchemaConfigured(); SchemaConfigured(Configuration conf, Path path); SchemaConfigured(Path path); SchemaConfigured(Configuration conf, String tableName, String cfName); SchemaConfigured(SchemaAware that); static SchemaConfigured createUnknown(); @Override String getTableName(); @Override String getColumnFamilyName(); @Override SchemaMetrics getSchemaMetrics(); void passSchemaMetricsTo(SchemaConfigured target); static void resetSchemaMetricsConf(SchemaConfigured target); @Override long heapSize(); String schemaConfAsJSON(); static final int SCHEMA_CONFIGURED_UNALIGNED_HEAP_SIZE; }### Answer:
@Test public void testResetSchemaMetricsConf() { SchemaConfigured target = new SchemaConfigured(null, "t1", "cf1"); SchemaConfigured.resetSchemaMetricsConf(target); new SchemaConfigured(null, "t2", "cf2").passSchemaMetricsTo(target); assertEquals("t2", target.getTableName()); assertEquals("cf2", target.getColumnFamilyName()); }
|
### Question:
ExecutorService { public ExecutorService(final String servername) { super(); this.servername = servername; } ExecutorService(final String servername); ExecutorType getExecutorServiceType(final EventHandler.EventType type); void shutdown(); void startExecutorService(final ExecutorType type, final int maxThreads); void submit(final EventHandler eh); void registerListener(final EventHandler.EventType type,
final EventHandlerListener listener); EventHandlerListener unregisterListener(final EventHandler.EventType type); Map<String, ExecutorStatus> getAllExecutorStatuses(); }### Answer:
@Test public void testExecutorService() throws Exception { int maxThreads = 5; int maxTries = 10; int sleepInterval = 10; Server mockedServer = mock(Server.class); when(mockedServer.getConfiguration()).thenReturn(HBaseConfiguration.create()); ExecutorService executorService = new ExecutorService("unit_test"); executorService.startExecutorService( ExecutorType.MASTER_SERVER_OPERATIONS, maxThreads); Executor executor = executorService.getExecutor(ExecutorType.MASTER_SERVER_OPERATIONS); ThreadPoolExecutor pool = executor.threadPoolExecutor; assertEquals(0, pool.getPoolSize()); AtomicBoolean lock = new AtomicBoolean(true); AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < maxThreads; i++) { executorService.submit( new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); } int tries = 0; while (counter.get() < maxThreads && tries < maxTries) { LOG.info("Waiting for all event handlers to start..."); Thread.sleep(sleepInterval); tries++; } assertEquals(maxThreads, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); ExecutorStatus status = executor.getStatus(); assertTrue(status.queuedEvents.isEmpty()); assertEquals(5, status.running.size()); checkStatusDump(status); synchronized (lock) { lock.set(false); lock.notifyAll(); } while (counter.get() < (maxThreads * 2) && tries < maxTries) { System.out.println("Waiting for all event handlers to finish..."); Thread.sleep(sleepInterval); tries++; } assertEquals(maxThreads * 2, counter.get()); assertEquals(maxThreads, pool.getPoolSize()); for (int i = 0; i < (2 * maxThreads); i++) { executorService.submit( new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); } synchronized (lock) { lock.set(false); lock.notifyAll(); } Thread.sleep(executor.keepAliveTimeInMillis * 2); assertEquals(maxThreads, pool.getPoolSize()); executorService.shutdown(); assertEquals(0, executorService.getAllExecutorStatuses().size()); executorService.submit( new TestEventHandler(mockedServer, EventType.M_SERVER_SHUTDOWN, lock, counter)); }
|
### Question:
RegionSplitPolicy extends Configured { public static RegionSplitPolicy create(HRegion region, Configuration conf) throws IOException { Class<? extends RegionSplitPolicy> clazz = getSplitPolicyClass( region.getTableDesc(), conf); RegionSplitPolicy policy = ReflectionUtils.newInstance(clazz, conf); policy.configureForRegion(region); return policy; } static RegionSplitPolicy create(HRegion region,
Configuration conf); }### Answer:
@Test public void testCreateDefault() throws IOException { conf.setLong(HConstants.HREGION_MAX_FILESIZE, 1234L); ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create( mockRegion, conf); assertEquals(1234L, policy.getDesiredMaxFileSize()); htd.setMaxFileSize(9999L); policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create( mockRegion, conf); assertEquals(9999L, policy.getDesiredMaxFileSize()); }
@Test public void testConstantSizePolicy() throws IOException { htd.setMaxFileSize(1024L); ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); doConstantSizePolicyTests(policy); }
|
### Question:
RegionSplitPolicy extends Configured { protected byte[] getSplitPoint() { byte[] explicitSplitPoint = this.region.getExplicitSplitPoint(); if (explicitSplitPoint != null) { return explicitSplitPoint; } Map<byte[], Store> stores = region.getStores(); byte[] splitPointFromLargestStore = null; long largestStoreSize = 0; for (Store s : stores.values()) { byte[] splitPoint = s.getSplitPoint(); long storeSize = s.getSize(); if (splitPoint != null && largestStoreSize < storeSize) { splitPointFromLargestStore = splitPoint; largestStoreSize = storeSize; } } return splitPointFromLargestStore; } static RegionSplitPolicy create(HRegion region,
Configuration conf); }### Answer:
@Test public void testGetSplitPoint() throws IOException { ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); assertFalse(policy.shouldSplit()); assertNull(policy.getSplitPoint()); Store mockStore = Mockito.mock(Store.class); Mockito.doReturn(2000L).when(mockStore).getSize(); Mockito.doReturn(true).when(mockStore).canSplit(); Mockito.doReturn(Bytes.toBytes("store 1 split")) .when(mockStore).getSplitPoint(); stores.put(new byte[]{1}, mockStore); assertEquals("store 1 split", Bytes.toString(policy.getSplitPoint())); Store mockStore2 = Mockito.mock(Store.class); Mockito.doReturn(4000L).when(mockStore2).getSize(); Mockito.doReturn(true).when(mockStore2).canSplit(); Mockito.doReturn(Bytes.toBytes("store 2 split")) .when(mockStore2).getSplitPoint(); stores.put(new byte[]{2}, mockStore2); assertEquals("store 2 split", Bytes.toString(policy.getSplitPoint())); }
@Test public void testGetSplitPoint() throws IOException { ConstantSizeRegionSplitPolicy policy = (ConstantSizeRegionSplitPolicy)RegionSplitPolicy.create(mockRegion, conf); assertFalse(policy.shouldSplit()); assertNull(policy.getSplitPoint()); HStore mockStore = Mockito.mock(HStore.class); Mockito.doReturn(2000L).when(mockStore).getSize(); Mockito.doReturn(true).when(mockStore).canSplit(); Mockito.doReturn(Bytes.toBytes("store 1 split")) .when(mockStore).getSplitPoint(); stores.put(new byte[]{1}, mockStore); assertEquals("store 1 split", Bytes.toString(policy.getSplitPoint())); HStore mockStore2 = Mockito.mock(HStore.class); Mockito.doReturn(4000L).when(mockStore2).getSize(); Mockito.doReturn(true).when(mockStore2).canSplit(); Mockito.doReturn(Bytes.toBytes("store 2 split")) .when(mockStore2).getSplitPoint(); stores.put(new byte[]{2}, mockStore2); assertEquals("store 2 split", Bytes.toString(policy.getSplitPoint())); }
|
### Question:
LRUDictionary implements Dictionary { @Override public short addEntry(byte[] data, int offset, int length) { if (length <= 0) return NOT_IN_DICTIONARY; return backingStore.put(data, offset, length); } @Override byte[] getEntry(short idx); @Override short findEntry(byte[] data, int offset, int length); @Override short addEntry(byte[] data, int offset, int length); @Override void clear(); }### Answer:
@Test public void testPassingSameArrayToAddEntry() { int len = HConstants.CATALOG_FAMILY.length; int index = testee.addEntry(HConstants.CATALOG_FAMILY, 0, len); assertFalse(index == testee.addEntry(HConstants.CATALOG_FAMILY, 0, len)); assertFalse(index == testee.addEntry(HConstants.CATALOG_FAMILY, 0, len)); }
|
### Question:
FSTableDescriptors implements TableDescriptors { static int getTableInfoSequenceid(final Path p) { if (p == null) return 0; Matcher m = SUFFIX.matcher(p.getName()); if (!m.matches()) throw new IllegalArgumentException(p.toString()); String suffix = m.group(2); if (suffix == null || suffix.length() <= 0) return 0; return Integer.parseInt(m.group(2)); } FSTableDescriptors(final FileSystem fs, final Path rootdir); FSTableDescriptors(final FileSystem fs, final Path rootdir,
final boolean fsreadOnly); @Override HTableDescriptor get(final byte [] tablename); @Override HTableDescriptor get(final String tablename); @Override Map<String, HTableDescriptor> getAll(); @Override void add(HTableDescriptor htd); @Override HTableDescriptor remove(final String tablename); static boolean isTableInfoExists(FileSystem fs, Path rootdir,
String tableName); static FileStatus getTableInfoPath(final FileSystem fs,
final Path tabledir); static HTableDescriptor getTableDescriptor(FileSystem fs,
Path hbaseRootDir, byte[] tableName); static HTableDescriptor getTableDescriptor(FileSystem fs, Path tableDir); static void deleteTableDescriptorIfExists(String tableName,
Configuration conf); static boolean createTableDescriptor(final HTableDescriptor htableDescriptor,
Configuration conf); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor, boolean forceCreation); static boolean createTableDescriptorForTableDirectory(FileSystem fs, Path tabledir,
HTableDescriptor htableDescriptor, boolean forceCreation); static final String TABLEINFO_NAME; }### Answer:
@Test (expected=IllegalArgumentException.class) public void testRegexAgainstOldStyleTableInfo() { Path p = new Path("/tmp", FSTableDescriptors.TABLEINFO_NAME); int i = FSTableDescriptors.getTableInfoSequenceid(p); assertEquals(0, i); p = new Path("/tmp", "abc"); FSTableDescriptors.getTableInfoSequenceid(p); }
|
### Question:
LRUDictionary implements Dictionary { @Override public short findEntry(byte[] data, int offset, int length) { short ret = backingStore.findIdx(data, offset, length); if (ret == NOT_IN_DICTIONARY) { addEntry(data, offset, length); } return ret; } @Override byte[] getEntry(short idx); @Override short findEntry(byte[] data, int offset, int length); @Override short addEntry(byte[] data, int offset, int length); @Override void clear(); }### Answer:
@Test public void TestLRUPolicy(){ for (int i = 0; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { testee.findEntry((BigInteger.valueOf(i)).toByteArray(), 0, (BigInteger.valueOf(i)).toByteArray().length); } assertTrue(testee.findEntry(BigInteger.ZERO.toByteArray(), 0, BigInteger.ZERO.toByteArray().length) != -1); assertTrue(testee.findEntry(BigInteger.valueOf(Integer.MAX_VALUE).toByteArray(), 0, BigInteger.valueOf(Integer.MAX_VALUE).toByteArray().length) == -1); assertTrue(testee.findEntry(BigInteger.valueOf(Integer.MAX_VALUE).toByteArray(), 0, BigInteger.valueOf(Integer.MAX_VALUE).toByteArray().length) != -1); assertTrue(testee.findEntry(BigInteger.ZERO.toByteArray(), 0, BigInteger.ZERO.toByteArray().length) != -1); for(int i = 1; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { assertTrue(testee.findEntry(BigInteger.valueOf(i).toByteArray(), 0, BigInteger.valueOf(i).toByteArray().length) == -1); } for (int i = 0; i < LRUDictionary.BidirectionalLRUMap.MAX_SIZE; i++) { assertTrue(testee.findEntry(BigInteger.valueOf(i).toByteArray(), 0, BigInteger.valueOf(i).toByteArray().length) != -1); } }
|
### Question:
SnapshotTask implements ForeignExceptionSnare, Callable<Void> { public void snapshotFailure(String message, Exception e) { ForeignException ee = new ForeignException(message, e); errorMonitor.receive(ee); } SnapshotTask(SnapshotDescription snapshot, ForeignExceptionDispatcher monitor); void snapshotFailure(String message, Exception e); @Override void rethrowException(); @Override boolean hasException(); @Override ForeignException getException(); }### Answer:
@Test public void testErrorPropagation() throws Exception { ForeignExceptionDispatcher error = mock(ForeignExceptionDispatcher.class); SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("snapshot") .setTable("table").build(); final Exception thrown = new Exception("Failed!"); SnapshotTask fail = new SnapshotTask(snapshot, error) { @Override public Void call() { snapshotFailure("Injected failure", thrown); return null; } }; fail.call(); verify(error, Mockito.times(1)).receive(any(ForeignException.class)); }
|
### Question:
ExportSnapshot extends Configured implements Tool { static List<List<Path>> getBalancedSplits(final List<Pair<Path, Long>> files, int ngroups) { Collections.sort(files, new Comparator<Pair<Path, Long>>() { public int compare(Pair<Path, Long> a, Pair<Path, Long> b) { long r = a.getSecond() - b.getSecond(); return (r < 0) ? -1 : ((r > 0) ? 1 : 0); } }); List<List<Path>> fileGroups = new LinkedList<List<Path>>(); long[] sizeGroups = new long[ngroups]; int hi = files.size() - 1; int lo = 0; List<Path> group; int dir = 1; int g = 0; while (hi >= lo) { if (g == fileGroups.size()) { group = new LinkedList<Path>(); fileGroups.add(group); } else { group = fileGroups.get(g); } Pair<Path, Long> fileInfo = files.get(hi--); sizeGroups[g] += fileInfo.getSecond(); group.add(fileInfo.getFirst()); g += dir; if (g == ngroups) { dir = -1; g = ngroups - 1; } else if (g < 0) { dir = 1; g = 0; } } if (LOG.isDebugEnabled()) { for (int i = 0; i < sizeGroups.length; ++i) { LOG.debug("export split=" + i + " size=" + StringUtils.humanReadableInt(sizeGroups[i])); } } return fileGroups; } @Override int run(String[] args); static void main(String[] args); }### Answer:
@Test public void testBalanceSplit() throws Exception { List<Pair<Path, Long>> files = new ArrayList<Pair<Path, Long>>(); for (long i = 0; i <= 20; i++) { files.add(new Pair<Path, Long>(new Path("file-" + i), i)); } List<List<Path>> splits = ExportSnapshot.getBalancedSplits(files, 5); assertEquals(5, splits.size()); assertEquals(Arrays.asList(new Path("file-20"), new Path("file-11"), new Path("file-10"), new Path("file-1"), new Path("file-0")), splits.get(0)); assertEquals(Arrays.asList(new Path("file-19"), new Path("file-12"), new Path("file-9"), new Path("file-2")), splits.get(1)); assertEquals(Arrays.asList(new Path("file-18"), new Path("file-13"), new Path("file-8"), new Path("file-3")), splits.get(2)); assertEquals(Arrays.asList(new Path("file-17"), new Path("file-14"), new Path("file-7"), new Path("file-4")), splits.get(3)); assertEquals(Arrays.asList(new Path("file-16"), new Path("file-15"), new Path("file-6"), new Path("file-5")), splits.get(4)); }
|
### Question:
SnapshotDescriptionUtils { public static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf) throws IllegalArgumentException { if (!snapshot.hasTable()) { throw new IllegalArgumentException( "Descriptor doesn't apply to a table, so we can't build it."); } long time = snapshot.getCreationTime(); if (time == SnapshotDescriptionUtils.NO_SNAPSHOT_START_TIME_SPECIFIED) { time = EnvironmentEdgeManager.currentTimeMillis(); LOG.debug("Creation time not specified, setting to:" + time + " (current time:" + EnvironmentEdgeManager.currentTimeMillis() + ")."); SnapshotDescription.Builder builder = snapshot.toBuilder(); builder.setCreationTime(time); snapshot = builder.build(); } return snapshot; } private SnapshotDescriptionUtils(); static void assertSnapshotRequestIsValid(SnapshotDescription snapshot); static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type,
long defaultMaxWaitTime); static Path getSnapshotRootDir(final Path rootDir); static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir); static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir); static Path getWorkingSnapshotDir(final Path rootDir); static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir); static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir); static final Path getSnapshotsDir(Path rootDir); static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf); static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs); static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir); static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
FileSystem fs); static String toString(SnapshotDescription ssd); static final int SNAPSHOT_LAYOUT_VERSION; static final String SNAPSHOTINFO_FILE; static final String SNAPSHOT_TMP_DIR_NAME; static final long NO_SNAPSHOT_START_TIME_SPECIFIED; static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS; static final long DEFAULT_MAX_WAIT_TIME; }### Answer:
@Test public void testValidateMissingTableName() { Configuration conf = new Configuration(false); try { SnapshotDescriptionUtils.validate(SnapshotDescription.newBuilder().setName("fail").build(), conf); fail("Snapshot was considered valid without a table name"); } catch (IllegalArgumentException e) { LOG.debug("Correctly failed when snapshot doesn't have a tablename"); } }
|
### Question:
FSTableDescriptors implements TableDescriptors { static String formatTableInfoSequenceId(final int number) { byte [] b = new byte[WIDTH_OF_SEQUENCE_ID]; int d = Math.abs(number); for (int i = b.length - 1; i >= 0; i--) { b[i] = (byte)((d % 10) + '0'); d /= 10; } return Bytes.toString(b); } FSTableDescriptors(final FileSystem fs, final Path rootdir); FSTableDescriptors(final FileSystem fs, final Path rootdir,
final boolean fsreadOnly); @Override HTableDescriptor get(final byte [] tablename); @Override HTableDescriptor get(final String tablename); @Override Map<String, HTableDescriptor> getAll(); @Override void add(HTableDescriptor htd); @Override HTableDescriptor remove(final String tablename); static boolean isTableInfoExists(FileSystem fs, Path rootdir,
String tableName); static FileStatus getTableInfoPath(final FileSystem fs,
final Path tabledir); static HTableDescriptor getTableDescriptor(FileSystem fs,
Path hbaseRootDir, byte[] tableName); static HTableDescriptor getTableDescriptor(FileSystem fs, Path tableDir); static void deleteTableDescriptorIfExists(String tableName,
Configuration conf); static boolean createTableDescriptor(final HTableDescriptor htableDescriptor,
Configuration conf); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor, boolean forceCreation); static boolean createTableDescriptorForTableDirectory(FileSystem fs, Path tabledir,
HTableDescriptor htableDescriptor, boolean forceCreation); static final String TABLEINFO_NAME; }### Answer:
@Test public void testFormatTableInfoSequenceId() { Path p0 = assertWriteAndReadSequenceid(0); StringBuilder sb = new StringBuilder(); for (int i = 0; i < FSTableDescriptors.WIDTH_OF_SEQUENCE_ID; i++) { sb.append("0"); } assertEquals(FSTableDescriptors.TABLEINFO_NAME + "." + sb.toString(), p0.getName()); Path p2 = assertWriteAndReadSequenceid(2); Path p10000 = assertWriteAndReadSequenceid(10000); Path p = new Path(p0.getParent(), FSTableDescriptors.TABLEINFO_NAME); FileStatus fs = new FileStatus(0, false, 0, 0, 0, p); FileStatus fs0 = new FileStatus(0, false, 0, 0, 0, p0); FileStatus fs2 = new FileStatus(0, false, 0, 0, 0, p2); FileStatus fs10000 = new FileStatus(0, false, 0, 0, 0, p10000); FSTableDescriptors.FileStatusFileNameComparator comparator = new FSTableDescriptors.FileStatusFileNameComparator(); assertTrue(comparator.compare(fs, fs0) > 0); assertTrue(comparator.compare(fs0, fs2) > 0); assertTrue(comparator.compare(fs2, fs10000) > 0); }
|
### Question:
SnapshotDescriptionUtils { public static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir, FileSystem fs) throws SnapshotCreationException, IOException { Path finishedDir = getCompletedSnapshotDir(snapshot, rootdir); LOG.debug("Snapshot is done, just moving the snapshot from " + workingDir + " to " + finishedDir); if (!fs.rename(workingDir, finishedDir)) { throw new SnapshotCreationException("Failed to move working directory(" + workingDir + ") to completed directory(" + finishedDir + ").", snapshot); } } private SnapshotDescriptionUtils(); static void assertSnapshotRequestIsValid(SnapshotDescription snapshot); static long getMaxMasterTimeout(Configuration conf, SnapshotDescription.Type type,
long defaultMaxWaitTime); static Path getSnapshotRootDir(final Path rootDir); static Path getCompletedSnapshotDir(final SnapshotDescription snapshot, final Path rootDir); static Path getCompletedSnapshotDir(final String snapshotName, final Path rootDir); static Path getWorkingSnapshotDir(final Path rootDir); static Path getWorkingSnapshotDir(SnapshotDescription snapshot, final Path rootDir); static Path getWorkingSnapshotDir(String snapshotName, final Path rootDir); static final Path getSnapshotsDir(Path rootDir); static SnapshotDescription validate(SnapshotDescription snapshot, Configuration conf); static void writeSnapshotInfo(SnapshotDescription snapshot, Path workingDir, FileSystem fs); static SnapshotDescription readSnapshotInfo(FileSystem fs, Path snapshotDir); static void completeSnapshot(SnapshotDescription snapshot, Path rootdir, Path workingDir,
FileSystem fs); static String toString(SnapshotDescription ssd); static final int SNAPSHOT_LAYOUT_VERSION; static final String SNAPSHOTINFO_FILE; static final String SNAPSHOT_TMP_DIR_NAME; static final long NO_SNAPSHOT_START_TIME_SPECIFIED; static final String MASTER_SNAPSHOT_TIMEOUT_MILLIS; static final long DEFAULT_MAX_WAIT_TIME; }### Answer:
@Test public void testCompleteSnapshotWithNoSnapshotDirectoryFailure() throws Exception { Path snapshotDir = new Path(root, ".snapshot"); Path tmpDir = new Path(snapshotDir, ".tmp"); Path workingDir = new Path(tmpDir, "not_a_snapshot"); assertFalse("Already have working snapshot dir: " + workingDir + " but shouldn't. Test file leak?", fs.exists(workingDir)); SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("snapshot").build(); try { SnapshotDescriptionUtils.completeSnapshot(snapshot, root, workingDir, fs); fail("Shouldn't successfully complete move of a non-existent directory."); } catch (IOException e) { LOG.info("Correctly failed to move non-existant directory: " + e.getMessage()); } }
|
### Question:
ReferenceRegionHFilesTask extends SnapshotTask { @Override public Void call() throws IOException { FileStatus[] families = FSUtils.listStatus(fs, regiondir, new FSUtils.FamilyDirFilter(fs)); if (families == null || families.length == 0) { LOG.info("No families under region directory:" + regiondir + ", not attempting to add references."); return null; } List<Path> snapshotFamilyDirs = TakeSnapshotUtils.getFamilySnapshotDirectories(snapshot, snapshotDir, families); LOG.debug("Add hfile references to snapshot directories:" + snapshotFamilyDirs); for (int i = 0; i < families.length; i++) { FileStatus family = families[i]; Path familyDir = family.getPath(); FileStatus[] hfiles = FSUtils.listStatus(fs, familyDir, fileFilter); if (hfiles == null || hfiles.length == 0) { LOG.debug("Not hfiles found for family: " + familyDir + ", skipping."); continue; } Path snapshotFamilyDir = snapshotFamilyDirs.get(i); fs.mkdirs(snapshotFamilyDir); for (FileStatus hfile : hfiles) { Path referenceFile = new Path(snapshotFamilyDir, hfile.getPath().getName()); LOG.debug("Creating reference for:" + hfile.getPath() + " at " + referenceFile); if (!fs.createNewFile(referenceFile)) { throw new IOException("Failed to create reference file:" + referenceFile); } } } if (LOG.isDebugEnabled()) { LOG.debug("Finished referencing hfiles, current region state:"); FSUtils.logFileSystemState(fs, regiondir, LOG); LOG.debug("and the snapshot directory:"); FSUtils.logFileSystemState(fs, snapshotDir, LOG); } return null; } ReferenceRegionHFilesTask(final SnapshotDescription snapshot,
ForeignExceptionDispatcher monitor, Path regionDir, final FileSystem fs, Path regionSnapshotDir); @Override Void call(); static final Log LOG; }### Answer:
@Test public void testRun() throws IOException { FileSystem fs = UTIL.getTestFileSystem(); Path testdir = UTIL.getDataTestDir(); Path regionDir = new Path(testdir, "region"); Path family1 = new Path(regionDir, "fam1"); Path family2 = new Path(regionDir, "fam2"); fs.mkdirs(family2); Path file1 = new Path(family1, "05f99689ae254693836613d1884c6b63"); fs.createNewFile(file1); Path file2 = new Path(family1, "7ac9898bf41d445aa0003e3d699d5d26"); fs.createNewFile(file2); Path snapshotRegionDir = new Path(testdir, HConstants.SNAPSHOT_DIR_NAME); fs.mkdirs(snapshotRegionDir); SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("name") .setTable("table").build(); ForeignExceptionDispatcher monitor = Mockito.mock(ForeignExceptionDispatcher.class); ReferenceRegionHFilesTask task = new ReferenceRegionHFilesTask(snapshot, monitor, regionDir, fs, snapshotRegionDir); ReferenceRegionHFilesTask taskSpy = Mockito.spy(task); task.call(); Mockito.verify(taskSpy, Mockito.never()).snapshotFailure(Mockito.anyString(), Mockito.any(Exception.class)); List<String> hfiles = new ArrayList<String>(2); FileStatus[] regions = FSUtils.listStatus(fs, snapshotRegionDir); for (FileStatus region : regions) { FileStatus[] fams = FSUtils.listStatus(fs, region.getPath()); for (FileStatus fam : fams) { FileStatus[] files = FSUtils.listStatus(fs, fam.getPath()); for (FileStatus file : files) { hfiles.add(file.getPath().getName()); } } } assertTrue("Didn't reference :" + file1, hfiles.contains(file1.getName())); assertTrue("Didn't reference :" + file1, hfiles.contains(file2.getName())); }
|
### Question:
CopyRecoveredEditsTask extends SnapshotTask { @Override public Void call() throws IOException { NavigableSet<Path> files = HLog.getSplitEditFilesSorted(this.fs, regiondir); if (files == null || files.size() == 0) return null; for (Path source : files) { FileStatus stat = fs.getFileStatus(source); if (stat.getLen() <= 0) continue; Path out = new Path(outputDir, source.getName()); LOG.debug("Copying " + source + " to " + out); FileUtil.copy(fs, source, fs, out, true, fs.getConf()); this.rethrowException(); } return null; } CopyRecoveredEditsTask(SnapshotDescription snapshot, ForeignExceptionDispatcher monitor,
FileSystem fs, Path regionDir, Path snapshotRegionDir); @Override Void call(); }### Answer:
@Test public void testCopyFiles() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("snapshot").build(); ForeignExceptionDispatcher monitor = Mockito.mock(ForeignExceptionDispatcher.class); FileSystem fs = UTIL.getTestFileSystem(); Path root = UTIL.getDataTestDir(); String regionName = "regionA"; Path regionDir = new Path(root, regionName); Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, root); try { Path snapshotRegionDir = new Path(workingDir, regionName); fs.mkdirs(snapshotRegionDir); Path edits = HLog.getRegionDirRecoveredEditsDir(regionDir); fs.mkdirs(edits); Path file1 = new Path(edits, "0000000000000002352"); FSDataOutputStream out = fs.create(file1); byte[] data = new byte[] { 1, 2, 3, 4 }; out.write(data); out.close(); Path empty = new Path(edits, "empty"); fs.createNewFile(empty); CopyRecoveredEditsTask task = new CopyRecoveredEditsTask(snapshot, monitor, fs, regionDir, snapshotRegionDir); CopyRecoveredEditsTask taskSpy = Mockito.spy(task); taskSpy.call(); Path snapshotEdits = HLog.getRegionDirRecoveredEditsDir(snapshotRegionDir); FileStatus[] snapshotEditFiles = FSUtils.listStatus(fs, snapshotEdits); assertEquals("Got wrong number of files in the snapshot edits", 1, snapshotEditFiles.length); FileStatus file = snapshotEditFiles[0]; assertEquals("Didn't copy expected file", file1.getName(), file.getPath().getName()); Mockito.verify(monitor, Mockito.never()).receive(Mockito.any(ForeignException.class)); Mockito.verify(taskSpy, Mockito.never()).snapshotFailure(Mockito.anyString(), Mockito.any(Exception.class)); } finally { FSUtils.delete(fs, regionDir, true); FSUtils.delete(fs, workingDir, true); } }
@Test public void testNoEditsDir() throws Exception { SnapshotDescription snapshot = SnapshotDescription.newBuilder().setName("snapshot").build(); ForeignExceptionDispatcher monitor = Mockito.mock(ForeignExceptionDispatcher.class); FileSystem fs = UTIL.getTestFileSystem(); Path root = UTIL.getDataTestDir(); String regionName = "regionA"; Path regionDir = new Path(root, regionName); Path workingDir = SnapshotDescriptionUtils.getWorkingSnapshotDir(snapshot, root); try { Path snapshotRegionDir = new Path(workingDir, regionName); fs.mkdirs(snapshotRegionDir); Path regionEdits = HLog.getRegionDirRecoveredEditsDir(regionDir); assertFalse("Edits dir exists already - it shouldn't", fs.exists(regionEdits)); CopyRecoveredEditsTask task = new CopyRecoveredEditsTask(snapshot, monitor, fs, regionDir, snapshotRegionDir); task.call(); } finally { FSUtils.delete(fs, regionDir, true); FSUtils.delete(fs, workingDir, true); } }
|
### Question:
HTableDescriptor implements WritableComparable<HTableDescriptor> { public long getMaxFileSize() { byte [] value = getValue(MAX_FILESIZE_KEY); if (value != null) { return Long.parseLong(Bytes.toString(value)); } return -1; } protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families); protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families,
Map<ImmutableBytesWritable,ImmutableBytesWritable> values); HTableDescriptor(); HTableDescriptor(final String name); HTableDescriptor(final byte [] name); HTableDescriptor(final HTableDescriptor desc); boolean isRootRegion(); boolean isMetaRegion(); boolean isMetaTable(); static boolean isMetaTable(final byte [] tableName); static byte [] isLegalTableName(final byte [] tableName); byte[] getValue(byte[] key); String getValue(String key); Map<ImmutableBytesWritable,ImmutableBytesWritable> getValues(); void setValue(byte[] key, byte[] value); void setValue(String key, String value); void remove(final byte [] key); void remove(final String key); boolean isReadOnly(); void setReadOnly(final boolean readOnly); synchronized boolean isDeferredLogFlush(); void setDeferredLogFlush(final boolean isDeferredLogFlush); byte [] getName(); String getNameAsString(); String getRegionSplitPolicyClassName(); void setName(byte[] name); long getMaxFileSize(); void setMaxFileSize(long maxFileSize); long getMemStoreFlushSize(); void setMemStoreFlushSize(long memstoreFlushSize); void addFamily(final HColumnDescriptor family); boolean hasFamily(final byte [] familyName); @Override String toString(); String toStringCustomizedValues(); @Override boolean equals(Object obj); @Override int hashCode(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int compareTo(final HTableDescriptor other); Collection<HColumnDescriptor> getFamilies(); Set<byte[]> getFamiliesKeys(); HColumnDescriptor[] getColumnFamilies(); HColumnDescriptor getFamily(final byte [] column); HColumnDescriptor removeFamily(final byte [] column); void addCoprocessor(String className); void addCoprocessor(String className, Path jarFilePath,
int priority, final Map<String, String> kvs); boolean hasCoprocessor(String className); List<String> getCoprocessors(); void removeCoprocessor(String className); static Path getTableDir(Path rootdir, final byte [] tableName); @Deprecated void setOwner(User owner); @Deprecated void setOwnerString(String ownerString); @Deprecated String getOwnerString(); static final String SPLIT_POLICY; static final String MAX_FILESIZE; static final String OWNER; static final ImmutableBytesWritable OWNER_KEY; static final String READONLY; static final String MEMSTORE_FLUSHSIZE; static final String IS_ROOT; static final String IS_META; static final String DEFERRED_LOG_FLUSH; static final boolean DEFAULT_READONLY; static final long DEFAULT_MEMSTORE_FLUSH_SIZE; static final String VALID_USER_TABLE_REGEX; static final HTableDescriptor ROOT_TABLEDESC; static final HTableDescriptor META_TABLEDESC; }### Answer:
@Test public void testGetMaxFileSize() { HTableDescriptor desc = new HTableDescriptor("table"); assertEquals(-1, desc.getMaxFileSize()); desc.setMaxFileSize(1111L); assertEquals(1111L, desc.getMaxFileSize()); }
|
### Question:
HTableDescriptor implements WritableComparable<HTableDescriptor> { public long getMemStoreFlushSize() { byte [] value = getValue(MEMSTORE_FLUSHSIZE_KEY); if (value != null) { return Long.parseLong(Bytes.toString(value)); } return -1; } protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families); protected HTableDescriptor(final byte [] name, HColumnDescriptor[] families,
Map<ImmutableBytesWritable,ImmutableBytesWritable> values); HTableDescriptor(); HTableDescriptor(final String name); HTableDescriptor(final byte [] name); HTableDescriptor(final HTableDescriptor desc); boolean isRootRegion(); boolean isMetaRegion(); boolean isMetaTable(); static boolean isMetaTable(final byte [] tableName); static byte [] isLegalTableName(final byte [] tableName); byte[] getValue(byte[] key); String getValue(String key); Map<ImmutableBytesWritable,ImmutableBytesWritable> getValues(); void setValue(byte[] key, byte[] value); void setValue(String key, String value); void remove(final byte [] key); void remove(final String key); boolean isReadOnly(); void setReadOnly(final boolean readOnly); synchronized boolean isDeferredLogFlush(); void setDeferredLogFlush(final boolean isDeferredLogFlush); byte [] getName(); String getNameAsString(); String getRegionSplitPolicyClassName(); void setName(byte[] name); long getMaxFileSize(); void setMaxFileSize(long maxFileSize); long getMemStoreFlushSize(); void setMemStoreFlushSize(long memstoreFlushSize); void addFamily(final HColumnDescriptor family); boolean hasFamily(final byte [] familyName); @Override String toString(); String toStringCustomizedValues(); @Override boolean equals(Object obj); @Override int hashCode(); @Override void readFields(DataInput in); @Override void write(DataOutput out); @Override int compareTo(final HTableDescriptor other); Collection<HColumnDescriptor> getFamilies(); Set<byte[]> getFamiliesKeys(); HColumnDescriptor[] getColumnFamilies(); HColumnDescriptor getFamily(final byte [] column); HColumnDescriptor removeFamily(final byte [] column); void addCoprocessor(String className); void addCoprocessor(String className, Path jarFilePath,
int priority, final Map<String, String> kvs); boolean hasCoprocessor(String className); List<String> getCoprocessors(); void removeCoprocessor(String className); static Path getTableDir(Path rootdir, final byte [] tableName); @Deprecated void setOwner(User owner); @Deprecated void setOwnerString(String ownerString); @Deprecated String getOwnerString(); static final String SPLIT_POLICY; static final String MAX_FILESIZE; static final String OWNER; static final ImmutableBytesWritable OWNER_KEY; static final String READONLY; static final String MEMSTORE_FLUSHSIZE; static final String IS_ROOT; static final String IS_META; static final String DEFERRED_LOG_FLUSH; static final boolean DEFAULT_READONLY; static final long DEFAULT_MEMSTORE_FLUSH_SIZE; static final String VALID_USER_TABLE_REGEX; static final HTableDescriptor ROOT_TABLEDESC; static final HTableDescriptor META_TABLEDESC; }### Answer:
@Test public void testGetMemStoreFlushSize() { HTableDescriptor desc = new HTableDescriptor("table"); assertEquals(-1, desc.getMemStoreFlushSize()); desc.setMemStoreFlushSize(1111L); assertEquals(1111L, desc.getMemStoreFlushSize()); }
|
### Question:
CatalogTracker { public boolean verifyRootRegionLocation(final long timeout) throws InterruptedException, IOException { HRegionInterface connection = null; try { connection = waitForRootServerConnection(timeout); } catch (NotAllMetaRegionsOnlineException e) { } catch (ServerNotRunningYetException e) { } catch (UnknownHostException e) { } return (connection == null)? false: verifyRegionLocation(connection, this.rootRegionTracker.getRootRegionLocation(), ROOT_REGION_NAME); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer:
@Test public void testVerifyRootRegionLocationFails() throws IOException, InterruptedException, KeeperException { HConnection connection = Mockito.mock(HConnection.class); ConnectException connectException = new ConnectException("Connection refused"); final HRegionInterface implementation = Mockito.mock(HRegionInterface.class); Mockito.when(implementation.getRegionInfo((byte [])Mockito.any())). thenThrow(connectException); Mockito.when(connection.getHRegionConnection(Mockito.anyString(), Mockito.anyInt(), Mockito.anyBoolean())). thenReturn(implementation); final CatalogTracker ct = constructAndStartCatalogTracker(connection); try { RootLocationEditor.setRootLocation(this.watcher, new ServerName("example.com", 1234, System.currentTimeMillis())); Assert.assertFalse(ct.verifyRootRegionLocation(100)); } finally { RootLocationEditor.deleteRootLocation(this.watcher); } }
|
### Question:
CatalogTracker { public void waitForRoot() throws InterruptedException { this.rootRegionTracker.blockUntilAvailable(); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer:
@Test (expected = NotAllMetaRegionsOnlineException.class) public void testTimeoutWaitForRoot() throws IOException, InterruptedException { HConnection connection = Mockito.mock(HConnection.class); final CatalogTracker ct = constructAndStartCatalogTracker(connection); ct.waitForRoot(100); }
|
### Question:
FSTableDescriptors implements TableDescriptors { @Override public HTableDescriptor get(final byte [] tablename) throws IOException { return get(Bytes.toString(tablename)); } FSTableDescriptors(final FileSystem fs, final Path rootdir); FSTableDescriptors(final FileSystem fs, final Path rootdir,
final boolean fsreadOnly); @Override HTableDescriptor get(final byte [] tablename); @Override HTableDescriptor get(final String tablename); @Override Map<String, HTableDescriptor> getAll(); @Override void add(HTableDescriptor htd); @Override HTableDescriptor remove(final String tablename); static boolean isTableInfoExists(FileSystem fs, Path rootdir,
String tableName); static FileStatus getTableInfoPath(final FileSystem fs,
final Path tabledir); static HTableDescriptor getTableDescriptor(FileSystem fs,
Path hbaseRootDir, byte[] tableName); static HTableDescriptor getTableDescriptor(FileSystem fs, Path tableDir); static void deleteTableDescriptorIfExists(String tableName,
Configuration conf); static boolean createTableDescriptor(final HTableDescriptor htableDescriptor,
Configuration conf); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor); static boolean createTableDescriptor(FileSystem fs, Path rootdir,
HTableDescriptor htableDescriptor, boolean forceCreation); static boolean createTableDescriptorForTableDirectory(FileSystem fs, Path tabledir,
HTableDescriptor htableDescriptor, boolean forceCreation); static final String TABLEINFO_NAME; }### Answer:
@Test public void testNoSuchTable() throws IOException { final String name = "testNoSuchTable"; FileSystem fs = FileSystem.get(UTIL.getConfiguration()); Path rootdir = new Path(UTIL.getDataTestDir(), name); TableDescriptors htds = new FSTableDescriptors(fs, rootdir); assertNull("There shouldn't be any HTD for this table", htds.get("NoSuchTable")); }
@Test public void testReadingArchiveDirectoryFromFS() throws IOException { FileSystem fs = FileSystem.get(UTIL.getConfiguration()); try { new FSTableDescriptors(fs, FSUtils.getRootDir(UTIL.getConfiguration())) .get(HConstants.HFILE_ARCHIVE_DIRECTORY); fail("Shouldn't be able to read a table descriptor for the archive directory."); } catch (IOException e) { LOG.debug("Correctly got error when reading a table descriptor from the archive directory: " + e.getMessage()); } }
|
### Question:
HRegionLocation implements Comparable<HRegionLocation> { public int compareTo(HRegionLocation o) { int result = this.hostname.compareTo(o.getHostname()); if (result != 0) return result; return this.port - o.getPort(); } HRegionLocation(HRegionInfo regionInfo, final String hostname,
final int port); @Override synchronized String toString(); @Override boolean equals(Object o); @Override int hashCode(); HRegionInfo getRegionInfo(); HServerAddress getServerAddress(); String getHostname(); int getPort(); synchronized String getHostnamePort(); int compareTo(HRegionLocation o); }### Answer:
@Test public void testCompareTo() { ServerName hsa1 = new ServerName("localhost", 1234, -1L); HRegionLocation hsl1 = new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, hsa1.getHostname(), hsa1.getPort()); ServerName hsa2 = new ServerName("localhost", 1235, -1L); HRegionLocation hsl2 = new HRegionLocation(HRegionInfo.ROOT_REGIONINFO, hsa2.getHostname(), hsa2.getPort()); assertTrue(hsl1.compareTo(hsl1) == 0); assertTrue(hsl2.compareTo(hsl2) == 0); int compare1 = hsl1.compareTo(hsl2); int compare2 = hsl2.compareTo(hsl1); assertTrue((compare1 > 0)? compare2 < 0: compare2 > 0); }
|
### Question:
CatalogTracker { public void waitForMeta() throws InterruptedException { while (!this.stopped) { try { if (waitForMeta(100) != null) break; } catch (NotAllMetaRegionsOnlineException e) { if (LOG.isTraceEnabled()) { LOG.info(".META. still not available, sleeping and retrying." + " Reason: " + e.getMessage()); } } catch (IOException e) { LOG.info("Retrying", e); } } } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer:
@Test (expected = RetriesExhaustedException.class) public void testTimeoutWaitForMeta() throws IOException, InterruptedException { HConnection connection = HConnectionTestingUtility.getMockedConnection(UTIL.getConfiguration()); try { final CatalogTracker ct = constructAndStartCatalogTracker(connection); ct.waitForMeta(100); } finally { HConnectionManager.deleteConnection(UTIL.getConfiguration()); } }
|
### Question:
CatalogTracker { public ServerName getRootLocation() throws InterruptedException { return this.rootRegionTracker.getRootRegionLocation(); } CatalogTracker(final Configuration conf); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
Abortable abortable); CatalogTracker(final ZooKeeperWatcher zk, final Configuration conf,
HConnection connection, Abortable abortable); void start(); void stop(); ServerName getRootLocation(); ServerName getMetaLocation(); ServerName getMetaLocationOrReadLocationFromRoot(); void waitForRoot(); HRegionInterface waitForRootServerConnection(long timeout); void waitForMeta(); ServerName waitForMeta(long timeout); HRegionInterface waitForMetaServerConnection(long timeout); void resetMetaLocation(); boolean verifyRootRegionLocation(final long timeout); boolean verifyMetaRegionLocation(final long timeout); HConnection getConnection(); }### Answer:
@Test public void testNoTimeoutWaitForRoot() throws IOException, InterruptedException, KeeperException { HConnection connection = Mockito.mock(HConnection.class); final CatalogTracker ct = constructAndStartCatalogTracker(connection); ServerName hsa = ct.getRootLocation(); Assert.assertNull(hsa); Thread t = new WaitOnMetaThread(ct); startWaitAliveThenWaitItLives(t, 1000); hsa = setRootLocation(); t.join(); Assert.assertTrue(ct.getRootLocation().equals(hsa)); }
|
### Question:
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean exists(ByteBuffer table, TGet get) throws TIOError, TException { HTableInterface htable = getTable(table.array()); try { return htable.exists(getFromThrift(get)); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftHBaseServiceHandler(Configuration conf); static THBaseService.Iface newInstance(
Configuration conf, ThriftMetrics metrics); @Override boolean exists(ByteBuffer table, TGet get); @Override TResult get(ByteBuffer table, TGet get); @Override List<TResult> getMultiple(ByteBuffer table, List<TGet> gets); @Override void put(ByteBuffer table, TPut put); @Override boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put); @Override void putMultiple(ByteBuffer table, List<TPut> puts); @Override void deleteSingle(ByteBuffer table, TDelete deleteSingle); @Override List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes); @Override boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value,
TDelete deleteSingle); @Override TResult increment(ByteBuffer table, TIncrement increment); @Override int openScanner(ByteBuffer table, TScan scan); @Override List<TResult> getScannerRows(int scannerId, int numRows); @Override void closeScanner(int scannerId); }### Answer:
@Test public void testExists() throws TIOError, TException { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testExists".getBytes(); ByteBuffer table = ByteBuffer.wrap(tableAname); TGet get = new TGet(ByteBuffer.wrap(rowName)); assertFalse(handler.exists(table, get)); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); columnValues.add(new TColumnValue(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer .wrap(valueAname))); columnValues.add(new TColumnValue(ByteBuffer.wrap(familyBname), ByteBuffer.wrap(qualifierBname), ByteBuffer .wrap(valueBname))); TPut put = new TPut(ByteBuffer.wrap(rowName), columnValues); put.setColumnValues(columnValues); handler.put(table, put); assertTrue(handler.exists(table, get)); }
|
### Question:
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes) throws TIOError, TException { HTableInterface htable = getTable(table.array()); List<Delete> tempDeletes = deletesFromThrift(deletes); try { htable.delete(tempDeletes); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } return deletesFromHBase(tempDeletes); } ThriftHBaseServiceHandler(Configuration conf); static THBaseService.Iface newInstance(
Configuration conf, ThriftMetrics metrics); @Override boolean exists(ByteBuffer table, TGet get); @Override TResult get(ByteBuffer table, TGet get); @Override List<TResult> getMultiple(ByteBuffer table, List<TGet> gets); @Override void put(ByteBuffer table, TPut put); @Override boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put); @Override void putMultiple(ByteBuffer table, List<TPut> puts); @Override void deleteSingle(ByteBuffer table, TDelete deleteSingle); @Override List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes); @Override boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value,
TDelete deleteSingle); @Override TResult increment(ByteBuffer table, TIncrement increment); @Override int openScanner(ByteBuffer table, TScan scan); @Override List<TResult> getScannerRows(int scannerId, int numRows); @Override void closeScanner(int scannerId); }### Answer:
@Test public void testDeleteMultiple() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); ByteBuffer table = ByteBuffer.wrap(tableAname); byte[] rowName1 = "testDeleteMultiple1".getBytes(); byte[] rowName2 = "testDeleteMultiple2".getBytes(); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); columnValues.add(new TColumnValue(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer .wrap(valueAname))); columnValues.add(new TColumnValue(ByteBuffer.wrap(familyBname), ByteBuffer.wrap(qualifierBname), ByteBuffer .wrap(valueBname))); List<TPut> puts = new ArrayList<TPut>(); puts.add(new TPut(ByteBuffer.wrap(rowName1), columnValues)); puts.add(new TPut(ByteBuffer.wrap(rowName2), columnValues)); handler.putMultiple(table, puts); List<TDelete> deletes = new ArrayList<TDelete>(); deletes.add(new TDelete(ByteBuffer.wrap(rowName1))); deletes.add(new TDelete(ByteBuffer.wrap(rowName2))); List<TDelete> deleteResults = handler.deleteMultiple(table, deletes); assertEquals(0, deleteResults.size()); assertFalse(handler.exists(table, new TGet(ByteBuffer.wrap(rowName1)))); assertFalse(handler.exists(table, new TGet(ByteBuffer.wrap(rowName2)))); }
|
### Question:
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public TResult increment(ByteBuffer table, TIncrement increment) throws TIOError, TException { HTableInterface htable = getTable(table.array()); try { return resultFromHBase(htable.increment(incrementFromThrift(increment))); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftHBaseServiceHandler(Configuration conf); static THBaseService.Iface newInstance(
Configuration conf, ThriftMetrics metrics); @Override boolean exists(ByteBuffer table, TGet get); @Override TResult get(ByteBuffer table, TGet get); @Override List<TResult> getMultiple(ByteBuffer table, List<TGet> gets); @Override void put(ByteBuffer table, TPut put); @Override boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put); @Override void putMultiple(ByteBuffer table, List<TPut> puts); @Override void deleteSingle(ByteBuffer table, TDelete deleteSingle); @Override List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes); @Override boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value,
TDelete deleteSingle); @Override TResult increment(ByteBuffer table, TIncrement increment); @Override int openScanner(ByteBuffer table, TScan scan); @Override List<TResult> getScannerRows(int scannerId, int numRows); @Override void closeScanner(int scannerId); }### Answer:
@Test public void testIncrement() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testIncrement".getBytes(); ByteBuffer table = ByteBuffer.wrap(tableAname); List<TColumnValue> columnValues = new ArrayList<TColumnValue>(); columnValues.add(new TColumnValue(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer .wrap(Bytes.toBytes(1L)))); TPut put = new TPut(ByteBuffer.wrap(rowName), columnValues); put.setColumnValues(columnValues); handler.put(table, put); List<TColumnIncrement> incrementColumns = new ArrayList<TColumnIncrement>(); incrementColumns.add(new TColumnIncrement(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname))); TIncrement increment = new TIncrement(ByteBuffer.wrap(rowName), incrementColumns); handler.increment(table, increment); TGet get = new TGet(ByteBuffer.wrap(rowName)); TResult result = handler.get(table, get); assertArrayEquals(rowName, result.getRow()); assertEquals(1, result.getColumnValuesSize()); TColumnValue columnValue = result.getColumnValues().get(0); assertArrayEquals(Bytes.toBytes(2L), columnValue.getValue()); }
|
### Question:
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put) throws TIOError, TException { HTableInterface htable = getTable(table.array()); try { return htable.checkAndPut(row.array(), family.array(), qualifier.array(), (value == null) ? null : value.array(), putFromThrift(put)); } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftHBaseServiceHandler(Configuration conf); static THBaseService.Iface newInstance(
Configuration conf, ThriftMetrics metrics); @Override boolean exists(ByteBuffer table, TGet get); @Override TResult get(ByteBuffer table, TGet get); @Override List<TResult> getMultiple(ByteBuffer table, List<TGet> gets); @Override void put(ByteBuffer table, TPut put); @Override boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put); @Override void putMultiple(ByteBuffer table, List<TPut> puts); @Override void deleteSingle(ByteBuffer table, TDelete deleteSingle); @Override List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes); @Override boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value,
TDelete deleteSingle); @Override TResult increment(ByteBuffer table, TIncrement increment); @Override int openScanner(ByteBuffer table, TScan scan); @Override List<TResult> getScannerRows(int scannerId, int numRows); @Override void closeScanner(int scannerId); }### Answer:
@Test public void testCheckAndPut() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testCheckAndPut".getBytes(); ByteBuffer table = ByteBuffer.wrap(tableAname); List<TColumnValue> columnValuesA = new ArrayList<TColumnValue>(); TColumnValue columnValueA = new TColumnValue(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname)); columnValuesA.add(columnValueA); TPut putA = new TPut(ByteBuffer.wrap(rowName), columnValuesA); putA.setColumnValues(columnValuesA); List<TColumnValue> columnValuesB = new ArrayList<TColumnValue>(); TColumnValue columnValueB = new TColumnValue(ByteBuffer.wrap(familyBname), ByteBuffer.wrap(qualifierBname), ByteBuffer.wrap(valueBname)); columnValuesB.add(columnValueB); TPut putB = new TPut(ByteBuffer.wrap(rowName), columnValuesB); putB.setColumnValues(columnValuesB); assertFalse(handler.checkAndPut(table, ByteBuffer.wrap(rowName), ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname), putB)); TGet get = new TGet(ByteBuffer.wrap(rowName)); TResult result = handler.get(table, get); assertEquals(0, result.getColumnValuesSize()); handler.put(table, putA); assertTrue(handler.checkAndPut(table, ByteBuffer.wrap(rowName), ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname), putB)); result = handler.get(table, get); assertArrayEquals(rowName, result.getRow()); List<TColumnValue> returnedColumnValues = result.getColumnValues(); List<TColumnValue> expectedColumnValues = new ArrayList<TColumnValue>(); expectedColumnValues.add(columnValueA); expectedColumnValues.add(columnValueB); assertTColumnValuesEqual(expectedColumnValues, returnedColumnValues); }
|
### Question:
ThriftHBaseServiceHandler implements THBaseService.Iface { @Override public boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TDelete deleteSingle) throws TIOError, TException { HTableInterface htable = getTable(table.array()); try { if (value == null) { return htable.checkAndDelete(row.array(), family.array(), qualifier.array(), null, deleteFromThrift(deleteSingle)); } else { return htable.checkAndDelete(row.array(), family.array(), qualifier.array(), value.array(), deleteFromThrift(deleteSingle)); } } catch (IOException e) { throw getTIOError(e); } finally { closeTable(htable); } } ThriftHBaseServiceHandler(Configuration conf); static THBaseService.Iface newInstance(
Configuration conf, ThriftMetrics metrics); @Override boolean exists(ByteBuffer table, TGet get); @Override TResult get(ByteBuffer table, TGet get); @Override List<TResult> getMultiple(ByteBuffer table, List<TGet> gets); @Override void put(ByteBuffer table, TPut put); @Override boolean checkAndPut(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value, TPut put); @Override void putMultiple(ByteBuffer table, List<TPut> puts); @Override void deleteSingle(ByteBuffer table, TDelete deleteSingle); @Override List<TDelete> deleteMultiple(ByteBuffer table, List<TDelete> deletes); @Override boolean checkAndDelete(ByteBuffer table, ByteBuffer row, ByteBuffer family, ByteBuffer qualifier, ByteBuffer value,
TDelete deleteSingle); @Override TResult increment(ByteBuffer table, TIncrement increment); @Override int openScanner(ByteBuffer table, TScan scan); @Override List<TResult> getScannerRows(int scannerId, int numRows); @Override void closeScanner(int scannerId); }### Answer:
@Test public void testCheckAndDelete() throws Exception { ThriftHBaseServiceHandler handler = createHandler(); byte[] rowName = "testCheckAndDelete".getBytes(); ByteBuffer table = ByteBuffer.wrap(tableAname); List<TColumnValue> columnValuesA = new ArrayList<TColumnValue>(); TColumnValue columnValueA = new TColumnValue(ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname)); columnValuesA.add(columnValueA); TPut putA = new TPut(ByteBuffer.wrap(rowName), columnValuesA); putA.setColumnValues(columnValuesA); List<TColumnValue> columnValuesB = new ArrayList<TColumnValue>(); TColumnValue columnValueB = new TColumnValue(ByteBuffer.wrap(familyBname), ByteBuffer.wrap(qualifierBname), ByteBuffer.wrap(valueBname)); columnValuesB.add(columnValueB); TPut putB = new TPut(ByteBuffer.wrap(rowName), columnValuesB); putB.setColumnValues(columnValuesB); handler.put(table, putB); TDelete delete = new TDelete(ByteBuffer.wrap(rowName)); assertFalse(handler.checkAndDelete(table, ByteBuffer.wrap(rowName), ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname), delete)); TGet get = new TGet(ByteBuffer.wrap(rowName)); TResult result = handler.get(table, get); assertArrayEquals(rowName, result.getRow()); assertTColumnValuesEqual(columnValuesB, result.getColumnValues()); handler.put(table, putA); assertTrue(handler.checkAndDelete(table, ByteBuffer.wrap(rowName), ByteBuffer.wrap(familyAname), ByteBuffer.wrap(qualifierAname), ByteBuffer.wrap(valueAname), delete)); result = handler.get(table, get); assertFalse(result.isSetRow()); assertEquals(0, result.getColumnValuesSize()); }
|
### Question:
DynamicClassLoader extends ClassLoaderBase { @Override public Class<?> loadClass(String name) throws ClassNotFoundException { try { return parent.loadClass(name); } catch (ClassNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Class " + name + " not found - using dynamical class loader"); } synchronized (getClassLoadingLock(name)) { Class<?> clasz = findLoadedClass(name); if (clasz != null) { if (LOG.isDebugEnabled()) { LOG.debug("Class " + name + " already loaded"); } } else { try { if (LOG.isDebugEnabled()) { LOG.debug("Finding class: " + name); } clasz = findClass(name); } catch (ClassNotFoundException cnfe) { if (LOG.isDebugEnabled()) { LOG.debug("Loading new jar files, if any"); } loadNewJars(); if (LOG.isDebugEnabled()) { LOG.debug("Finding class again: " + name); } clasz = findClass(name); } } return clasz; } } } DynamicClassLoader(
final Configuration conf, final ClassLoader parent); @Override Class<?> loadClass(String name); }### Answer:
@Test public void testLoadClassFromLocalPath() throws Exception { ClassLoader parent = TestDynamicClassLoader.class.getClassLoader(); DynamicClassLoader classLoader = new DynamicClassLoader(conf, parent); String className = "TestLoadClassFromLocalPath"; deleteClass(className); try { classLoader.loadClass(className); fail("Should not be able to load class " + className); } catch (ClassNotFoundException cnfe) { } try { String folder = TEST_UTIL.getDataTestDir().toString(); ClassLoaderTestHelper.buildJar(folder, className, null, localDirPath()); classLoader.loadClass(className); } catch (ClassNotFoundException cnfe) { LOG.error("Should be able to load class " + className, cnfe); fail(cnfe.getMessage()); } }
@Test public void testLoadClassFromLocalPath() throws Exception { ClassLoader parent = TestDynamicClassLoader.class.getClassLoader(); DynamicClassLoader classLoader = new DynamicClassLoader(conf, parent); String className = "TestLoadClassFromLocalPath"; deleteClass(className); try { classLoader.loadClass(className); fail("Should not be able to load class " + className); } catch (ClassNotFoundException cnfe) { } try { String folder = TEST_UTIL.getDataTestDir().toString(); ClassLoaderTestHelper.buildJar( folder, className, null, ClassLoaderTestHelper.localDirPath(conf)); classLoader.loadClass(className); } catch (ClassNotFoundException cnfe) { LOG.error("Should be able to load class " + className, cnfe); fail(cnfe.getMessage()); } }
@Test public void testLoadClassFromAnotherPath() throws Exception { ClassLoader parent = TestDynamicClassLoader.class.getClassLoader(); DynamicClassLoader classLoader = new DynamicClassLoader(conf, parent); String className = "TestLoadClassFromAnotherPath"; deleteClass(className); try { classLoader.loadClass(className); fail("Should not be able to load class " + className); } catch (ClassNotFoundException cnfe) { } try { String folder = TEST_UTIL.getDataTestDir().toString(); ClassLoaderTestHelper.buildJar(folder, className, null); classLoader.loadClass(className); } catch (ClassNotFoundException cnfe) { LOG.error("Should be able to load class " + className, cnfe); fail(cnfe.getMessage()); } }
|
### Question:
MRApps extends Apps { public static String toString(JobId jid) { return jid.toString(); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment,
Configuration conf); }### Answer:
@Test public void testJobIDtoString() { JobId jid = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(JobId.class); jid.setAppId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(ApplicationId.class)); assertEquals("job_0_0000", MRApps.toString(jid)); }
@Test public void testTaskIDtoString() { TaskId tid = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(TaskId.class); tid.setJobId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(JobId.class)); tid.getJobId().setAppId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(ApplicationId.class)); tid.setTaskType(TaskType.MAP); TaskType type = tid.getTaskType(); System.err.println(type); type = TaskType.REDUCE; System.err.println(type); System.err.println(tid.getTaskType()); assertEquals("task_0_0000_m_000000", MRApps.toString(tid)); tid.setTaskType(TaskType.REDUCE); assertEquals("task_0_0000_r_000000", MRApps.toString(tid)); }
@Test public void testTaskAttemptIDtoString() { TaskAttemptId taid = RecordFactoryProvider.getRecordFactory(null).newRecordInstance(TaskAttemptId.class); taid.setTaskId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(TaskId.class)); taid.getTaskId().setTaskType(TaskType.MAP); taid.getTaskId().setJobId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(JobId.class)); taid.getTaskId().getJobId().setAppId(RecordFactoryProvider.getRecordFactory(null).newRecordInstance(ApplicationId.class)); assertEquals("attempt_0_0000_m_000000_0", MRApps.toString(taid)); }
|
### Question:
IdLock { void assertMapEmpty() { assert map.size() == 0; } Entry getLockEntry(long id); void releaseLockEntry(Entry entry); }### Answer:
@Test public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0; i < NUM_THREADS; ++i) { Future<Boolean> result = ecs.take(); assertTrue(result.get()); } idLock.assertMapEmpty(); } finally { exec.shutdown(); } }
@Test public void testMultipleClients() throws Exception { ExecutorService exec = Executors.newFixedThreadPool(NUM_THREADS); try { ExecutorCompletionService<Boolean> ecs = new ExecutorCompletionService<Boolean>(exec); for (int i = 0; i < NUM_THREADS; ++i) ecs.submit(new IdLockTestThread("client_" + i)); for (int i = 0; i < NUM_THREADS; ++i) { Future<Boolean> result = ecs.take(); assertTrue(result.get()); } idLock.assertMapEmpty(); } finally { exec.shutdown(); exec.awaitTermination(5000, TimeUnit.MILLISECONDS); } }
|
### Question:
MRApps extends Apps { public static JobId toJobID(String jid) { return TypeConverter.toYarn(JobID.forName(jid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment,
Configuration conf); }### Answer:
@Test public void testToJobID() { JobId jid = MRApps.toJobID("job_1_1"); assertEquals(1, jid.getAppId().getClusterTimestamp()); assertEquals(1, jid.getAppId().getId()); assertEquals(1, jid.getId()); }
@Test(expected=IllegalArgumentException.class) public void testJobIDShort() { MRApps.toJobID("job_0_0_0"); }
|
### Question:
MRApps extends Apps { public static TaskId toTaskID(String tid) { return TypeConverter.toYarn(TaskID.forName(tid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment,
Configuration conf); }### Answer:
@Test public void testToTaskID() { TaskId tid = MRApps.toTaskID("task_1_2_r_3"); assertEquals(1, tid.getJobId().getAppId().getClusterTimestamp()); assertEquals(2, tid.getJobId().getAppId().getId()); assertEquals(2, tid.getJobId().getId()); assertEquals(TaskType.REDUCE, tid.getTaskType()); assertEquals(3, tid.getId()); tid = MRApps.toTaskID("task_1_2_m_3"); assertEquals(TaskType.MAP, tid.getTaskType()); }
@Test(expected=IllegalArgumentException.class) public void testTaskIDShort() { MRApps.toTaskID("task_0_0000_m"); }
@Test(expected=IllegalArgumentException.class) public void testTaskIDBadType() { MRApps.toTaskID("task_0_0000_x_000000"); }
|
### Question:
MRApps extends Apps { public static TaskAttemptId toTaskAttemptID(String taid) { return TypeConverter.toYarn(TaskAttemptID.forName(taid)); } if(userClassesTakesPrecedence); static String toString(JobId jid); static JobId toJobID(String jid); static String toString(TaskId tid); static TaskId toTaskID(String tid); static String toString(TaskAttemptId taid); static TaskAttemptId toTaskAttemptID(String taid); static String taskSymbol(TaskType type); static TaskType taskType(String symbol); static TaskAttemptStateUI taskAttemptState(String attemptStateStr); @SuppressWarnings("deprecation") static void setClasspath(Map<String, String> environment,
Configuration conf); }### Answer:
@Test public void testToTaskAttemptID() { TaskAttemptId taid = MRApps.toTaskAttemptID("attempt_0_1_m_2_3"); assertEquals(0, taid.getTaskId().getJobId().getAppId().getClusterTimestamp()); assertEquals(1, taid.getTaskId().getJobId().getAppId().getId()); assertEquals(1, taid.getTaskId().getJobId().getId()); assertEquals(2, taid.getTaskId().getId()); assertEquals(3, taid.getId()); }
@Test(expected=IllegalArgumentException.class) public void testTaskAttemptIDShort() { MRApps.toTaskAttemptID("attempt_0_0_0_m_0"); }
|
### Question:
FileNameIndexUtils { public static String getDoneFileName(JobIndexInfo indexInfo) throws IOException { StringBuilder sb = new StringBuilder(); sb.append(escapeDelimiters(TypeConverter.fromYarn(indexInfo.getJobId()).toString())); sb.append(DELIMITER); sb.append(indexInfo.getSubmitTime()); sb.append(DELIMITER); sb.append(escapeDelimiters(getUserName(indexInfo))); sb.append(DELIMITER); sb.append(escapeDelimiters(trimJobName(getJobName(indexInfo)))); sb.append(DELIMITER); sb.append(indexInfo.getFinishTime()); sb.append(DELIMITER); sb.append(indexInfo.getNumMaps()); sb.append(DELIMITER); sb.append(indexInfo.getNumReduces()); sb.append(DELIMITER); sb.append(indexInfo.getJobStatus()); sb.append(DELIMITER); sb.append(indexInfo.getQueueName()); sb.append(JobHistoryUtils.JOB_HISTORY_FILE_EXTENSION); return encodeJobHistoryFileName(sb.toString()); } static String getDoneFileName(JobIndexInfo indexInfo); static JobIndexInfo getIndexInfo(String jhFileName); static String encodeJobHistoryFileName(String logFileName); static String decodeJobHistoryFileName(String logFileName); }### Answer:
@Test public void testUserNamePercentEncoding() throws IOException { JobIndexInfo info = new JobIndexInfo(); JobID oldJobId = JobID.forName(JOB_ID); JobId jobId = TypeConverter.toYarn(oldJobId); info.setJobId(jobId); info.setSubmitTime(Long.parseLong(SUBMIT_TIME)); info.setUser(USER_NAME_WITH_DELIMITER); info.setJobName(JOB_NAME); info.setFinishTime(Long.parseLong(FINISH_TIME)); info.setNumMaps(Integer.parseInt(NUM_MAPS)); info.setNumReduces(Integer.parseInt(NUM_REDUCES)); info.setJobStatus(JOB_STATUS); info.setQueueName(QUEUE_NAME); String jobHistoryFile = FileNameIndexUtils.getDoneFileName(info); Assert.assertTrue("User name not encoded correctly into job history file", jobHistoryFile.contains(USER_NAME_WITH_DELIMITER_ESCAPE)); }
@Test public void testJobNamePercentEncoding() throws IOException { JobIndexInfo info = new JobIndexInfo(); JobID oldJobId = JobID.forName(JOB_ID); JobId jobId = TypeConverter.toYarn(oldJobId); info.setJobId(jobId); info.setSubmitTime(Long.parseLong(SUBMIT_TIME)); info.setUser(USER_NAME); info.setJobName(JOB_NAME_WITH_DELIMITER); info.setFinishTime(Long.parseLong(FINISH_TIME)); info.setNumMaps(Integer.parseInt(NUM_MAPS)); info.setNumReduces(Integer.parseInt(NUM_REDUCES)); info.setJobStatus(JOB_STATUS); info.setQueueName(QUEUE_NAME); String jobHistoryFile = FileNameIndexUtils.getDoneFileName(info); Assert.assertTrue("Job name not encoded correctly into job history file", jobHistoryFile.contains(JOB_NAME_WITH_DELIMITER_ESCAPE)); }
|
### Question:
FileNameIndexUtils { public static JobIndexInfo getIndexInfo(String jhFileName) throws IOException { String fileName = jhFileName.substring(0, jhFileName.indexOf(JobHistoryUtils.JOB_HISTORY_FILE_EXTENSION)); JobIndexInfo indexInfo = new JobIndexInfo(); String[] jobDetails = fileName.split(DELIMITER); JobID oldJobId = JobID.forName(decodeJobHistoryFileName(jobDetails[JOB_ID_INDEX])); JobId jobId = TypeConverter.toYarn(oldJobId); indexInfo.setJobId(jobId); try { try { indexInfo.setSubmitTime( Long.parseLong(decodeJobHistoryFileName(jobDetails[SUBMIT_TIME_INDEX]))); } catch (NumberFormatException e) { LOG.warn("Unable to parse submit time from job history file " + jhFileName + " : " + e); } indexInfo.setUser( decodeJobHistoryFileName(jobDetails[USER_INDEX])); indexInfo.setJobName( decodeJobHistoryFileName(jobDetails[JOB_NAME_INDEX])); try { indexInfo.setFinishTime( Long.parseLong(decodeJobHistoryFileName(jobDetails[FINISH_TIME_INDEX]))); } catch (NumberFormatException e) { LOG.warn("Unable to parse finish time from job history file " + jhFileName + " : " + e); } try { indexInfo.setNumMaps( Integer.parseInt(decodeJobHistoryFileName(jobDetails[NUM_MAPS_INDEX]))); } catch (NumberFormatException e) { LOG.warn("Unable to parse num maps from job history file " + jhFileName + " : " + e); } try { indexInfo.setNumReduces( Integer.parseInt(decodeJobHistoryFileName(jobDetails[NUM_REDUCES_INDEX]))); } catch (NumberFormatException e) { LOG.warn("Unable to parse num reduces from job history file " + jhFileName + " : " + e); } indexInfo.setJobStatus( decodeJobHistoryFileName(jobDetails[JOB_STATUS_INDEX])); indexInfo.setQueueName( decodeJobHistoryFileName(jobDetails[QUEUE_NAME_INDEX])); } catch (IndexOutOfBoundsException e) { LOG.warn("Parsing job history file with partial data encoded into name: " + jhFileName); } return indexInfo; } static String getDoneFileName(JobIndexInfo indexInfo); static JobIndexInfo getIndexInfo(String jhFileName); static String encodeJobHistoryFileName(String logFileName); static String decodeJobHistoryFileName(String logFileName); }### Answer:
@Test public void testUserNamePercentDecoding() throws IOException { String jobHistoryFile = String.format(JOB_HISTORY_FILE_FORMATTER, JOB_ID, SUBMIT_TIME, USER_NAME_WITH_DELIMITER_ESCAPE, JOB_NAME, FINISH_TIME, NUM_MAPS, NUM_REDUCES, JOB_STATUS, QUEUE_NAME); JobIndexInfo info = FileNameIndexUtils.getIndexInfo(jobHistoryFile); Assert.assertEquals("User name doesn't match", USER_NAME_WITH_DELIMITER, info.getUser()); }
|
### Question:
CompletedTask implements Task { @Override public synchronized TaskReport getReport() { if (report == null) { constructTaskReport(); } return report; } CompletedTask(TaskId taskId, TaskInfo taskInfo); @Override boolean canCommit(TaskAttemptId taskAttemptID); @Override TaskAttempt getAttempt(TaskAttemptId attemptID); @Override Map<TaskAttemptId, TaskAttempt> getAttempts(); @Override Counters getCounters(); @Override TaskId getID(); @Override float getProgress(); @Override synchronized TaskReport getReport(); @Override TaskType getType(); @Override boolean isFinished(); @Override TaskState getState(); }### Answer:
@Test public void testTaskStartTimes() { TaskId taskId = Mockito.mock(TaskId.class); TaskInfo taskInfo = Mockito.mock(TaskInfo.class); Map<TaskAttemptID, TaskAttemptInfo> taskAttempts = new TreeMap<TaskAttemptID, TaskAttemptInfo>(); TaskAttemptID id = new TaskAttemptID("0", 0, TaskType.MAP, 0, 0); TaskAttemptInfo info = Mockito.mock(TaskAttemptInfo.class); Mockito.when(info.getAttemptId()).thenReturn(id); Mockito.when(info.getStartTime()).thenReturn(10l); taskAttempts.put(id, info); id = new TaskAttemptID("1", 0, TaskType.MAP, 1, 1); info = Mockito.mock(TaskAttemptInfo.class); Mockito.when(info.getAttemptId()).thenReturn(id); Mockito.when(info.getStartTime()).thenReturn(20l); taskAttempts.put(id, info); Mockito.when(taskInfo.getAllTaskAttempts()).thenReturn(taskAttempts); CompletedTask task = new CompletedTask(taskId, taskInfo); TaskReport report = task.getReport(); Assert.assertTrue(report.getStartTime() == 10); }
|
### Question:
TokenCache { public static void cleanUpTokenReferral(Configuration conf) { conf.unset(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY); } static byte[] getSecretKey(Credentials credentials, Text alias); static void obtainTokensForNamenodes(Credentials credentials,
Path[] ps, Configuration conf); static void cleanUpTokenReferral(Configuration conf); @InterfaceAudience.Private static Credentials loadTokens(String jobTokenFile, JobConf conf); @InterfaceAudience.Private static void setJobToken(Token<? extends TokenIdentifier> t,
Credentials credentials); @SuppressWarnings("unchecked") @InterfaceAudience.Private static Token<JobTokenIdentifier> getJobToken(Credentials credentials); @InterfaceAudience.Private
static final String JOB_TOKEN_HDFS_FILE; @InterfaceAudience.Private
static final String JOB_TOKENS_FILENAME; }### Answer:
@Test public void testCleanUpTokenReferral() throws Exception { Configuration conf = new Configuration(); conf.set(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY, "foo"); TokenCache.cleanUpTokenReferral(conf); assertNull(conf.get(MRJobConfig.MAPREDUCE_JOB_CREDENTIALS_BINARY)); }
|
### Question:
ShuffleScheduler { public synchronized void tipFailed(TaskID taskId) { if (!finishedMaps[taskId.getId()]) { finishedMaps[taskId.getId()] = true; if (--remainingMaps == 0) { notifyAll(); } updateStatus(); } } ShuffleScheduler(JobConf job, TaskStatus status,
ExceptionReporter reporter,
Progress progress,
Counters.Counter shuffledMapsCounter,
Counters.Counter reduceShuffleBytes,
Counters.Counter failedShuffleCounter); synchronized void copySucceeded(TaskAttemptID mapId,
MapHost host,
long bytes,
long millis,
MapOutput<K,V> output
); synchronized void copyFailed(TaskAttemptID mapId, MapHost host,
boolean readError, boolean connectExcpt); synchronized void tipFailed(TaskID taskId); synchronized void addKnownMapOutput(String hostName,
String hostUrl,
TaskAttemptID mapId); synchronized void obsoleteMapOutput(TaskAttemptID mapId); synchronized void putBackKnownMapOutput(MapHost host,
TaskAttemptID mapId); synchronized MapHost getHost(); synchronized List<TaskAttemptID> getMapsForHost(MapHost host); synchronized void freeHost(MapHost host); synchronized void resetKnownMaps(); synchronized boolean waitUntilDone(int millis
); void close(); synchronized void informMaxMapRunTime(int duration); }### Answer:
@SuppressWarnings("rawtypes") @Test public void testTipFailed() throws Exception { JobConf job = new JobConf(); job.setNumMapTasks(2); TaskStatus status = new TaskStatus() { @Override public boolean getIsMap() { return false; } @Override public void addFetchFailedMap(TaskAttemptID mapTaskId) { } }; Progress progress = new Progress(); ShuffleScheduler scheduler = new ShuffleScheduler(job, status, null, progress, null, null, null); JobID jobId = new JobID(); TaskID taskId1 = new TaskID(jobId, TaskType.REDUCE, 1); scheduler.tipFailed(taskId1); Assert.assertEquals("Progress should be 0.5", 0.5f, progress.getProgress(), 0.0f); Assert.assertFalse(scheduler.waitUntilDone(1)); TaskID taskId0 = new TaskID(jobId, TaskType.REDUCE, 0); scheduler.tipFailed(taskId0); Assert.assertEquals("Progress should be 1.0", 1.0f, progress.getProgress(), 0.0f); Assert.assertTrue(scheduler.waitUntilDone(1)); }
|
### Question:
Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public Counters() { super(groupFactory); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer:
@Test public void testCounters() throws IOException { Enum[] keysWithResource = {TaskCounter.MAP_INPUT_RECORDS, TaskCounter.MAP_OUTPUT_BYTES}; Enum[] keysWithoutResource = {myCounters.TEST1, myCounters.TEST2}; String[] groups = {"group1", "group2", "group{}()[]"}; String[] counters = {"counter1", "counter2", "counter{}()[]"}; try { testCounter(getEnumCounters(keysWithResource)); testCounter(getEnumCounters(keysWithoutResource)); testCounter(getEnumCounters(groups, counters)); } catch (ParseException pe) { throw new IOException(pe); } }
|
### Question:
Counters extends AbstractCounters<Counters.Counter, Counters.Group> { public synchronized Counter findCounter(String group, String name) { if (name.equals("MAP_INPUT_BYTES")) { LOG.warn("Counter name MAP_INPUT_BYTES is deprecated. " + "Use FileInputFormatCounters as group name and " + " BYTES_READ as counter name instead"); return findCounter(FileInputFormatCounter.BYTES_READ); } return getGroup(group).getCounterForName(name); } Counters(); Counters(org.apache.hadoop.mapreduce.Counters newCounters); synchronized Group getGroup(String groupName); @SuppressWarnings("unchecked") synchronized Collection<String> getGroupNames(); synchronized String makeCompactString(); synchronized Counter findCounter(String group, String name); @Deprecated Counter findCounter(String group, int id, String name); void incrCounter(Enum<?> key, long amount); void incrCounter(String group, String counter, long amount); synchronized long getCounter(Enum<?> key); synchronized void incrAllCounters(Counters other); int size(); static Counters sum(Counters a, Counters b); void log(Log log); String makeEscapedCompactString(); static Counters fromEscapedCompactString(String compactString); static int MAX_COUNTER_LIMIT; }### Answer:
@SuppressWarnings("deprecation") @Test public void testCounterValue() { Counters counters = new Counters(); final int NUMBER_TESTS = 100; final int NUMBER_INC = 10; final Random rand = new Random(); for (int i = 0; i < NUMBER_TESTS; i++) { long initValue = rand.nextInt(); long expectedValue = initValue; Counter counter = counters.findCounter("foo", "bar"); counter.setValue(initValue); assertEquals("Counter value is not initialized correctly", expectedValue, counter.getValue()); for (int j = 0; j < NUMBER_INC; j++) { int incValue = rand.nextInt(); counter.increment(incValue); expectedValue += incValue; assertEquals("Counter value is not incremented correctly", expectedValue, counter.getValue()); } expectedValue = rand.nextInt(); counter.setValue(expectedValue); assertEquals("Counter value is not set correctly", expectedValue, counter.getValue()); } }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.