src_fm_fc_ms_ff stringlengths 43 86.8k | target stringlengths 20 276k |
|---|---|
Result { @SuppressWarnings("ConstantConditions") public static <T> Result<T> response(Response<T> response) { if (response == null) throw new NullPointerException("response == null"); return new Result<>(response, null); } private Result(@Nullable Response<T> response, @Nullable Throwable error); @SuppressWarnings("Co... | @Test public void response() { Response<String> response = Response.success("Hi"); Result<String> result = Result.response(response); assertThat(result.isError()).isFalse(); assertThat(result.error()).isNull(); assertThat(result.response()).isSameAs(response); }
@Test public void nullResponseThrows() { try { Result.res... |
MoshiConverterFactory extends Converter.Factory { public MoshiConverterFactory failOnUnknown() { return new MoshiConverterFactory(moshi, lenient, true, serializeNulls); } private MoshiConverterFactory(
Moshi moshi, boolean lenient, boolean failOnUnknown, boolean serializeNulls); static MoshiConverterFactory crea... | @Test public void failOnUnknown() throws IOException, InterruptedException { server.enqueue(new MockResponse().setBody("{\"taco\":\"delicious\"}")); Call<AnImplementation> call = serviceFailOnUnknown.anImplementation(new AnImplementation(null)); try { call.execute(); fail(); } catch (JsonDataException e) { assertThat(e... |
Result { @SuppressWarnings("ConstantConditions") public static <T> Result<T> error(Throwable error) { if (error == null) throw new NullPointerException("error == null"); return new Result<>(null, error); } private Result(@Nullable Response<T> response, @Nullable Throwable error); @SuppressWarnings("ConstantConditions"... | @Test public void error() { Throwable error = new IOException(); Result<Object> result = Result.error(error); assertThat(result.isError()).isTrue(); assertThat(result.error()).isSameAs(error); assertThat(result.response()).isNull(); }
@Test public void nullErrorThrows() { try { Result.error(null); fail(); } catch (Null... |
GuavaCallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != ListenableFuture.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateException... | @Test public void responseType() { Type bodyClass = new TypeToken<ListenableFuture<String>>() {}.getType(); assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()) .isEqualTo(String.class); Type bodyWildcard = new TypeToken<ListenableFuture<? extends String>>() {}.getType(); assertThat(factory.get(b... |
DefaultCallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != Call.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalArgumentException( "Call... | @Test public void rawTypeThrows() { try { factory.get(Call.class, NO_ANNOTATIONS, retrofit); fail(); } catch (IllegalArgumentException e) { assertThat(e) .hasMessage("Call return type must be parameterized as Call<Foo> or Call<? extends Foo>"); } }
@Test public void responseType() { Type classType = new TypeToken<Call<... |
GuavaOptionalConverterFactory extends Converter.Factory { public static GuavaOptionalConverterFactory create() { return new GuavaOptionalConverterFactory(); } private GuavaOptionalConverterFactory(); static GuavaOptionalConverterFactory create(); @Override @Nullable Converter<ResponseBody, ?> responseBodyConverter(
... | @Test public void delegates() throws IOException { final Object object = new Object(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory( new Converter.Factory() { @Nullable @Override public Converter<ResponseBody, Object> responseBodyConverter( Type type, Annotation[] annotation... |
Response { public static <T> Response<T> success(@Nullable T body) { return success( body, new okhttp3.Response.Builder() .code(200) .message("OK") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http: .build()); } private Response(
okhttp3.Response rawResponse, @Nullable T body, @Nullable Respo... | @Test public void success() { Object body = new Object(); Response<Object> response = Response.success(body); assertThat(response.raw()).isNotNull(); assertThat(response.code()).isEqualTo(200); assertThat(response.message()).isEqualTo("OK"); assertThat(response.headers().size()).isZero(); assertThat(response.isSuccessf... |
Response { public static <T> Response<T> error(int code, ResponseBody body) { Objects.requireNonNull(body, "body == null"); if (code < 400) throw new IllegalArgumentException("code < 400: " + code); return error( body, new okhttp3.Response.Builder() .body(new OkHttpCall.NoContentResponseBody(body.contentType(), body.co... | @Test public void error() { MediaType plainText = MediaType.get("text/plain; charset=utf-8"); ResponseBody errorBody = ResponseBody.create(plainText, "Broken!"); Response<?> response = Response.error(400, errorBody); assertThat(response.raw()).isNotNull(); assertThat(response.raw().body().contentType()).isEqualTo(plain... |
RxJava3CallAdapterFactory extends CallAdapter.Factory { @SuppressWarnings("ConstantConditions") public static RxJava3CallAdapterFactory createWithScheduler(Scheduler scheduler) { if (scheduler == null) throw new NullPointerException("scheduler == null"); return new RxJava3CallAdapterFactory(scheduler, false); } private... | @Test public void nullSchedulerThrows() { try { RxJava3CallAdapterFactory.createWithScheduler(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("scheduler == null"); } } |
Platform { static Platform get() { return PLATFORM; } Platform(boolean hasJava8Types); } | @Test public void isAndroid() { assertFalse(Platform.get() instanceof Platform.Android); } |
Invocation { public static Invocation of(Method method, List<?> arguments) { Objects.requireNonNull(method, "method == null"); Objects.requireNonNull(arguments, "arguments == null"); return new Invocation(method, new ArrayList<>(arguments)); } Invocation(Method method, List<?> arguments); static Invocation of(Method me... | @Test public void nullMethod() { try { Invocation.of(null, Arrays.asList("one", "two")); fail(); } catch (NullPointerException expected) { assertThat(expected).hasMessage("method == null"); } }
@Test public void nullArguments() { try { Invocation.of(Example.class.getDeclaredMethods()[0], null); fail(); } catch (NullPoi... |
HttpException extends RuntimeException { public @Nullable Response<?> response() { return response; } HttpException(Response<?> response); int code(); String message(); @Nullable Response<?> response(); } | @Test public void response() { Response<String> response = Response.success("Hi"); HttpException exception = new HttpException(response); assertThat(exception.code()).isEqualTo(200); assertThat(exception.message()).isEqualTo("OK"); assertThat(exception.response()).isSameAs(response); } |
Retrofit { public HttpUrl baseUrl() { return baseUrl; } Retrofit(
okhttp3.Call.Factory callFactory,
HttpUrl baseUrl,
List<Converter.Factory> converterFactories,
List<CallAdapter.Factory> callAdapterFactories,
@Nullable Executor callbackExecutor,
boolean validateEagerly); @SuppressWar... | @Test public void baseUrlNullThrows() { try { new Retrofit.Builder().baseUrl((String) null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("baseUrl == null"); } try { new Retrofit.Builder().baseUrl((HttpUrl) null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("baseUrl == nul... |
Retrofit { public @Nullable Executor callbackExecutor() { return callbackExecutor; } Retrofit(
okhttp3.Call.Factory callFactory,
HttpUrl baseUrl,
List<Converter.Factory> converterFactories,
List<CallAdapter.Factory> callAdapterFactories,
@Nullable Executor callbackExecutor,
boolean v... | @Test public void callbackExecutorNullThrows() { try { new Retrofit.Builder().callbackExecutor(null); fail(); } catch (NullPointerException e) { assertThat(e).hasMessage("executor == null"); } } |
CompletableFutureCallAdapterFactory extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != CompletableFuture.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalS... | @Test public void responseType() { Type bodyClass = new TypeToken<CompletableFuture<String>>() {}.getType(); assertThat(factory.get(bodyClass, NO_ANNOTATIONS, retrofit).responseType()) .isEqualTo(String.class); Type bodyWildcard = new TypeToken<CompletableFuture<? extends String>>() {}.getType(); assertThat(factory.get... |
RequestFactory { okhttp3.Request create(Object[] args) throws IOException { @SuppressWarnings("unchecked") ParameterHandler<Object>[] handlers = (ParameterHandler<Object>[]) parameterHandlers; int argumentCount = args.length; if (argumentCount != handlers.length) { throw new IllegalArgumentException( "Argument count ("... | @Test public void customMethodWithBody() { class Example { @HTTP(method = "CUSTOM2", path = "/foo", hasBody = true) Call<ResponseBody> method(@Body RequestBody body) { return null; } } RequestBody body = RequestBody.create(TEXT_PLAIN, "hi"); Request request = buildRequest(Example.class, body); assertThat(request.method... |
NetworkBehavior { public Throwable failureException() { return failureException; } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Guarding API nullability. static NetworkBehavior create(Random random); void setDelay(long amount, TimeUnit unit); long ... | @Test public void defaultThrowable() { Throwable t = behavior.failureException(); assertThat(t) .isInstanceOf(IOException.class) .isExactlyInstanceOf(MockRetrofitIOException.class); assertThat(t.getStackTrace()).isEmpty(); } |
NetworkBehavior { public void setDelay(long amount, TimeUnit unit) { if (amount < 0) { throw new IllegalArgumentException("Amount must be positive value."); } this.delayMs = unit.toMillis(amount); } private NetworkBehavior(Random random); static NetworkBehavior create(); @SuppressWarnings("ConstantConditions") // Guar... | @Test public void delayMustBePositive() { try { behavior.setDelay(-1, SECONDS); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("Amount must be positive value."); } } |
UriTemplateParser { public static void parse(String template, Handler handler) { assert template != null; assert handler != null; int pos = 0; final int length = template.length(); State state = State.OutsideParam; StringBuilder builder = new StringBuilder(); while (pos < length) { char c = template.charAt(pos++); swit... | @Test public void shouldParseParameterFirst() { UriTemplateParser.parse("{a}/bc", handler); verify(handler).handleParam("a"); verify(handler).handleText("/bc"); verifyNoMoreInteractions(handler); }
@Test public void shouldParseParameterLast() { UriTemplateParser.parse("bc/{a}", handler); verify(handler).handleText("bc/... |
WadlXsltUtils { public static String hypernizeURI(String uri) { String result = uri.replaceAll("/", "/​"); return result; } static InputStream getUpgradeTransformAsStream(); static InputStream getWadlSummaryTransform(); static String hypernizeURI(String uri); } | @Test public void hypernizUriTest() { String uri = "http: String result = WadlXsltUtils.hypernizeURI(uri); assertThat(5, equalTo(result.split("&").length)); } |
WadlAstBuilder { public ApplicationNode buildAst(URI rootFile) throws InvalidWADLException, IOException { try { Application a = processDescription(rootFile); return buildAst(a,rootFile); } catch (JAXBException ex) { throw new RuntimeException("Internal error",ex); } } WadlAstBuilder(
SchemaCallback schemaCa... | @Test public void testSoapUIYahooSearch() throws InvalidWADLException, IOException, URISyntaxException { WadlAstBuilder builder = new WadlAstBuilder( new WadlAstBuilder.SchemaCallback() { public void processSchema(InputSource is) { } public void processSchema(String uri, Element node) { } }, new MessageListener() { pub... |
JModule { public String name() { return name; } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final boolean isStatic); void _requires(final String name); void... | @Test public void testName() { final JModule instance = new JModule(MODULE_NAME); assertEquals(MODULE_NAME, instance.name()); } |
JModule { public void _exports(final JPackage pkg) { directives.add(new JExportsDirective(pkg.name())); } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); void _requires(final String name, final boolean isPublic, final ... | @Test public void test_exports() { final JModule instance = new JModule(MODULE_NAME); final JCodeModel cm = new JCodeModel(); final JPackage pkg = new JPackage(PKG_NAME, cm); instance._exports(pkg); JModuleDirective directive = directivesSingleElementCheck(instance); assertTrue(directive instanceof JExportsDirective); ... |
JModule { public void _requires(final String name, final boolean isPublic, final boolean isStatic) { directives.add(new JRequiresDirective(name, isPublic, isStatic)); } JModule(final String name); String name(); void _exports(final JPackage pkg); void _exports(final Collection<JPackage> pkgs, final boolean addEmpty); v... | @Test public void test_requires() { final JModule instance = new JModule(MODULE_NAME); instance._requires(DEP_MODULE_NAME); JModuleDirective directive = directivesSingleElementCheck(instance); assertTrue(directive instanceof JRequiresDirective); assertEquals(DEP_MODULE_NAME, directive.name); } |
JModule { public JFormatter generate(final JFormatter f) { f.p("module").p(name); f.p('{').nl(); if (!directives.isEmpty()) { f.i(); for (final JModuleDirective directive : directives) { directive.generate(f); } f.o(); } f.p('}').nl(); return f; } JModule(final String name); String name(); void _exports(final JPackage ... | @Test public void testGenerate() { final JModule instance = new JModule(MODULE_NAME); instance.generate(jf); final String output = normalizeWhiteSpaces(out.toString()); verifyModuleEnvelope(output, instance); } |
ApNavigator implements Navigator<TypeMirror, TypeElement, VariableElement, ExecutableElement> { public VariableElement[] getEnumConstants(TypeElement clazz) { List<? extends Element> elements = env.getElementUtils().getAllMembers(clazz); Collection<VariableElement> constants = new ArrayList<VariableElement>(); for (Ele... | @Test public void testgetEnumConstantsOrder( @Mocked final ProcessingEnvironment env, @Mocked final TypeElement clazz, @Mocked final VariableElement enumElement1, @Mocked final VariableElement enumElement2, @Mocked final VariableElement enumElement3, @Mocked final VariableElement enumElement4 ) throws Exception { new E... |
SchemaGenerator extends AbstractProcessor { private void filterClass(List<Reference> result, Collection<? extends Element> elements) { for (Element element : elements) { final ElementKind kind = element.getKind(); if (ElementKind.CLASS.equals(kind) || ElementKind.ENUM.equals(kind)) { result.add(new Reference((TypeEleme... | @Test public void filterClassTest( @Mocked Reference ref, @Mocked final TypeElement interfaceElement, @Mocked final TypeElement enumElement, @Mocked final TypeElement classElement, @Mocked final TypeElement nestedClassElement, @Mocked final TypeElement nestedEnumElement) throws Exception { new Expectations() {{ interfa... |
SchemaGenerator { private static String setClasspath(String givenClasspath) { StringBuilder cp = new StringBuilder(); appendPath(cp, givenClasspath); ClassLoader cl = Thread.currentThread().getContextClassLoader(); while (cl != null) { if (cl instanceof URLClassLoader) { for (URL url : ((URLClassLoader) cl).getURLs()) ... | @Test public void setClassPathTest() throws Exception { final URL cUrl = new MockUp<URL>() { String path = "C:"; @Mock public String getPath() { return "/" + path; } @Mock public URI toURI() { return new File(path).toURI(); } }.getMockInstance(); new MockUp<URLClassLoader>() { @Mock URL[] getURLs() { URL[] urls = { cUr... |
PluginImpl extends Plugin { public boolean run(@NotNull Outline model, Options opt, ErrorHandler errorHandler) { checkAndInject(model.getClasses()); checkAndInject(model.getEnums()); return true; } String getOptionName(); List<String> getCustomizationURIs(); boolean isCustomizationTagName(String nsUri, String localNam... | @Test public void pluginRunTest(final @Mocked Outline model, @Mocked Options opt, @Mocked ErrorHandler errorHandler) { new Expectations() {{ Collection<? extends CustomizableOutline> target = Collections.emptyList(); model.getClasses(); result = target; Deencapsulation.invoke(PluginImpl.class, "checkAndInject", target)... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public boolean preBalanceSwitch(ObserverContext<MasterCoprocessorEnvironment> c, boolean newValue) throws IOException { requirePe... | @Test (timeout=180000) public void testBalanceSwitch() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preBalanceSwitch(ObserverContext.createAndPrepare(CP_ENV, null), true); return null; } }; verifyAllowed(action, SUPERUSER, USER_... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preShutdown(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException { requirePermission("shutdown", Actio... | @Test (timeout=180000) public void testShutdown() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preShutdown(ObserverContext.createAndPrepare(CP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROU... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException { requirePermission("stopMaster", A... | @Test (timeout=180000) public void testStopMaster() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preStopMaster(ObserverContext.createAndPrepare(CP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preSplit(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException { requirePermission("split", getTableNam... | @Test (timeout=180000) public void testSplit() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preSplit(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, US... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preMerge(ObserverContext<RegionServerCoprocessorEnvironment> ctx, Region regionA, Region regionB) throws IOException ... | @Test (timeout=180000) public void testMergeRegions() throws Exception { final TableName tname = TableName.valueOf("testMergeRegions"); createTestTable(tname); try { final List<HRegion> regions = TEST_UTIL.getHBaseCluster().findRegionsForTable(tname); assertTrue("not enough regions: " + regions.size(), regions.size() >... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preFlush(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException { requirePermission("flush", getTableNam... | @Test (timeout=180000) public void testFlush() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preFlush(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, US... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public InternalScanner preCompact(ObserverContext<RegionCoprocessorEnvironment> e, final Store store, final InternalScanner scann... | @Test (timeout=180000) public void testCompact() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preCompact(ObserverContext.createAndPrepare(RCP_ENV, null), null, null, ScanType.COMPACT_RETAIN_DELETES); return null; } }; verifyAllo... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void getUserPermissions(RpcController controller, AccessControlProtos.GetUserPermissionsRequest request, RpcCallback<Acces... | @Test (timeout=180000) public void testPermissionList() throws Exception { final TableName tableName = TableName.valueOf("testPermissionList"); final byte[] family1 = Bytes.toBytes("f1"); final byte[] family2 = Bytes.toBytes("f2"); final byte[] qualifier = Bytes.toBytes("q"); Admin admin = TEST_UTIL.getHBaseAdmin(); if... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void checkPermissions(RpcController controller, AccessControlProtos.CheckPermissionsRequest request, RpcCallback<AccessCon... | @Test (timeout=180000) public void testCheckPermissions() throws Exception { AccessTestAction globalAdmin = new AccessTestAction() { @Override public Void run() throws Exception { checkGlobalPerms(TEST_UTIL, Permission.Action.ADMIN); return null; } }; verifyGlobal(globalAdmin); AccessTestAction globalReadWrite = new Ac... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preStopRegionServer( ObserverContext<RegionServerCoprocessorEnvironment> env) throws IOException { requirePermission(... | @Test (timeout=180000) public void testStopRegionServer() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preStopRegionServer(ObserverContext.createAndPrepare(RSCP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USE... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preRollWALWriterRequest(ObserverContext<RegionServerCoprocessorEnvironment> ctx) throws IOException { requirePermissi... | @Test (timeout=180000) public void testRollWALWriterRequest() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preRollWALWriterRequest(ObserverContext.createAndPrepare(RSCP_ENV, null)); return null; } }; verifyAllowed(action, SUPERU... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preOpen(ObserverContext<RegionCoprocessorEnvironment> e) throws IOException { RegionCoprocessorEnvironment env = e.ge... | @Test (timeout=180000) public void testOpenRegion() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preOpen(ObserverContext.createAndPrepare(RCP_ENV, null)); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_GROUP... |
AccessController extends BaseMasterAndRegionObserver implements RegionServerObserver,
AccessControlService.Interface, CoprocessorService, EndpointObserver, BulkLoadObserver { @Override public void preClose(ObserverContext<RegionCoprocessorEnvironment> e, boolean abortRequested) throws IOException { requirePermiss... | @Test (timeout=180000) public void testCloseRegion() throws Exception { AccessTestAction action = new AccessTestAction() { @Override public Object run() throws Exception { ACCESS_CONTROLLER.preClose(ObserverContext.createAndPrepare(RCP_ENV, null), false); return null; } }; verifyAllowed(action, SUPERUSER, USER_ADMIN, U... |
AuthenticationKey implements Writable { @Override public int hashCode() { int result = id; result = 31 * result + (int) (expirationDate ^ (expirationDate >>> 32)); result = 31 * result + ((secret == null) ? 0 : Arrays.hashCode(secret.getEncoded())); return result; } AuthenticationKey(); AuthenticationKey(int keyId, lo... | @Test public void test() throws UnsupportedEncodingException { SecretKey secret = Mockito.mock(SecretKey.class); Mockito.when(secret.getEncoded()).thenReturn("secret".getBytes("UTF-8")); AuthenticationKey key = new AuthenticationKey(0, 1234, secret); assertEquals(key.hashCode(), new AuthenticationKey(0, 1234, secret).h... |
EnforcingScanLabelGenerator implements ScanLabelGenerator { public EnforcingScanLabelGenerator() { this.labelsCache = VisibilityLabelsCache.get(); } EnforcingScanLabelGenerator(); @Override void setConf(Configuration conf); @Override Configuration getConf(); @Override List<String> getLabels(User user, Authorizations au... | @Test public void testEnforcingScanLabelGenerator() throws Exception { final TableName tableName = TableName.valueOf(TEST_NAME.getMethodName()); SUPERUSER.runAs(new PrivilegedExceptionAction<Void>() { public Void run() throws Exception { try (Connection connection = ConnectionFactory.createConnection(conf); Table table... |
HttpServer implements FilterContainer { @Override public String toString() { if (listeners.size() == 0) { return "Inactive HttpServer"; } else { StringBuilder sb = new StringBuilder("HttpServer (") .append(isAlive() ? STATE_DESCRIPTION_ALIVE : STATE_DESCRIPTION_NOT_LIVE).append("), listening at:"); for (ListenerInfo li... | @Test public void testLongHeader() throws Exception { URL url = new URL(baseUrl, "/longheader"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); StringBuilder sb = new StringBuilder(); for (int i = 0 ; i < 63 * 1024; i++) { sb.append("a"); } conn.setRequestProperty("longheader", sb.toString()); asser... |
NamespaceAuditor { public NamespaceTableAndRegionInfo getState(String namespace) { if (stateManager.isInitialized()) { return stateManager.getState(namespace); } return null; } NamespaceAuditor(MasterServices masterServices); void start(); void checkQuotaToCreateTable(TableName tName, int regions); void checkQuotaToUpd... | @Test public void testTableOperations() throws Exception { String nsp = prefix + "_np2"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "5") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build(); ADMIN.createNamespace(nspDesc); asser... |
NamespaceAuditor { public void deleteNamespace(String namespace) throws IOException { stateManager.deleteNamespace(namespace); } NamespaceAuditor(MasterServices masterServices); void start(); void checkQuotaToCreateTable(TableName tName, int regions); void checkQuotaToUpdateRegion(TableName tName, int regions); int get... | @Test public void testRecreateTableWithSameNameAfterFirstTimeFailure() throws Exception { String nsp1 = prefix + "_testRecreateTable"; NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1) .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20") .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1"... |
HttpServer implements FilterContainer { public static boolean hasAdministratorAccess( ServletContext servletContext, HttpServletRequest request, HttpServletResponse response) throws IOException { Configuration conf = (Configuration) servletContext.getAttribute(CONF_CONTEXT_ATTRIBUTE); if (!conf.getBoolean( CommonConfig... | @Test public void testHasAdministratorAccess() throws Exception { Configuration conf = new Configuration(); conf.setBoolean(CommonConfigurationKeys.HADOOP_SECURITY_AUTHORIZATION, false); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(context.getAttribute(HttpServer.CONF_CONTEXT_ATTRIBUTE)).th... |
MultiTableSnapshotInputFormatImpl { public Map<String, Collection<Scan>> getSnapshotsToScans(Configuration conf) throws IOException { Map<String, Collection<Scan>> rtn = Maps.newHashMap(); for (Map.Entry<String, String> entry : ConfigurationUtil .getKeyValues(conf, SNAPSHOT_TO_SCANS_KEY)) { String snapshotName = entry.... | @Test public void testSetInputSetsSnapshotToScans() throws Exception { callSetInput(); Map<String, Collection<Scan>> actual = subject.getSnapshotsToScans(conf); Map<String, Collection<ScanWithEquals>> actualWithEquals = toScanWithEquals(actual); Map<String, Collection<ScanWithEquals>> expectedWithEquals = toScanWithEqu... |
MultiTableSnapshotInputFormatImpl { public Map<String, Path> getSnapshotDirs(Configuration conf) throws IOException { List<Map.Entry<String, String>> kvps = ConfigurationUtil.getKeyValues(conf, RESTORE_DIRS_KEY); Map<String, Path> rtn = Maps.newHashMapWithExpectedSize(kvps.size()); for (Map.Entry<String, String> kvp : ... | @Test public void testSetInputPushesRestoreDirectories() throws Exception { callSetInput(); Map<String, Path> restoreDirs = subject.getSnapshotDirs(conf); assertEquals(this.snapshotScans.keySet(), restoreDirs.keySet()); }
@Test public void testSetInputCreatesRestoreDirectoriesUnderRootRestoreDir() throws Exception { ca... |
TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public int hashCode() { int result = tableName != null ? tableName.hashCode() : 0; result = 31 * result + (scan != null ? scan.hashCode() : 0); result = 31 * result + (startRow != null ? Arrays.hashCode(startRow) : 0); result = 31 * r... | @Test public void testHashCode() { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location"); TableSplit split2 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location"); assertEquals (split1, split2); assertTrue... |
TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public long getLength() { return length; } TableSplit(); @Deprecated TableSplit(final byte [] tableName, Scan scan, byte [] startRow, byte [] endRow,
final String location); TableSplit(TableName tableName, Scan scan, byte [] s... | @Test public void testLengthIsSerialized() throws Exception { TableSplit split1 = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location", 666); TableSplit deserialized = new TableSplit(TableName.valueOf("table"), "row-start2".getBytes(), "row-end2".getBytes(), "location1"); ... |
TableSplit extends InputSplit implements Writable, Comparable<TableSplit> { @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HBase table split("); sb.append("table name: ").append(tableName); sb.append(", scan: ").append(scan); sb.append(", start row: ").append(Bytes.toStringBinar... | @Test public void testToString() { TableSplit split = new TableSplit(TableName.valueOf("table"), "row-start".getBytes(), "row-end".getBytes(), "location"); String str = "HBase table split(table name: table, scan: , start row: row-start, " + "end row: row-end, region location: location)"; Assert.assertEquals(str, split.... |
HashTable extends Configured implements Tool { public HashTable(Configuration conf) { super(conf); } HashTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testHashTable() throws Exception { final String tableName = "testHashTable"; final byte[] family = Bytes.toBytes("family"); final byte[] column1 = Bytes.toBytes("c1"); final byte[] column2 = Bytes.toBytes("c2"); final byte[] column3 = Bytes.toBytes("c3"); int numRows = 100; int numRegions = 10; int nu... |
TableInputFormatBase extends InputFormat<ImmutableBytesWritable, Result> { @Deprecated public String reverseDNS(InetAddress ipAddress) throws NamingException, UnknownHostException { String hostName = this.reverseDNSCacheMap.get(ipAddress); if (hostName == null) { String ipAddressString = null; try { ipAddressString = D... | @Test public void testTableInputFormatBaseReverseDNSForIPv6() throws UnknownHostException, NamingException { String address = "ipv6.google.com"; String localhost = null; InetAddress addr = null; TableInputFormat inputFormat = new TableInputFormat(); try { localhost = InetAddress.getByName(address).getCanonicalHostName(... |
LoadIncrementalHFiles extends Configured implements Tool { protected List<LoadQueueItem> splitStoreFile(final LoadQueueItem item, final Table table, byte[] startKey, byte[] splitKey) throws IOException { final Path hfilePath = item.hfilePath; final String TMP_DIR = "_tmp"; Path tmpDir = item.hfilePath.getParent(); if (... | @Test(timeout = 120000) public void testSplitStoreFile() throws IOException { Path dir = util.getDataTestDirOnTestFS("testSplitHFile"); FileSystem fs = util.getTestFileSystem(); Path testIn = new Path(dir, "testhfile"); HColumnDescriptor familyDesc = new HColumnDescriptor(FAMILY); HFileTestUtil.createHFile(util.getConf... |
HttpServer implements FilterContainer { public void stop() throws Exception { MultiException exception = null; for (ListenerInfo li : listeners) { if (!li.isManaged) { continue; } try { li.listener.close(); } catch (Exception e) { LOG.error( "Error while stopping listener for webapp" + webAppContext.getDisplayName(), e... | @Test public void testHttpServerBuilderWithExternalConnector() throws Exception { Connector c = mock(Connector.class); doReturn("localhost").when(c).getHost(); HttpServer s = new HttpServer.Builder().setName("test").setConnector(c) .build(); s.stop(); } |
LoadIncrementalHFiles extends Configured implements Tool { public static byte[][] inferBoundaries(TreeMap<byte[], Integer> bdryMap) { ArrayList<byte[]> keysArray = new ArrayList<byte[]>(); int runningValue = 0; byte[] currStartKey = null; boolean firstBoundary = true; for (Map.Entry<byte[], Integer> item: bdryMap.entry... | @Test(timeout = 120000) public void testInferBoundaries() { TreeMap<byte[], Integer> map = new TreeMap<byte[], Integer>(Bytes.BYTES_COMPARATOR); String first; String last; first = "a"; last = "e"; addStartEndKeysForTest(map, first.getBytes(), last.getBytes()); first = "r"; last = "s"; addStartEndKeysForTest(map, first.... |
LoadIncrementalHFiles extends Configured implements Tool { @Override public int run(String[] args) throws Exception { if (args.length != 2) { usage(); return -1; } initialize(); String dirPath = args[0]; TableName tableName = TableName.valueOf(args[1]); boolean tableExists = this.doesTableExist(tableName); if (!tableEx... | @Test(timeout = 60000) public void testLoadTooMayHFiles() throws Exception { Path dir = util.getDataTestDirOnTestFS("testLoadTooMayHFiles"); FileSystem fs = util.getTestFileSystem(); dir = dir.makeQualified(fs); Path familyDir = new Path(dir, Bytes.toString(FAMILY)); byte[] from = Bytes.toBytes("begin"); byte[] to = By... |
CopyTable extends Configured implements Tool { public CopyTable(Configuration conf) { super(conf); } CopyTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testCopyTable() throws Exception { doCopyTableTest(false); } |
CopyTable extends Configured implements Tool { @Override public int run(String[] args) throws Exception { String[] otherArgs = new GenericOptionsParser(getConf(), args).getRemainingArgs(); Job job = createSubmittableJob(otherArgs); if (job == null) return 1; if (!job.waitForCompletion(true)) { LOG.info("Map-reduce job ... | @Test public void testStartStopRow() throws Exception { final TableName TABLENAME1 = TableName.valueOf("testStartStopRow1"); final TableName TABLENAME2 = TableName.valueOf("testStartStopRow2"); final byte[] FAMILY = Bytes.toBytes("family"); final byte[] COLUMN1 = Bytes.toBytes("c1"); final byte[] ROW0 = Bytes.toBytes("... |
CopyTable extends Configured implements Tool { public static void main(String[] args) throws Exception { int ret = ToolRunner.run(new CopyTable(HBaseConfiguration.create()), args); System.exit(ret); } CopyTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int ... | @Test public void testMainMethod() throws Exception { String[] emptyArgs = { "-h" }; PrintStream oldWriter = System.err; ByteArrayOutputStream data = new ByteArrayOutputStream(); PrintStream writer = new PrintStream(data); System.setErr(writer); SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSe... |
ImportTsv extends Configured implements Tool { private static void createTable(Admin admin, TableName tableName, String[] columns) throws IOException { HTableDescriptor htd = new HTableDescriptor(tableName); Set<String> cfSet = getColumnFamilies(columns); for (String cf : cfSet) { HColumnDescriptor hcd = new HColumnDes... | @Test public void testMROnTable() throws Exception { String table = "test-" + UUID.randomUUID(); String[] args = new String[] { "-D" + ImportTsv.COLUMNS_CONF_KEY + "=HBASE_ROW_KEY,FAM:A,FAM:B", "-D" + ImportTsv.SEPARATOR_CONF_KEY + "=\u001b", table }; util.createTable(TableName.valueOf(table), FAMILY); doMROnTableTest(... |
ImportTsv extends Configured implements Tool { public static Job createSubmittableJob(Configuration conf, String[] args) throws IOException, ClassNotFoundException { Job job = null; try (Connection connection = ConnectionFactory.createConnection(conf)) { try (Admin admin = connection.getAdmin()) { String actualSeparato... | @Test public void testJobConfigurationsWithTsvImporterTextMapper() throws Exception { String table = "test-" + UUID.randomUUID(); Path bulkOutputPath = new Path(util.getDataTestDirOnTestFS(table),"hfiles"); String INPUT_FILE = "InputFile1.csv"; String[] args = new String[] { "-D" + ImportTsv.MAPPER_CONF_KEY + "=org.apa... |
TableMapReduceUtil { public static void initTableMapperJob(String table, Scan scan, Class<? extends TableMapper> mapper, Class<?> outputKeyClass, Class<?> outputValueClass, Job job) throws IOException { initTableMapperJob(table, scan, mapper, outputKeyClass, outputValueClass, job, true); } static void initTableMapperJ... | @Test public void testInitTableMapperJob1() throws Exception { Configuration configuration = new Configuration(); Job job = new Job(configuration, "tableName"); TableMapReduceUtil.initTableMapperJob("Table", new Scan(), Import.Importer.class, Text.class, Text.class, job, false, WALInputFormat.class); assertEquals(WALIn... |
FSHDFSUtils extends FSUtils { boolean recoverLease(final DistributedFileSystem dfs, final int nbAttempt, final Path p, final long startWaiting) throws FileNotFoundException { boolean recovered = false; try { recovered = dfs.recoverLease(p); LOG.info((recovered? "Recovered lease, ": "Failed to recover lease, ") + getLog... | @Test (timeout = 30000) public void testRecoverLease() throws IOException { HTU.getConfiguration().setInt("hbase.lease.recovery.dfs.timeout", 1000); CancelableProgressable reporter = Mockito.mock(CancelableProgressable.class); Mockito.when(reporter.progress()).thenReturn(true); DistributedFileSystem dfs = Mockito.mock(... |
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { @Override public RecordWriter<ImmutableBytesWritable, KeyValue> getRecordWriter( final TaskAttemptContext context) throws IOException, InterruptedException { return HFileOutputFormat2.createRecordWriter(context); } @Override RecordWriter<Im... | @Test public void test_LATEST_TIMESTAMP_isReplaced() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, KeyValue> writer = null; TaskAttemptContext context = null; Path dir = util.getDataTestDir("test_LATEST_TIMESTAMP_isReplaced"); try { Job job... |
HFileOutputFormat extends FileOutputFormat<ImmutableBytesWritable, KeyValue> { public static void configureIncrementalLoad(Job job, HTable table) throws IOException { HFileOutputFormat2.configureIncrementalLoad(job, table.getTableDescriptor(), table.getRegionLocator()); } @Override RecordWriter<ImmutableBytesWritable,... | @Test public void testJobConfiguration() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); conf.set("hbase.fs.tmp.dir", util.getDataTestDir("testJobConfiguration").toString()); Job job = new Job(conf); job.setWorkingDirectory(util.getDataTestDir("testJobConfiguration")); HTableDes... |
SyncTable extends Configured implements Tool { public SyncTable(Configuration conf) { super(conf); } SyncTable(Configuration conf); Job createSubmittableJob(String[] args); static void main(String[] args); @Override int run(String[] args); } | @Test public void testSyncTable() throws Exception { String sourceTableName = "testSourceTable"; String targetTableName = "testTargetTable"; Path testDir = TEST_UTIL.getDataTestDirOnTestFS("testSyncTable"); writeTestData(sourceTableName, targetTableName); hashSourceTable(sourceTableName, testDir); Counters syncCounters... |
HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> { @Override public RecordWriter<ImmutableBytesWritable, Cell> getRecordWriter( final TaskAttemptContext context) throws IOException, InterruptedException { return createRecordWriter(context); } @Override RecordWriter<ImmutableBytesWritable, Cell... | @Ignore("Goes zombie too frequently; needs work. See HBASE-14563") @Test public void test_LATEST_TIMESTAMP_isReplaced() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); RecordWriter<ImmutableBytesWritable, Cell> writer = null; TaskAttemptContext context = null; Path dir = util.ge... |
HFileOutputFormat2 extends FileOutputFormat<ImmutableBytesWritable, Cell> { @Deprecated public static void configureIncrementalLoad(Job job, HTable table) throws IOException { configureIncrementalLoad(job, table.getTableDescriptor(), table.getRegionLocator()); } @Override RecordWriter<ImmutableBytesWritable, Cell> get... | @Ignore("Goes zombie too frequently; needs work. See HBASE-14563") @Test public void testJobConfiguration() throws Exception { Configuration conf = new Configuration(this.util.getConfiguration()); conf.set(HConstants.TEMPORARY_FS_DIRECTORY_KEY, util.getDataTestDir("testJobConfiguration") .toString()); Job job = new Job... |
JarFinder { public static String getJar(Class klass) { Preconditions.checkNotNull(klass, "klass"); ClassLoader loader = klass.getClassLoader(); if (loader != null) { String class_file = klass.getName().replaceAll("\\.", "/") + ".class"; try { for (Enumeration itr = loader.getResources(class_file); itr.hasMoreElements()... | @Test public void testJar() throws Exception { String jar = JarFinder.getJar(LogFactory.class); Assert.assertTrue(new File(jar).exists()); }
@Test public void testExpandedClasspath() throws Exception { String jar = JarFinder.getJar(TestJarFinder.class); Assert.assertTrue(new File(jar).exists()); } |
CellCounter { public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs(); if (otherArgs.length < 2) { System.err.println("ERROR: Wrong number of parameters: " + args.length); System.err.println(... | @Test (timeout=300000) public void testCellCounterMain() throws Exception { PrintStream oldPrintStream = System.err; SecurityManager SECURITY_MANAGER = System.getSecurityManager(); LauncherSecurityManager newSecurityManager= new LauncherSecurityManager(); System.setSecurityManager(newSecurityManager); ByteArrayOutputSt... |
ReplicationSink { public void replicateEntries(List<WALEntry> entries, final CellScanner cells) throws IOException { if (entries.isEmpty()) return; if (cells == null) throw new NullPointerException("TODO: Add handling of null CellScanner"); try { long totalReplicated = 0; Map<TableName, Map<List<UUID>, List<Row>>> rowM... | @Test public void testBatchSink() throws Exception { List<WALEntry> entries = new ArrayList<WALEntry>(BATCH_SIZE); List<Cell> cells = new ArrayList<Cell>(); for(int i = 0; i < BATCH_SIZE; i++) { entries.add(createEntry(TABLE_NAME1, i, KeyValue.Type.Put, cells)); } SINK.replicateEntries(entries, CellUtil.createCellScann... |
ReplicationSourceManager implements ReplicationListener { protected void init() throws IOException, ReplicationException { for (String id : this.replicationPeers.getPeerIds()) { addSource(id); } List<String> currentReplicators = this.replicationQueues.getListOfReplicators(); if (currentReplicators == null || currentRep... | @Test public void testClaimQueues() throws Exception { LOG.debug("testNodeFailoverWorkerCopyQueuesFromRSUsingMulti"); conf.setBoolean(HConstants.ZOOKEEPER_USEMULTI, true); final Server server = new DummyServer("hostname0.example.org"); ReplicationQueues rq = ReplicationFactory.getReplicationQueues(server.getZooKeeper()... |
FSHDFSUtils extends FSUtils { public static boolean isSameHdfs(Configuration conf, FileSystem srcFs, FileSystem desFs) { String srcServiceName = srcFs.getCanonicalServiceName(); String desServiceName = desFs.getCanonicalServiceName(); if (srcServiceName == null || desServiceName == null) { return false; } if (srcServic... | @Test public void testIsSameHdfs() throws IOException { try { Class dfsUtilClazz = Class.forName("org.apache.hadoop.hdfs.DFSUtil"); dfsUtilClazz.getMethod("getNNServiceRpcAddresses", Configuration.class); } catch (Exception e) { LOG.info("Skip testIsSameHdfs test case because of the no-HA hadoop version."); return; } C... |
ReplicationSinkManager { public synchronized void chooseSinks() { List<ServerName> slaveAddresses = endpoint.getRegionServers(); Collections.shuffle(slaveAddresses, random); int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio); sinks = slaveAddresses.subList(0, numSinks); lastUpdateToPeers = System.currentTime... | @Test public void testChooseSinks() { List<ServerName> serverNames = Lists.newArrayList(); for (int i = 0; i < 20; i++) { serverNames.add(mock(ServerName.class)); } when(replicationEndpoint.getRegionServers()) .thenReturn(serverNames); sinkManager.chooseSinks(); assertEquals(2, sinkManager.getNumSinks()); } |
ReplicationSinkManager { public synchronized void reportBadSink(SinkPeer sinkPeer) { ServerName serverName = sinkPeer.getServerName(); int badReportCount = (badReportCounts.containsKey(serverName) ? badReportCounts.get(serverName) : 0) + 1; badReportCounts.put(serverName, badReportCount); if (badReportCount > badSinkTh... | @Test public void testReportBadSink() { ServerName serverNameA = mock(ServerName.class); ServerName serverNameB = mock(ServerName.class); when(replicationEndpoint.getRegionServers()) .thenReturn(Lists.newArrayList(serverNameA, serverNameB)); sinkManager.chooseSinks(); assertEquals(1, sinkManager.getNumSinks()); SinkPee... |
ConfigurationManager { public void notifyAllObservers(Configuration conf) { LOG.info("Starting to notify all observers that config changed."); synchronized (configurationObservers) { for (ConfigurationObserver observer : configurationObservers) { try { if (observer != null) { observer.onConfigurationChange(conf); } } c... | @Test public void testCheckIfObserversNotified() { Configuration conf = new Configuration(); ConfigurationManager cm = new ConfigurationManager(); DummyConfigurationObserver d1 = new DummyConfigurationObserver(cm); cm.notifyAllObservers(conf); assertTrue(d1.wasNotifiedOnChange()); d1.resetNotifiedOnChange(); DummyConfi... |
DefaultWALProvider implements WALProvider { public static ServerName getServerNameFromWALDirectoryName(Configuration conf, String path) throws IOException { if (path == null || path.length() <= HConstants.HREGION_LOGDIR_NAME.length()) { return null; } if (conf == null) { throw new IllegalArgumentException("parameter co... | @Test public void testGetServerNameFromWALDirectoryName() throws IOException { ServerName sn = ServerName.valueOf("hn", 450, 1398); String hl = FSUtils.getRootDir(conf) + "/" + DefaultWALProvider.getWALDirectoryName(sn.toString()); assertNull(DefaultWALProvider.getServerNameFromWALDirectoryName(conf, null)); assertNull... |
BoundedRegionGroupingProvider extends RegionGroupingProvider { @Override public void close() throws IOException { IOException failure = null; for (WALProvider provider : delegates) { try { provider.close(); } catch (IOException exception) { LOG.error("Problem closing provider '" + provider + "': " + exception.getMessag... | @Test public void setMembershipDedups() throws IOException { final int temp = conf.getInt(NUM_REGION_GROUPS, DEFAULT_NUM_REGION_GROUPS); WALFactory wals = null; try { conf.setInt(NUM_REGION_GROUPS, temp*4); FSUtils.setRootDir(conf, TEST_UTIL.getDataTestDirOnTestFS()); wals = new WALFactory(conf, null, currentTest.getMe... |
WALFactory { public WAL getWAL(final byte[] identifier) throws IOException { return provider.getWAL(identifier); } private WALFactory(Configuration conf); WALFactory(final Configuration conf, final List<WALActionsListener> listeners,
final String factoryId); void close(); void shutdown(); WAL getWAL(final byte[... | @Test public void testVisitors() throws Exception { final int COL_COUNT = 10; final TableName tableName = TableName.valueOf("tablename"); final byte [] row = Bytes.toBytes("row"); final DumbWALActionsListener visitor = new DumbWALActionsListener(); final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrency... |
FSTableDescriptors implements TableDescriptors { @VisibleForTesting static int getTableInfoSequenceId(final Path p) { if (p == null) return 0; Matcher m = TABLEINFO_FILE_REGEX.matcher(p.getName()); if (!m.matches()) throw new IllegalArgumentException(p.toString()); String suffix = m.group(2); if (suffix == null || suff... | @Test (expected=IllegalArgumentException.class) public void testRegexAgainstOldStyleTableInfo() { Path p = new Path("/tmp", FSTableDescriptors.TABLEINFO_FILE_PREFIX); int i = FSTableDescriptors.getTableInfoSequenceId(p); assertEquals(0, i); p = new Path("/tmp", "abc"); FSTableDescriptors.getTableInfoSequenceId(p); } |
ZooKeeperMainServer { public String parse(final Configuration c) { return ZKConfig.getZKQuorumServersString(c); } String parse(final Configuration c); static void main(String args[]); } | @Test public void testHostPortParse() { ZooKeeperMainServer parser = new ZooKeeperMainServer(); 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.zo... |
CoprocessorHost { protected void loadSystemCoprocessors(Configuration conf, String confKey) { boolean coprocessorsEnabled = conf.getBoolean(COPROCESSORS_ENABLED_CONF_KEY, DEFAULT_COPROCESSORS_ENABLED); if (!coprocessorsEnabled) { return; } Class<?> implClass = null; String[] defaultCPClasses = conf.getStrings(confKey);... | @Test public void testDoubleLoading() { final Configuration conf = HBaseConfiguration.create(); CoprocessorHost<CoprocessorEnvironment> host = new CoprocessorHost<CoprocessorEnvironment>(new TestAbortable()) { final Configuration cpHostConf = conf; @Override public CoprocessorEnvironment createEnvironment(Class<?> impl... |
FSTableDescriptors implements TableDescriptors { private 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(fi... | @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_FILE_PREFIX + "." + sb.toString(), p0.getName()); Path p2... |
HttpRequestLog { public static RequestLog getRequestLog(String name) { String lookup = serverToComponent.get(name); if (lookup != null) { name = lookup; } String loggerName = "http.requests." + name; String appenderName = name + "requestlog"; Log logger = LogFactory.getLog(loggerName); if (logger instanceof Log4JLogger... | @Test public void testAppenderUndefined() { RequestLog requestLog = HttpRequestLog.getRequestLog("test"); assertNull("RequestLog should be null", requestLog); }
@Test public void testAppenderDefined() { HttpRequestLogAppender requestLogAppender = new HttpRequestLogAppender(); requestLogAppender.setName("testrequestlog"... |
RegionPlan implements Comparable<RegionPlan> { @Override public int hashCode() { return getRegionName().hashCode(); } RegionPlan(final HRegionInfo hri, ServerName source, ServerName dest); void setDestination(ServerName dest); ServerName getSource(); ServerName getDestination(); String getRegionName(); HRegionInfo getR... | @Test public void test() { HRegionInfo hri = new HRegionInfo(TableName.valueOf("table")); ServerName source = ServerName.valueOf("source", 1234, 2345); ServerName dest = ServerName.valueOf("dest", 1234, 2345); RegionPlan plan = new RegionPlan(hri, source, dest); assertEquals(plan.hashCode(), new RegionPlan(hri, source,... |
HMasterCommandLine extends ServerCommandLine { public int run(String args[]) throws Exception { Options opt = new Options(); opt.addOption("localRegionServers", true, "RegionServers to start in master process when running standalone"); opt.addOption("masters", true, "Masters to start in this process"); opt.addOption("m... | @Test public void testRun() throws Exception { HMasterCommandLine masterCommandLine = new HMasterCommandLine(HMaster.class); masterCommandLine.setConf(TESTING_UTIL.getConfiguration()); assertEquals(0, masterCommandLine.run(new String [] {"clear"})); } |
ActiveMasterManager extends ZooKeeperListener { boolean blockUntilBecomingActiveMaster( int checkInterval, MonitoredTask startupStatus) { String backupZNode = ZKUtil.joinZNode( this.watcher.backupMasterAddressesZNode, this.sn.toString()); while (!(master.isAborted() || master.isStopped())) { startupStatus.setStatus("Tr... | @Test public void testRestartMaster() throws IOException, KeeperException { ZooKeeperWatcher zk = new ZooKeeperWatcher(TEST_UTIL.getConfiguration(), "testActiveMasterManagerFromZK", null, true); try { ZKUtil.deleteNode(zk, zk.getMasterAddressZNode()); ZKUtil.deleteNode(zk, zk.clusterStateZNode); } catch(KeeperException... |
ServerAndLoad implements Comparable<ServerAndLoad>, Serializable { @Override public int hashCode() { int result = load; result = 31 * result + ((sn == null) ? 0 : sn.hashCode()); return result; } ServerAndLoad(final ServerName sn, final int load); @Override int compareTo(ServerAndLoad other); @Override int hashCode(); ... | @Test public void test() { ServerName server = ServerName.valueOf("host", 12345, 112244); int startcode = 12; ServerAndLoad sal = new ServerAndLoad(server, startcode); assertEquals(sal.hashCode(), new ServerAndLoad(server, startcode).hashCode()); assertEquals(sal, new ServerAndLoad(server, startcode)); assertNotEquals(... |
FavoredNodeAssignmentHelper { void placePrimaryRSAsRoundRobin(Map<ServerName, List<HRegionInfo>> assignmentMap, Map<HRegionInfo, ServerName> primaryRSMap, List<HRegionInfo> regions) { List<String> rackList = new ArrayList<String>(rackToRegionServerMap.size()); rackList.addAll(rackToRegionServerMap.keySet()); int rackIn... | @Ignore("Disabled for now until FavoredNodes gets finished as a feature") @Test public void testPlacePrimaryRSAsRoundRobin() { primaryRSPlacement(6, null, 10, 10, 10); primaryRSPlacement(600, null, 10, 10, 10); } |
FavoredNodeAssignmentHelper { Map<HRegionInfo, ServerName[]> placeSecondaryAndTertiaryRS( Map<HRegionInfo, ServerName> primaryRSMap) { Map<HRegionInfo, ServerName[]> secondaryAndTertiaryMap = new HashMap<HRegionInfo, ServerName[]>(); for (Map.Entry<HRegionInfo, ServerName> entry : primaryRSMap.entrySet()) { HRegionInfo... | @Ignore("Disabled for now until FavoredNodes gets finished as a feature") @Test public void testSecondaryAndTertiaryPlacementWithSingleRack() { Map<String,Integer> rackToServerCount = new HashMap<String,Integer>(); rackToServerCount.put("rack1", 10); Triple<Map<HRegionInfo, ServerName>, FavoredNodeAssignmentHelper, Lis... |
FSTableDescriptors implements TableDescriptors { @Override public Map<String, HTableDescriptor> getAll() throws IOException { Map<String, HTableDescriptor> htds = new TreeMap<String, HTableDescriptor>(); if (fsvisited && usecache) { for (Map.Entry<TableName, HTableDescriptor> entry: this.cache.entrySet()) { htds.put(en... | @Test public void testGetAll() throws IOException, InterruptedException { final String name = "testGetAll"; FileSystem fs = FileSystem.get(UTIL.getConfiguration()); Path rootdir = new Path(UTIL.getDataTestDir(), name); FSTableDescriptors htds = new FSTableDescriptorsTest(fs, rootdir); final int count = 4; for (int i = ... |
BaseLoadBalancer implements LoadBalancer { @Override public Map<HRegionInfo, ServerName> immediateAssignment(List<HRegionInfo> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); if (servers == null || servers.isEmpty()) { LOG.warn("Wanted to do random assignment but no servers to assign to"); r... | @Test (timeout=30000) 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... |
BaseLoadBalancer implements LoadBalancer { @Override public Map<ServerName, List<HRegionInfo>> roundRobinAssignment(List<HRegionInfo> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); Map<ServerName, List<HRegionInfo>> assignments = assignMasterRegions(regions, servers); if (assignments != nul... | @Test (timeout=180000) 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); Li... |
BaseLoadBalancer implements LoadBalancer { @Override public Map<ServerName, List<HRegionInfo>> retainAssignment(Map<HRegionInfo, ServerName> regions, List<ServerName> servers) { metricsBalancer.incrMiscInvocations(); Map<ServerName, List<HRegionInfo>> assignments = assignMasterRegions(regions.keySet(), servers); if (as... | @Test (timeout=180000) public void testRetainAssignment() throws Exception { List<ServerAndLoad> servers = randomServers(10, 10); List<HRegionInfo> regions = randomRegions(100); Map<HRegionInfo, ServerName> existing = new TreeMap<HRegionInfo, ServerName>(); for (int i = 0; i < regions.size(); i++) { ServerName sn = ser... |
RegionLocationFinder { protected HDFSBlocksDistribution internalGetTopBlockLocation(HRegionInfo region) { try { HTableDescriptor tableDescriptor = getTableDescriptor(region.getTable()); if (tableDescriptor != null) { HDFSBlocksDistribution blocksDistribution = HRegion.computeHDFSBlocksDistribution(getConf(), tableDescr... | @Test public void testInternalGetTopBlockLocation() throws Exception { for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); for (Region region : server.getOnlineRegions(tableName)) { HDFSBlocksDistribution blocksDistribution1 = region.getHDFSBlocksDistribution(); HDFSBlocksDistributi... |
RegionLocationFinder { protected List<ServerName> mapHostNameToServerName(List<String> hosts) { if (hosts == null || status == null) { if (hosts == null) { LOG.warn("RegionLocationFinder top hosts is null"); } return Lists.newArrayList(); } List<ServerName> topServerNames = new ArrayList<ServerName>(); Collection<Serve... | @Test public void testMapHostNameToServerName() throws Exception { List<String> topHosts = new ArrayList<String>(); for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); String serverHost = server.getServerName().getHostname(); if (!topHosts.contains(serverHost)) { topHosts.add(server... |
RegionLocationFinder { protected List<ServerName> getTopBlockLocations(HRegionInfo region) { HDFSBlocksDistribution blocksDistribution = getBlockDistribution(region); List<String> topHosts = blocksDistribution.getTopHosts(); return mapHostNameToServerName(topHosts); } RegionLocationFinder(); Configuration getConf(); vo... | @Test public void testGetTopBlockLocations() throws Exception { for (int i = 0; i < ServerNum; i++) { HRegionServer server = cluster.getRegionServer(i); for (Region region : server.getOnlineRegions(tableName)) { List<ServerName> servers = finder.getTopBlockLocations(region.getRegionInfo()); if (region.getHDFSBlocksDist... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.