method2testcases
stringlengths 118
3.08k
|
---|
### Question:
AbstractEnvironmentEnricher implements EnvironmentEnricher<E> { @VisibleForTesting static void validateSchemaName(String schemaName) { if (!PATTERN.matcher(schemaName).matches()) { throw new IllegalArgumentException("SchemaName " + schemaName + " does not match regexp " + PATTERN.pattern()); } } @Override ImmutableCollection<E> readSystem(final HierarchicalConfiguration sysCfg, final FileObject sourcePath); @Override E readEnvironment(ImmutableHierarchicalConfiguration combinedConfiguration, FileObject sourcePath); }### Answer:
@Test public void validSchemaName() { AbstractEnvironmentEnricher.validateSchemaName("AbcDef123_456_98"); }
@Test public void invalidSchemaName() { thrown.expect(IllegalArgumentException.class); AbstractEnvironmentEnricher.validateSchemaName("abc.def"); } |
### Question:
AseToH2SqlTranslator implements PostColumnSqlTranslator, PostParsedSqlTranslator { @Override public String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table) { sql = sql.replaceAll("(?i)\\bidentity\\s*(\\(.*\\))?", "AUTO_INCREMENT "); return sql; } @Override String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table); @Override String handleAnySqlPostTranslation(String string, ChangeInput change); }### Answer:
@Test public void testPostColumnIdentity() throws Exception { assertEquals("AUTO_INCREMENT NOT NULL", this.translator.handlePostColumnText("IDENTITY NOT NULL", null, null)); assertEquals(" AUTO_INCREMENT NOT NULL", this.translator.handlePostColumnText(" IDENTITY NOT NULL", null, null)); assertEquals("sometext AUTO_INCREMENT NOT NULL", this.translator.handlePostColumnText("sometext IDENTITY NOT NULL", null, null)); } |
### Question:
AseRenameTranslator implements UnparsedSqlTranslator { @Override public String handleRawFullSql(String sql, ChangeInput change) { Matcher matcher = SP_RENAME_PATTERN.matcher(sql); if (matcher.find()) { String replacementSql = " ALTER TABLE " + matcher.group(1) + " ALTER COLUMN " + matcher.group(2) + " RENAME TO " + matcher.group(3); return matcher.replaceFirst(replacementSql); } return sql; } @Override String handleRawFullSql(String sql, ChangeInput change); }### Answer:
@Test public void translateSpRename() throws Exception { assertThat(translator.handleRawFullSql("sp_rename 'mytab.mycol', 'mynewcol'", null), equalToIgnoringWhiteSpace("ALTER TABLE mytab ALTER COLUMN mycol RENAME TO mynewcol")); }
@Test public void translateSpRenameWithOtherText() throws Exception { assertThat(translator.handleRawFullSql("[with surrounding]\t\n[text] sp_rename 'mytab.mycol', 'mynewcol' [before\n\tand after]", null), equalToIgnoringWhiteSpace("[with surrounding] [text] ALTER TABLE mytab ALTER COLUMN mycol RENAME TO mynewcol [before and after]")); } |
### Question:
AseToHsqlSqlTranslator implements ColumnSqlTranslator, PostColumnSqlTranslator, PostParsedSqlTranslator { @Override public String handleAnySqlPostTranslation(String string, ChangeInput change) { if (change != null && change.getMetadataSection() != null && change.getMetadataSection().isTogglePresent(TextMarkupDocumentReader.TOGGLE_DISABLE_QUOTED_IDENTIFIERS)) { if (!change.getChangeKey().getChangeType().getName().equals(ChangeType.VIEW_STR)) { string = string.replace('"', '\''); } } Matcher varbinaryDefaultMatcher = this.varbinaryDefaultPattern.matcher(string); if (varbinaryDefaultMatcher.find()) { string = varbinaryDefaultMatcher.replaceFirst("varbinary(1)" + varbinaryDefaultMatcher.group(1)); } return string; } @Override String handleAnySqlPostTranslation(String string, ChangeInput change); @Override String handlePostColumnText(String postColumnText, CreateTableColumn column, CreateTable table); @Override CreateTableColumn handleColumn(CreateTableColumn column, CreateTable table); }### Answer:
@Test public void testVarbinaryChange() { assertEquals("varbinary(1)not null", this.translator.handleAnySqlPostTranslation("varbinary not null", null)); assertEquals("varbinary(32) not null", this.translator.handleAnySqlPostTranslation("varbinary(32) not null", null)); } |
### Question:
AseToHsqlSqlTranslator implements ColumnSqlTranslator, PostColumnSqlTranslator, PostParsedSqlTranslator { @Override public String handlePostColumnText(String postColumnText, CreateTableColumn column, CreateTable table) { postColumnText = postColumnText.replaceAll("(?i)\\bidentity\\s*(\\(.*\\))?", "GENERATED BY DEFAULT AS IDENTITY "); return postColumnText; } @Override String handleAnySqlPostTranslation(String string, ChangeInput change); @Override String handlePostColumnText(String postColumnText, CreateTableColumn column, CreateTable table); @Override CreateTableColumn handleColumn(CreateTableColumn column, CreateTable table); }### Answer:
@Test public void testPostColumnIdentity() throws Exception { assertEquals("GENERATED BY DEFAULT AS IDENTITY NOT NULL", this.translator.handlePostColumnText("IDENTITY NOT NULL", null, null)); assertEquals(" GENERATED BY DEFAULT AS IDENTITY NOT NULL", this.translator.handlePostColumnText(" IDENTITY NOT NULL", null, null)); assertEquals("sometext GENERATED BY DEFAULT AS IDENTITY NOT NULL", this.translator.handlePostColumnText("sometext IDENTITY NOT NULL", null, null)); } |
### Question:
Db2ToH2SqlTranslator implements PostColumnSqlTranslator { @Override public String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table) { Matcher identityMatcher = Db2ToInMemorySqlTranslator.identityPattern.matcher(sql); if (identityMatcher.find()) { return identityMatcher.replaceFirst("auto_increment "); } else { return sql; } } @Override String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table); }### Answer:
@Test public void testPostColumnIdentity() throws Exception { assertEquals("auto_increment NOT NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20) NOT NULL", null, null)); assertEquals("auto_increment NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20) NULL", null, null)); assertEquals("auto_increment NOT NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY NOT NULL", null, null)); assertEquals("auto_increment NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY NULL", null, null)); assertEquals("auto_increment ", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20)", null, null)); assertEquals("auto_increment ", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY", null, null)); } |
### Question:
Db2ToHsqlSqlTranslator implements PostColumnSqlTranslator { @Override public String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table) { Matcher identityMatcher = Db2ToInMemorySqlTranslator.identityPattern.matcher(sql); if (identityMatcher.find()) { return identityMatcher.replaceFirst("generated " + identityMatcher.group(1) + " as identity "); } else { return sql; } } @Override String handlePostColumnText(String sql, CreateTableColumn column, CreateTable table); }### Answer:
@Test public void testPostColumnIdentity() throws Exception { assertEquals("generated BY DEFAULT as identity NOT NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20) NOT NULL", null, null)); assertEquals("generated BY DEFAULT as identity NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20) NULL", null, null)); assertEquals("generated BY DEFAULT as identity NOT NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY NOT NULL", null, null)); assertEquals("generated BY DEFAULT as identity NULL", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY NULL", null, null)); assertEquals("generated BY DEFAULT as identity ", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY (START WITH 1, INCREMENT BY 1, CACHE 20)", null, null)); assertEquals("generated BY DEFAULT as identity ", this.translator.handlePostColumnText("GENERATED BY DEFAULT AS IDENTITY", null, null)); } |
### Question:
Db2SqlExecutor extends AbstractSqlExecutor { private String getCurrentPathSql(Connection conn) { synchronized (currentPathSqlLock) { if (this.currentPathSql == null) { this.currentPathSql = getCurrentPathSql(conn, this.getJdbcTemplate(), this.env.getPhysicalSchemas()); } } return this.currentPathSql; } Db2SqlExecutor(DataSource ds, DbEnvironment env); @Override void setDataSourceSchema(Connection conn, PhysicalSchema schema); static void executeReorg(JdbcHelper jdbc, Connection conn, PhysicalSchema schema, String table); }### Answer:
@Test public void testSetPathSqlCreation() { JdbcHelper jdbc = mock(JdbcHelper.class); Connection conn = mock(Connection.class); when(jdbc.query(Matchers.any(Connection.class), Matchers.anyString(), Matchers.<ResultSetHandler<Object>>any())).thenReturn("s3,\"s1\",\"sB\",s2"); LinkedHashSet<PhysicalSchema> schemas = new LinkedHashSet<PhysicalSchema>(Arrays.asList(new PhysicalSchema("sA"), new PhysicalSchema("sB"), new PhysicalSchema("sC"))); assertEquals("set path s3,s1,sB,s2,sA,sC", Db2SqlExecutor.getCurrentPathSql(conn, jdbc, SetAdapter.adapt(schemas).toImmutable())); } |
### Question:
Db2ToInMemorySqlTranslator implements PostColumnSqlTranslator, PostParsedSqlTranslator, UnparsedSqlTranslator { @Override public String handleRawFullSql(String string, ChangeInput change) { return string.replaceAll("(?i)CALL\\s+SYSPROC.*", ""); } @Override String handlePostColumnText(String postColumnText, CreateTableColumn column, CreateTable table); @Override String handleAnySqlPostTranslation(String string, ChangeInput change); @Override String handleRawFullSql(String string, ChangeInput change); static final ImmutableList<String> ACCEPTED_DATE_FORMATS; }### Answer:
@Test public void testremoveProcCalls() { assertThat(this.translator.handleRawFullSql( " call sysproc.admin_cmd ( 'reorg table calc_result_future_merlin_detail' )", null), equalToIgnoringWhiteSpace("")); } |
### Question:
AbstractBreak implements Break { public void setExcluded(boolean excluded) { this.excluded = excluded; } AbstractBreak(CatoDataObject dataObject, CatoDataSide dataSide); CatoDataObject getDataObject(); CatoDataSide getDataSide(); boolean isExcluded(); void setExcluded(boolean excluded); }### Answer:
@Test public void setExcludedTest() { this.br = new AbstractBreak(AbstractBreakTest.this.obj, CatoDataSide.LEFT) {}; Assert.assertFalse(this.br.isExcluded()); this.br.setExcluded(true); Assert.assertTrue(this.br.isExcluded()); } |
### Question:
FieldBreak extends AbstractBreak { public Map<String, Object> getFieldBreaks() { return this.fieldBreaks; } FieldBreak(CatoDataObject dataObject, Map<String, Object> fieldBreaks); Map<String, Object> getFieldBreaks(); Set<String> getFields(); void setExcluded(String field, boolean excluded); boolean isExcluded(String field); Object getExpectedValue(String field); Object getActualValue(String field); }### Answer:
@Test public void testGetFieldBreaks() { Assert.assertEquals(fieldBreaks, br.getFieldBreaks()); } |
### Question:
FieldBreak extends AbstractBreak { public Set<String> getFields() { return this.fieldBreaks.keySet(); } FieldBreak(CatoDataObject dataObject, Map<String, Object> fieldBreaks); Map<String, Object> getFieldBreaks(); Set<String> getFields(); void setExcluded(String field, boolean excluded); boolean isExcluded(String field); Object getExpectedValue(String field); Object getActualValue(String field); }### Answer:
@Test public void testGetFields() { TestUtil.assertEquals(TestUtil.ATTR_FIELDS.subList(0, 2), br.getFields()); } |
### Question:
FieldBreak extends AbstractBreak { public Object getExpectedValue(String field) { return this.fieldBreaks.get(field); } FieldBreak(CatoDataObject dataObject, Map<String, Object> fieldBreaks); Map<String, Object> getFieldBreaks(); Set<String> getFields(); void setExcluded(String field, boolean excluded); boolean isExcluded(String field); Object getExpectedValue(String field); Object getActualValue(String field); }### Answer:
@Test public void testGetExpectedValue() { Assert.assertEquals(0, br.getExpectedValue(TestUtil.ATTR_FIELDS.get(0))); Assert.assertEquals(1, br.getExpectedValue(TestUtil.ATTR_FIELDS.get(1))); Assert.assertNull(br.getExpectedValue(TestUtil.ATTR_FIELDS.get(2))); Assert.assertNull(br.getExpectedValue(TestUtil.KEY_FIELDS.get(0))); Assert.assertNull(br.getExpectedValue(TestUtil.KEY_FIELDS.get(1))); } |
### Question:
FieldBreak extends AbstractBreak { public Object getActualValue(String field) { return this.dataObject.getValue(field); } FieldBreak(CatoDataObject dataObject, Map<String, Object> fieldBreaks); Map<String, Object> getFieldBreaks(); Set<String> getFields(); void setExcluded(String field, boolean excluded); boolean isExcluded(String field); Object getExpectedValue(String field); Object getActualValue(String field); }### Answer:
@Test public void testGetActualValue() { for (String field : TestUtil.ALL_FIELDS) { Assert.assertEquals(obj.getValue(field), br.getActualValue(field)); } } |
### Question:
FieldBreak extends AbstractBreak { public void setExcluded(String field, boolean excluded) { this.fieldExcludes.put(field, excluded); } FieldBreak(CatoDataObject dataObject, Map<String, Object> fieldBreaks); Map<String, Object> getFieldBreaks(); Set<String> getFields(); void setExcluded(String field, boolean excluded); boolean isExcluded(String field); Object getExpectedValue(String field); Object getActualValue(String field); }### Answer:
@Test public void setExcludedTest() { Assert.assertFalse(br.isExcluded(TestUtil.ATTR_FIELDS.get(0))); Assert.assertFalse(br.isExcluded(TestUtil.ATTR_FIELDS.get(1))); br.setExcluded(TestUtil.ATTR_FIELDS.get(0), true); Assert.assertTrue(br.isExcluded(TestUtil.ATTR_FIELDS.get(0))); } |
### Question:
GroupBreak extends AbstractBreak { public Collection<String> getFields() { return this.fields; } GroupBreak(CatoDataObject dataObject, CatoDataSide dataSide, Collection<String> fields, int groupId); Collection<String> getFields(); int getGroupId(); @Override String toString(); }### Answer:
@Test public void testGetFields() { TestUtil.assertEquals(TestUtil.ATTR_FIELDS.subList(0, 2), br.getFields()); } |
### Question:
GroupBreak extends AbstractBreak { public int getGroupId() { return this.groupId; } GroupBreak(CatoDataObject dataObject, CatoDataSide dataSide, Collection<String> fields, int groupId); Collection<String> getFields(); int getGroupId(); @Override String toString(); }### Answer:
@Test public void testGetGroupId() { Assert.assertEquals(1, br.getGroupId()); } |
### Question:
LambdaStreamObserver implements StreamObserver<T> { @Override public void onNext(T value) { onNext.accept(value); } LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError, Runnable onCompleted); LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError); LambdaStreamObserver(Consumer<T> onNext); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer:
@Test public void OnNextDelegatesCorrectly() { AtomicReference<Object> called = new AtomicReference<>(); Object val = new Object(); LambdaStreamObserver<Object> obs = new LambdaStreamObserver<>(called::set, null, null); obs.onNext(val); assertThat(called.get()).isEqualTo(val); } |
### Question:
LambdaStreamObserver implements StreamObserver<T> { @Override public void onError(Throwable t) { onError.accept(t); } LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError, Runnable onCompleted); LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError); LambdaStreamObserver(Consumer<T> onNext); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer:
@Test public void OnErrorDelegatesCorrectly() { AtomicReference<Throwable> called = new AtomicReference<>(); Throwable val = new Exception(); LambdaStreamObserver<Object> obs = new LambdaStreamObserver<>(null, called::set, null); obs.onError(val); assertThat(called.get()).isEqualTo(val); } |
### Question:
LambdaStreamObserver implements StreamObserver<T> { @Override public void onCompleted() { onCompleted.run(); } LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError, Runnable onCompleted); LambdaStreamObserver(Consumer<T> onNext, Consumer<Throwable> onError); LambdaStreamObserver(Consumer<T> onNext); @Override void onNext(T value); @Override void onError(Throwable t); @Override void onCompleted(); }### Answer:
@Test public void OnCompletedDelegatesCorrectly() { AtomicBoolean called = new AtomicBoolean(false); LambdaStreamObserver<Object> obs = new LambdaStreamObserver<>(null, null, () -> called.set(true)); obs.onCompleted(); assertThat(called.get()).isTrue(); } |
### Question:
TransmitUnexpectedExceptionInterceptor implements ServerInterceptor { public TransmitUnexpectedExceptionInterceptor forAllExceptions() { return forParentType(Throwable.class); } TransmitUnexpectedExceptionInterceptor forExactType(Class<? extends Throwable> exactType); TransmitUnexpectedExceptionInterceptor forExactTypes(Collection<Class<? extends Throwable>> exactTypes); TransmitUnexpectedExceptionInterceptor forParentType(Class<? extends Throwable> parentType); TransmitUnexpectedExceptionInterceptor forParentTypes(Collection<Class<? extends Throwable>> parentTypes); TransmitUnexpectedExceptionInterceptor forAllExceptions(); @Override ServerCall.Listener<ReqT> interceptCall(ServerCall<ReqT, RespT> call, Metadata headers, ServerCallHandler<ReqT, RespT> next); }### Answer:
@Test public void alleMatches() { GreeterGrpc.GreeterImplBase svc = new GreeterGrpc.GreeterImplBase() { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { responseObserver.onError(new ArithmeticException("Divide by zero")); } }; ServerInterceptor interceptor = new TransmitUnexpectedExceptionInterceptor().forAllExceptions(); serverRule.getServiceRegistry().addService(ServerInterceptors.intercept(svc, interceptor)); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(serverRule.getChannel()); assertThatThrownBy(() -> stub.sayHello(HelloRequest.newBuilder().setName("World").build())) .isInstanceOf(StatusRuntimeException.class) .matches(sre -> ((StatusRuntimeException) sre).getStatus().getCode().equals(Status.INTERNAL.getCode()), "is Status.INTERNAL") .hasMessageContaining("Divide by zero"); } |
### Question:
GuavaLFReturnValueHandler implements HandlerMethodReturnValueHandler { private int indexOfType(final List<HandlerMethodReturnValueHandler> originalHandlers, Class<?> handlerClass) { for (int i = 0; i < originalHandlers.size(); i++) { final HandlerMethodReturnValueHandler valueHandler = originalHandlers.get(i); if (handlerClass.isAssignableFrom(valueHandler.getClass())) { return i; } } return -1; } @Override boolean supportsReturnType(MethodParameter returnType); @Override void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest); GuavaLFReturnValueHandler install(RequestMappingHandlerAdapter requestMappingHandlerAdapter); }### Answer:
@Test public void handlerIsRegistered() { List<HandlerMethodReturnValueHandler> handlers = requestMappingHandlerAdapter.getReturnValueHandlers(); assertThat(indexOfType(handlers, GuavaLFReturnValueHandler.class)).isGreaterThanOrEqualTo(0); }
@Test public void handlerIsAfterDeferredResultMethodReturnValueHandler() { List<HandlerMethodReturnValueHandler> handlers = requestMappingHandlerAdapter.getReturnValueHandlers(); int lfHandlerIndex = indexOfType(handlers, GuavaLFReturnValueHandler.class); int drHandlerIndex = indexOfType(handlers, DeferredResultMethodReturnValueHandler.class); assertThat(lfHandlerIndex).isGreaterThan(drHandlerIndex); } |
### Question:
AmbientContext { public Object freeze() { checkState(!isFrozen(), "AmbientContext already frozen. Cannot freeze() twice."); freezeKey = new Object(); return freezeKey; } AmbientContext(); AmbientContext(AmbientContext other); static Context initialize(Context context); static AmbientContext current(); static boolean isPresent(); Object freeze(); void thaw(Object freezeKey); Context fork(Context context); boolean isFrozen(); boolean containsKey(Metadata.Key<?> key); void discardAll(Metadata.Key<T> key); @Nullable T get(Metadata.Key<T> key); @Nullable Iterable<T> getAll(final Metadata.Key<T> key); Set<String> keys(); void put(Metadata.Key<T> key, T value); boolean remove(Metadata.Key<T> key, T value); Iterable<T> removeAll(Metadata.Key<T> key); @Override String toString(); }### Answer:
@Test public void contextDoubleFreezingThrows() { AmbientContext context = new AmbientContext(); context.freeze(); assertThatThrownBy(context::freeze).isInstanceOf(IllegalStateException.class); } |
### Question:
AmbientContext { public void thaw(Object freezeKey) { checkState(isFrozen(), "AmbientContext is not frozen. Cannot thaw()."); checkArgument(this.freezeKey == freezeKey, "The provided freezeKey is not the same object returned by freeze()"); this.freezeKey = null; } AmbientContext(); AmbientContext(AmbientContext other); static Context initialize(Context context); static AmbientContext current(); static boolean isPresent(); Object freeze(); void thaw(Object freezeKey); Context fork(Context context); boolean isFrozen(); boolean containsKey(Metadata.Key<?> key); void discardAll(Metadata.Key<T> key); @Nullable T get(Metadata.Key<T> key); @Nullable Iterable<T> getAll(final Metadata.Key<T> key); Set<String> keys(); void put(Metadata.Key<T> key, T value); boolean remove(Metadata.Key<T> key, T value); Iterable<T> removeAll(Metadata.Key<T> key); @Override String toString(); }### Answer:
@Test public void contextThawingNotFrozenThrows() { AmbientContext context = new AmbientContext(); assertThatThrownBy(() -> context.thaw(new Object())).isInstanceOf(IllegalStateException.class); } |
### Question:
GuavaLFReturnValueHandler implements HandlerMethodReturnValueHandler { @Override public boolean supportsReturnType(MethodParameter returnType) { return ListenableFuture.class.isAssignableFrom(returnType.getParameterType()); } @Override boolean supportsReturnType(MethodParameter returnType); @Override void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest); GuavaLFReturnValueHandler install(RequestMappingHandlerAdapter requestMappingHandlerAdapter); }### Answer:
@Test public void supportsType() { MethodParameter mp = mock(MethodParameter.class); when(mp.getParameterType()).thenAnswer((Answer<Class<ListenableFuture>>) x -> ListenableFuture.class); assertThat(handler.supportsReturnType(mp)).isTrue(); } |
### Question:
MoreFutures { public static <V> void onSuccess(@Nonnull final ListenableFuture<V> future, @Nonnull final Consumer<V> success, @Nonnull final Executor executor) { checkNotNull(future, "future"); checkNotNull(success, "success"); checkNotNull(executor, "executor"); addCallback(future, success, throwable -> { }, executor); } private MoreFutures(); static void addCallback(
@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<V> success,
@Nonnull final Consumer<Throwable> failure,
@Nonnull final Executor executor); static void onSuccess(@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<V> success,
@Nonnull final Executor executor); static void onFailure(@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<Throwable> failure,
@Nonnull final Executor executor); @Deprecated static V getDone(Future<V> future); @Deprecated static V getDoneUnchecked(Future<V> future); static CompletableFuture<V> toCompletableFuture(@Nonnull final ListenableFuture<V> listenableFuture); static ListenableFuture<V> fromCompletableFuture(@Nonnull final CompletableFuture<V> completableFuture); }### Answer:
@Test public void addCallbackSuccess() { AtomicBoolean called = new AtomicBoolean(false); final Object value = new Object(); SettableFuture<Object> future = SettableFuture.create(); MoreFutures.onSuccess( future, o -> { assertEquals(value, o); called.set(true); }, MoreExecutors.directExecutor()); assertFalse(called.get()); future.set(value); assertTrue(called.get()); } |
### Question:
MoreFutures { public static <V> void onFailure(@Nonnull final ListenableFuture<V> future, @Nonnull final Consumer<Throwable> failure, @Nonnull final Executor executor) { checkNotNull(future, "future"); checkNotNull(failure, "failure"); checkNotNull(executor, "executor"); addCallback(future, v -> { }, failure, executor); } private MoreFutures(); static void addCallback(
@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<V> success,
@Nonnull final Consumer<Throwable> failure,
@Nonnull final Executor executor); static void onSuccess(@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<V> success,
@Nonnull final Executor executor); static void onFailure(@Nonnull final ListenableFuture<V> future,
@Nonnull final Consumer<Throwable> failure,
@Nonnull final Executor executor); @Deprecated static V getDone(Future<V> future); @Deprecated static V getDoneUnchecked(Future<V> future); static CompletableFuture<V> toCompletableFuture(@Nonnull final ListenableFuture<V> listenableFuture); static ListenableFuture<V> fromCompletableFuture(@Nonnull final CompletableFuture<V> completableFuture); }### Answer:
@Test public void addCallbackFailure() { AtomicBoolean called = new AtomicBoolean(false); final Exception ex = new Exception(); SettableFuture<Object> future = SettableFuture.create(); MoreFutures.onFailure( future, e -> { assertEquals(ex, e); called.set(true); }, MoreExecutors.directExecutor()); assertFalse(called.get()); future.setException(ex); assertTrue(called.get()); } |
### Question:
Statuses { public static boolean hasStatus(Throwable t) { return t instanceof StatusException || t instanceof StatusRuntimeException; } private Statuses(); static boolean hasStatus(Throwable t); static boolean hasStatusCode(Throwable t, Status.Code code); static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action); static T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function); }### Answer:
@Test public void hasStatusReturnsTrueStatusException() { Throwable t = Status.INTERNAL.asException(); assertThat(Statuses.hasStatus(t)).isTrue(); }
@Test public void hasStatusReturnsTrueStatusRuntimeException() { Throwable t = Status.INTERNAL.asRuntimeException(); assertThat(Statuses.hasStatus(t)).isTrue(); }
@Test public void hasStatusReturnsFalse() { Throwable t = new IllegalStateException(); assertThat(Statuses.hasStatus(t)).isFalse(); } |
### Question:
Statuses { public static boolean hasStatusCode(Throwable t, Status.Code code) { if (!hasStatus(t)) { return false; } else { return doWithStatus(t, (status, metadata) -> status.getCode() == code); } } private Statuses(); static boolean hasStatus(Throwable t); static boolean hasStatusCode(Throwable t, Status.Code code); static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action); static T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function); }### Answer:
@Test public void hasStatusCodeReturnsTrue() { Throwable t = Status.NOT_FOUND.asException(); assertThat(Statuses.hasStatusCode(t, Status.Code.NOT_FOUND)).isTrue(); }
@Test public void hasStatusCodeReturnsFalseWrongCode() { Throwable t = Status.NOT_FOUND.asException(); assertThat(Statuses.hasStatusCode(t, Status.Code.UNAUTHENTICATED)).isFalse(); }
@Test public void hasStatusCodeReturnsFalseWrongType() { Throwable t = new IllegalStateException(); assertThat(Statuses.hasStatusCode(t, Status.Code.UNAUTHENTICATED)).isFalse(); } |
### Question:
Statuses { public static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action) { doWithStatus(t, (status, metadata) -> { action.accept(status, metadata); return true; }); } private Statuses(); static boolean hasStatus(Throwable t); static boolean hasStatusCode(Throwable t, Status.Code code); static void doWithStatus(Throwable t, BiConsumer<Status, Metadata> action); static T doWithStatus(Throwable t, BiFunction<Status, Metadata, T> function); }### Answer:
@Test public void doWithStatusCallsAction() { Metadata trailers = new Metadata(); Throwable t = Status.NOT_FOUND.asRuntimeException(trailers); AtomicBoolean called = new AtomicBoolean(false); Statuses.doWithStatus(t, (status, metadata) -> { assertThat(status.getCode()).isEqualTo(Status.Code.NOT_FOUND); assertThat(metadata).isEqualTo(trailers); called.set(true); }); assertThat(called.get()).isTrue(); }
@Test public void doWithStatusThrowsWrongTypeAction() { Throwable t = new IllegalStateException(); assertThatThrownBy(() -> Statuses.doWithStatus(t, (status, metadata) -> { })) .isInstanceOf(IllegalArgumentException.class); }
@Test public void doWithStatusCallsFunction() { Metadata trailers = new Metadata(); Throwable t = Status.NOT_FOUND.asRuntimeException(trailers); boolean called = Statuses.doWithStatus(t, (status, metadata) -> { assertThat(status.getCode()).isEqualTo(Status.Code.NOT_FOUND); assertThat(metadata).isEqualTo(trailers); return true; }); assertThat(called).isTrue(); }
@Test public void doWithStatusThrowsWrongTypeFunction() { Throwable t = new IllegalStateException(); assertThatThrownBy(() -> Statuses.doWithStatus(t, (status, metadata) -> true)) .isInstanceOf(IllegalArgumentException.class); } |
### Question:
VipUtils { public static String getVIPPrefix(String vipAddress) { for (int i = 0; i < vipAddress.length(); i++) { char c = vipAddress.charAt(i); if (c == '.' || c == ':') { return vipAddress.substring(0, i); } } return vipAddress; } private VipUtils(); static String getVIPPrefix(String vipAddress); @Deprecated static String extractAppNameFromVIP(String vipAddress); static String extractUntrustedAppNameFromVIP(String vipAddress); }### Answer:
@Test(expected = NullPointerException.class) public void testGetVIPPrefix() { assertEquals("api-test", VipUtils.getVIPPrefix("api-test.netflix.net:7001")); assertEquals("api-test", VipUtils.getVIPPrefix("api-test.netflix.net")); assertEquals("api-test", VipUtils.getVIPPrefix("api-test:7001")); assertEquals("api-test", VipUtils.getVIPPrefix("api-test")); assertEquals("", VipUtils.getVIPPrefix("")); VipUtils.getVIPPrefix(null); } |
### Question:
VipUtils { @Deprecated public static String extractAppNameFromVIP(String vipAddress) { String vipPrefix = getVIPPrefix(vipAddress); return vipPrefix.split("-")[0]; } private VipUtils(); static String getVIPPrefix(String vipAddress); @Deprecated static String extractAppNameFromVIP(String vipAddress); static String extractUntrustedAppNameFromVIP(String vipAddress); }### Answer:
@Test(expected = NullPointerException.class) public void testExtractAppNameFromVIP() { assertEquals("api", VipUtils.extractUntrustedAppNameFromVIP("api-test.netflix.net:7001")); assertEquals("api", VipUtils.extractUntrustedAppNameFromVIP("api-test-blah.netflix.net:7001")); assertEquals("api", VipUtils.extractUntrustedAppNameFromVIP("api")); assertEquals("", VipUtils.extractUntrustedAppNameFromVIP("")); VipUtils.extractUntrustedAppNameFromVIP(null); } |
### Question:
ProxyUtils { public static boolean isValidResponseHeader(HeaderName headerName) { return ! RESP_HEADERS_TO_STRIP.contains(headerName); } static boolean isValidRequestHeader(HeaderName headerName); static boolean isValidResponseHeader(HeaderName headerName); static void addXForwardedHeaders(HttpRequestMessage request); static void addXForwardedHeader(Headers headers, HeaderName name, String latestValue); }### Answer:
@Test public void testIsValidResponseHeader() { Assert.assertTrue(ProxyUtils.isValidResponseHeader(HttpHeaderNames.get("test"))); Assert.assertFalse(ProxyUtils.isValidResponseHeader(HttpHeaderNames.get("Keep-Alive"))); Assert.assertFalse(ProxyUtils.isValidResponseHeader(HttpHeaderNames.get("keep-alive"))); } |
### Question:
HttpUtils { public static boolean isGzipped(String contentEncoding) { return contentEncoding.contains("gzip"); } static String getClientIP(HttpRequestInfo request); static String extractClientIpFromXForwardedFor(String xForwardedFor); static boolean isGzipped(String contentEncoding); static boolean isGzipped(Headers headers); static boolean acceptsGzip(Headers headers); static String stripMaliciousHeaderChars(@Nullable String input); static boolean hasNonZeroContentLengthHeader(ZuulMessage msg); static Integer getContentLengthIfPresent(ZuulMessage msg); static Integer getBodySizeIfKnown(ZuulMessage msg); static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg); static Channel getMainChannel(ChannelHandlerContext ctx); static Channel getMainChannel(Channel channel); }### Answer:
@Test public void detectsGzip() { assertTrue(HttpUtils.isGzipped("gzip")); }
@Test public void detectsNonGzip() { assertFalse(HttpUtils.isGzipped("identity")); }
@Test public void detectsGzipAmongOtherEncodings() { assertTrue(HttpUtils.isGzipped("gzip, deflate")); } |
### Question:
HttpUtils { public static String stripMaliciousHeaderChars(@Nullable String input) { if (input == null) { return null; } for (char c : MALICIOUS_HEADER_CHARS) { if (input.indexOf(c) != -1) { input = input.replace(Character.toString(c), ""); } } return input; } static String getClientIP(HttpRequestInfo request); static String extractClientIpFromXForwardedFor(String xForwardedFor); static boolean isGzipped(String contentEncoding); static boolean isGzipped(Headers headers); static boolean acceptsGzip(Headers headers); static String stripMaliciousHeaderChars(@Nullable String input); static boolean hasNonZeroContentLengthHeader(ZuulMessage msg); static Integer getContentLengthIfPresent(ZuulMessage msg); static Integer getBodySizeIfKnown(ZuulMessage msg); static boolean hasChunkedTransferEncodingHeader(ZuulMessage msg); static Channel getMainChannel(ChannelHandlerContext ctx); static Channel getMainChannel(Channel channel); }### Answer:
@Test public void stripMaliciousHeaderChars() { assertEquals("something", HttpUtils.stripMaliciousHeaderChars("some\r\nthing")); assertEquals("some thing", HttpUtils.stripMaliciousHeaderChars("some thing")); assertEquals("something", HttpUtils.stripMaliciousHeaderChars("\nsome\r\nthing\r")); assertEquals("", HttpUtils.stripMaliciousHeaderChars("\r")); assertEquals("", HttpUtils.stripMaliciousHeaderChars("")); assertNull(HttpUtils.stripMaliciousHeaderChars(null)); } |
### Question:
HttpQueryParams implements Cloneable { public String toEncodedString() { StringBuilder sb = new StringBuilder(); try { for (Map.Entry<String, String> entry : entries()) { sb.append(URLEncoder.encode(entry.getKey(), "UTF-8")); if (!Strings.isNullOrEmpty(entry.getValue())) { sb.append('='); sb.append(URLEncoder.encode(entry.getValue(), "UTF-8")); } else if (isTrailingEquals(entry.getKey())) { sb.append('='); } sb.append('&'); } if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return sb.toString(); } HttpQueryParams(); private HttpQueryParams(ListMultimap<String, String> delegate); static HttpQueryParams parse(String queryString); String getFirst(String name); List<String> get(String name); boolean contains(String name); boolean containsIgnoreCase(String name); boolean contains(String name, String value); void set(String name, String value); void add(String name, String value); void removeAll(String name); void clear(); Collection<Map.Entry<String, String>> entries(); Set<String> keySet(); String toEncodedString(); @Override String toString(); HttpQueryParams immutableCopy(); boolean isImmutable(); boolean isTrailingEquals(String key); void setTrailingEquals(String key, boolean trailingEquals); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testToEncodedString() { HttpQueryParams qp = new HttpQueryParams(); qp.add("k'1", "v1&"); assertEquals("k%271=v1%26", qp.toEncodedString()); qp = new HttpQueryParams(); qp.add("k+", "\n"); assertEquals("k%2B=%0A", qp.toEncodedString()); } |
### Question:
HttpQueryParams implements Cloneable { @Override public String toString() { StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : entries()) { sb.append(entry.getKey()); if (!Strings.isNullOrEmpty(entry.getValue())) { sb.append('='); sb.append(entry.getValue()); } sb.append('&'); } if (sb.length() > 0 && '&' == sb.charAt(sb.length() - 1)) { sb.deleteCharAt(sb.length() - 1); } return sb.toString(); } HttpQueryParams(); private HttpQueryParams(ListMultimap<String, String> delegate); static HttpQueryParams parse(String queryString); String getFirst(String name); List<String> get(String name); boolean contains(String name); boolean containsIgnoreCase(String name); boolean contains(String name, String value); void set(String name, String value); void add(String name, String value); void removeAll(String name); void clear(); Collection<Map.Entry<String, String>> entries(); Set<String> keySet(); String toEncodedString(); @Override String toString(); HttpQueryParams immutableCopy(); boolean isImmutable(); boolean isTrailingEquals(String key); void setTrailingEquals(String key, boolean trailingEquals); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testToString() { HttpQueryParams qp = new HttpQueryParams(); qp.add("k'1", "v1&"); assertEquals("k'1=v1&", qp.toString()); qp = new HttpQueryParams(); qp.add("k+", "\n"); assertEquals("k+=\n", qp.toString()); } |
### Question:
HttpQueryParams implements Cloneable { @Override public boolean equals(Object obj) { if (obj == null) return false; if (! (obj instanceof HttpQueryParams)) return false; HttpQueryParams hqp2 = (HttpQueryParams) obj; return Iterables.elementsEqual(delegate.entries(), hqp2.delegate.entries()); } HttpQueryParams(); private HttpQueryParams(ListMultimap<String, String> delegate); static HttpQueryParams parse(String queryString); String getFirst(String name); List<String> get(String name); boolean contains(String name); boolean containsIgnoreCase(String name); boolean contains(String name, String value); void set(String name, String value); void add(String name, String value); void removeAll(String name); void clear(); Collection<Map.Entry<String, String>> entries(); Set<String> keySet(); String toEncodedString(); @Override String toString(); HttpQueryParams immutableCopy(); boolean isImmutable(); boolean isTrailingEquals(String key); void setTrailingEquals(String key, boolean trailingEquals); @Override int hashCode(); @Override boolean equals(Object obj); }### Answer:
@Test public void testEquals() { HttpQueryParams qp1 = new HttpQueryParams(); qp1.add("k1", "v1"); qp1.add("k2", "v2"); HttpQueryParams qp2 = new HttpQueryParams(); qp2.add("k1", "v1"); qp2.add("k2", "v2"); assertEquals(qp1, qp2); } |
### Question:
ZuulMessageImpl implements ZuulMessage { @Override public ZuulMessage clone() { final ZuulMessageImpl copy = new ZuulMessageImpl(context.clone(), Headers.copyOf(headers)); this.bodyChunks.forEach(chunk -> { chunk.retain(); copy.bufferBodyContents(chunk); }); return copy; } ZuulMessageImpl(SessionContext context); ZuulMessageImpl(SessionContext context, Headers headers); @Override SessionContext getContext(); @Override Headers getHeaders(); @Override void setHeaders(Headers newHeaders); @Override int getMaxBodySize(); @Override void setHasBody(boolean hasBody); @Override boolean hasBody(); @Override boolean hasCompleteBody(); @Override void bufferBodyContents(final HttpContent chunk); @Override void setBodyAsText(String bodyText); @Override void setBody(byte[] body); @Override String getBodyAsText(); @Override byte[] getBody(); @Override int getBodyLength(); @Override Iterable<HttpContent> getBodyContents(); @Override boolean finishBufferedBodyIfIncomplete(); @Override void disposeBufferedBody(); @Override void runBufferedBodyContentThroughFilter(ZuulFilter<?, ?> filter); @Override ZuulMessage clone(); @Override String getInfoForLogging(); }### Answer:
@Test public void testClone() { SessionContext ctx1 = new SessionContext(); ctx1.set("k1", "v1"); Headers headers1 = new Headers(); headers1.set("k1", "v1"); ZuulMessage msg1 = new ZuulMessageImpl(ctx1, headers1); ZuulMessage msg2 = msg1.clone(); assertEquals(msg1.getBodyAsText(), msg2.getBodyAsText()); assertEquals(msg1.getHeaders(), msg2.getHeaders()); assertEquals(msg1.getContext(), msg2.getContext()); msg1.getHeaders().set("k1", "v_new"); msg1.getContext().set("k1", "v_new"); assertEquals("v1", msg2.getHeaders().getFirst("k1")); assertEquals("v1", msg2.getContext().get("k1")); } |
### Question:
ClientSslContextFactory extends BaseSslContextFactory { static String[] maybeAddTls13(boolean enableTls13, String ... defaultProtocols) { if (enableTls13) { String[] protocols = new String[defaultProtocols.length + 1]; System.arraycopy(defaultProtocols, 0, protocols, 1, defaultProtocols.length); protocols[0] = "TLSv1.3"; return protocols; } else { return defaultProtocols; } } ClientSslContextFactory(Registry spectatorRegistry); ClientSslContextFactory(Registry spectatorRegistry, ServerSslConfig serverSslConfig); SslContext getClientSslContext(); }### Answer:
@Test public void enableTls13() { String[] protos = ClientSslContextFactory.maybeAddTls13(true, "TLSv1.2"); assertEquals(Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList(protos)); }
@Test public void disableTls13() { String[] protos = ClientSslContextFactory.maybeAddTls13(false, "TLSv1.2"); assertEquals(Arrays.asList("TLSv1.2"), Arrays.asList(protos)); } |
### Question:
Attrs { public static <T> Key<T> newKey(String keyName) { return new Key<>(keyName); } private Attrs(); static Key<T> newKey(String keyName); static Attrs newInstance(); Set<Key<?>> keySet(); @Override String toString(); @Override @VisibleForTesting boolean equals(Object other); @Override @VisibleForTesting int hashCode(); }### Answer:
@Test public void newKeyFailsOnNull() { assertThrows(NullPointerException.class, () -> Attrs.newKey(null)); } |
### Question:
StaticFilterLoader implements FilterLoader { @Override public SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType) { return filtersByType.get(filterType); } @Inject StaticFilterLoader(
FilterFactory filterFactory, Set<? extends Class<? extends ZuulFilter<?, ?>>> filterTypes); static Set<Class<ZuulFilter<?, ?>>> loadFilterTypesFromResources(ClassLoader loader); @Override @DoNotCall boolean putFilter(File file); @Override @DoNotCall List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override @DoNotCall ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override @Nullable ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); static final String RESOURCE_NAME; }### Answer:
@Test public void getFiltersByType() { StaticFilterLoader filterLoader = new StaticFilterLoader(factory, ImmutableSet.of(DummyFilter2.class, DummyFilter1.class, DummyFilter22.class)); SortedSet<ZuulFilter<?, ?>> filters = filterLoader.getFiltersByType(FilterType.INBOUND); Truth.assertThat(filters).hasSize(3); List<ZuulFilter<?, ?>> filterList = new ArrayList<>(filters); Truth.assertThat(filterList.get(0)).isInstanceOf(DummyFilter1.class); Truth.assertThat(filterList.get(1)).isInstanceOf(DummyFilter2.class); Truth.assertThat(filterList.get(2)).isInstanceOf(DummyFilter22.class); } |
### Question:
StaticFilterLoader implements FilterLoader { @Override @Nullable public ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type) { Map<String, ZuulFilter<?, ?>> filtersByName = filtersByTypeAndName.get(type); if (filtersByName == null) { return null; } return filtersByName.get(name); } @Inject StaticFilterLoader(
FilterFactory filterFactory, Set<? extends Class<? extends ZuulFilter<?, ?>>> filterTypes); static Set<Class<ZuulFilter<?, ?>>> loadFilterTypesFromResources(ClassLoader loader); @Override @DoNotCall boolean putFilter(File file); @Override @DoNotCall List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override @DoNotCall ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override @Nullable ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); static final String RESOURCE_NAME; }### Answer:
@Test public void getFilterByNameAndType() { StaticFilterLoader filterLoader = new StaticFilterLoader(factory, ImmutableSet.of(DummyFilter2.class, DummyFilter1.class)); ZuulFilter<?, ?> filter = filterLoader.getFilterByNameAndType("Robin", FilterType.INBOUND); Truth.assertThat(filter).isInstanceOf(DummyFilter2.class); } |
### Question:
SessionContext extends HashMap<String, Object> implements Cloneable { public boolean getBoolean(String key) { return getBoolean(key, false); } SessionContext(); @Override SessionContext clone(); String getString(String key); boolean getBoolean(String key); boolean getBoolean(String key, boolean defaultResponse); void set(String key); void set(String key, Object value); SessionContext copy(); String getUUID(); void setUUID(String uuid); void setStaticResponse(HttpResponseMessage response); HttpResponseMessage getStaticResponse(); Throwable getError(); void setError(Throwable th); String getErrorEndpoint(); void setErrorEndpoint(String name); void setDebugRouting(boolean bDebug); boolean debugRouting(); void setDebugRequestHeadersOnly(boolean bHeadersOnly); boolean debugRequestHeadersOnly(); void setDebugRequest(boolean bDebug); boolean debugRequest(); void removeRouteHost(); void setRouteHost(URL routeHost); URL getRouteHost(); void addFilterExecutionSummary(String name, String status, long time); StringBuilder getFilterExecutionSummary(); boolean shouldSendErrorResponse(); void setShouldSendErrorResponse(boolean should); boolean errorResponseSent(); void setErrorResponseSent(boolean should); boolean isInBrownoutMode(); void setInBrownoutMode(); void stopFilterProcessing(); boolean shouldStopFilterProcessing(); String getRouteVIP(); void setRouteVIP(String sVip); void setEndpoint(String endpoint); String getEndpoint(); void setEventProperty(String key, Object value); Map<String, Object> getEventProperties(); List<FilterError> getFilterErrors(); Timings getTimings(); void setOriginReportedDuration(int duration); int getOriginReportedDuration(); boolean isCancelled(); void cancel(); }### Answer:
@Test public void testBoolean() { SessionContext context = new SessionContext(); assertEquals(context.getBoolean("boolean_test"), Boolean.FALSE); assertEquals(context.getBoolean("boolean_test", true), true); } |
### Question:
DynamicFilterLoader implements FilterLoader { @Override public boolean putFilter(File file) { if (!filterRegistry.isMutable()) { return false; } try { String sName = file.getAbsolutePath(); if (filterClassLastModified.get(sName) != null && (file.lastModified() != filterClassLastModified.get(sName))) { LOG.debug("reloading filter " + sName); filterRegistry.remove(sName); } ZuulFilter<?, ?> filter = filterRegistry.get(sName); if (filter == null) { Class<?> clazz = compiler.compile(file); if (!Modifier.isAbstract(clazz.getModifiers())) { filter = filterFactory.newInstance(clazz); putFilter(sName, filter, file.lastModified()); return true; } } } catch (Exception e) { LOG.error("Error loading filter! Continuing. file=" + file, e); return false; } return false; } @Inject DynamicFilterLoader(
FilterRegistry filterRegistry,
DynamicCodeCompiler compiler,
FilterFactory filterFactory); @Deprecated ZuulFilter<?, ?> getFilter(String sourceCode, String filterName); int filterInstanceMapSize(); @Override boolean putFilter(File file); @Override List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); }### Answer:
@Test public void testGetFilterFromFile() throws Exception { assertTrue(loader.putFilter(file)); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(1, filters.size()); } |
### Question:
DynamicFilterLoader implements FilterLoader { @Override public List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames) throws Exception { List<ZuulFilter<?, ?>> newFilters = new ArrayList<>(); for (String className : classNames) { newFilters.add(putFilterForClassName(className)); } return Collections.unmodifiableList(newFilters); } @Inject DynamicFilterLoader(
FilterRegistry filterRegistry,
DynamicCodeCompiler compiler,
FilterFactory filterFactory); @Deprecated ZuulFilter<?, ?> getFilter(String sourceCode, String filterName); int filterInstanceMapSize(); @Override boolean putFilter(File file); @Override List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); }### Answer:
@Test public void testPutFiltersForClasses() throws Exception { loader.putFiltersForClasses(new String[]{TestZuulFilter.class.getName()}); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(1, filters.size()); }
@Test public void testPutFiltersForClassesException() throws Exception { Exception caught = null; try { loader.putFiltersForClasses(new String[]{"asdf"}); } catch (ClassNotFoundException e) { caught = e; } assertTrue(caught != null); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(0, filters.size()); } |
### Question:
DynamicFilterLoader implements FilterLoader { @Override public SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType) { SortedSet<ZuulFilter<?, ?>> set = hashFiltersByType.get(filterType); if (set != null) return set; set = new TreeSet<>(FILTER_COMPARATOR); for (ZuulFilter<?, ?> filter : filterRegistry.getAllFilters()) { if (filter.filterType().equals(filterType)) { set.add(filter); } } hashFiltersByType.putIfAbsent(filterType, set); return Collections.unmodifiableSortedSet(set); } @Inject DynamicFilterLoader(
FilterRegistry filterRegistry,
DynamicCodeCompiler compiler,
FilterFactory filterFactory); @Deprecated ZuulFilter<?, ?> getFilter(String sourceCode, String filterName); int filterInstanceMapSize(); @Override boolean putFilter(File file); @Override List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); }### Answer:
@Test public void testGetFiltersByType() throws Exception { assertTrue(loader.putFilter(file)); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(1, filters.size()); Collection<ZuulFilter<?, ?>> list = loader.getFiltersByType(FilterType.INBOUND); assertTrue(list != null); assertTrue(list.size() == 1); ZuulFilter<?, ?> filter = list.iterator().next(); assertTrue(filter != null); assertTrue(filter.filterType().equals(FilterType.INBOUND)); } |
### Question:
DynamicFilterLoader implements FilterLoader { @Deprecated public ZuulFilter<?, ?> getFilter(String sourceCode, String filterName) throws Exception { if (filterCheck.get(filterName) == null) { filterCheck.putIfAbsent(filterName, filterName); if (!sourceCode.equals(filterClassCode.get(filterName))) { if (filterRegistry.isMutable()) { LOG.info("reloading code {}", filterName); filterRegistry.remove(filterName); } else { LOG.warn("Filter registry is not mutable, discarding {}", filterName); } } } ZuulFilter<?, ?> filter = filterRegistry.get(filterName); if (filter == null) { Class<?> clazz = compiler.compile(sourceCode, filterName); if (!Modifier.isAbstract(clazz.getModifiers())) { filter = filterFactory.newInstance(clazz); } } return filter; } @Inject DynamicFilterLoader(
FilterRegistry filterRegistry,
DynamicCodeCompiler compiler,
FilterFactory filterFactory); @Deprecated ZuulFilter<?, ?> getFilter(String sourceCode, String filterName); int filterInstanceMapSize(); @Override boolean putFilter(File file); @Override List<ZuulFilter<?, ?>> putFiltersForClasses(String[] classNames); @Override ZuulFilter<?, ?> putFilterForClassName(String className); @Override SortedSet<ZuulFilter<?, ?>> getFiltersByType(FilterType filterType); @Override ZuulFilter<?, ?> getFilterByNameAndType(String name, FilterType type); }### Answer:
@Test public void testGetFilterFromString() throws Exception { String string = ""; doReturn(TestZuulFilter.class).when(compiler).compile(string, string); ZuulFilter filter = loader.getFilter(string, string); assertNotNull(filter); assertTrue(filter.getClass() == TestZuulFilter.class); } |
### Question:
GZipResponseFilter extends HttpOutboundSyncFilter { @Override public boolean shouldFilter(HttpResponseMessage response) { if (!ENABLED.get() || !response.hasBody() || response.getContext().isInBrownoutMode()) { return false; } if (response.getContext().get(CommonContextKeys.GZIPPER) != null) { return true; } final HttpRequestInfo request = response.getInboundRequest(); final Boolean overrideIsGzipRequested = (Boolean) response.getContext().get(CommonContextKeys.OVERRIDE_GZIP_REQUESTED); final boolean isGzipRequested = (overrideIsGzipRequested == null) ? HttpUtils.acceptsGzip(request.getHeaders()) : overrideIsGzipRequested.booleanValue(); final Headers respHeaders = response.getHeaders(); boolean isResponseGzipped = HttpUtils.isGzipped(respHeaders); final boolean shouldGzip = isGzippableContentType(response) && isGzipRequested && !isResponseGzipped && isRightSizeForGzip(response); if (shouldGzip) { response.getContext().set(CommonContextKeys.GZIPPER, getGzipper()); } return shouldGzip; } @Override boolean shouldFilter(HttpResponseMessage response); @Override HttpResponseMessage apply(HttpResponseMessage response); @Override HttpContent processContentChunk(ZuulMessage resp, HttpContent chunk); }### Answer:
@Test public void prepareResponseBody_NeedsGZipping_butTooSmall() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); response.setHasBody(true); assertFalse(filter.shouldFilter(response)); }
@Test public void prepareChunkedEncodedResponseBody_NeedsGZipping() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip"); response.getHeaders().set("Transfer-Encoding", "chunked"); response.setHasBody(true); assertTrue(filter.shouldFilter(response)); } |
### Question:
ErrorStatsManager { public void putStats(String route, String cause) { if (route == null) route = "UNKNOWN_ROUTE"; route = route.replace("/", "_"); ConcurrentHashMap<String, ErrorStatsData> statsMap = routeMap.get(route); if (statsMap == null) { statsMap = new ConcurrentHashMap<String, ErrorStatsData>(); routeMap.putIfAbsent(route, statsMap); } ErrorStatsData sd = statsMap.get(cause); if (sd == null) { sd = new ErrorStatsData(route, cause); ErrorStatsData sd1 = statsMap.putIfAbsent(cause, sd); if (sd1 != null) { sd = sd1; } else { MonitorRegistry.getInstance().registerObject(sd); } } sd.update(); } static ErrorStatsManager getManager(); ErrorStatsData getStats(String route, String cause); void putStats(String route, String cause); }### Answer:
@Test public void testPutStats() { ErrorStatsManager sm = new ErrorStatsManager(); assertNotNull(sm); sm.putStats("test", "cause"); assertNotNull(sm.routeMap.get("test")); ConcurrentHashMap<String, ErrorStatsData> map = sm.routeMap.get("test"); ErrorStatsData sd = map.get("cause"); assertEquals(sd.getCount(), 1); sm.putStats("test", "cause"); assertEquals(sd.getCount(), 2); } |
### Question:
InstrumentedResourceLeakDetector extends ResourceLeakDetector<T> { @Override protected void reportTracedLeak(String resourceType, String records) { super.reportTracedLeak(resourceType, records); leakCounter.incrementAndGet(); resetReportedLeaks(); } InstrumentedResourceLeakDetector(Class<?> resourceType, int samplingInterval); InstrumentedResourceLeakDetector(Class<?> resourceType, int samplingInterval, long maxActive); }### Answer:
@Test public void test() { leakDetector.reportTracedLeak("test", "test"); assertEquals(leakDetector.leakCounter.get(), 1); leakDetector.reportTracedLeak("test", "test"); assertEquals(leakDetector.leakCounter.get(), 2); leakDetector.reportTracedLeak("test", "test"); assertEquals(leakDetector.leakCounter.get(), 3); } |
### Question:
ErrorStatsManager { public ErrorStatsData getStats(String route, String cause) { Map<String, ErrorStatsData> map = routeMap.get(route); if (map == null) return null; return map.get(cause); } static ErrorStatsManager getManager(); ErrorStatsData getStats(String route, String cause); void putStats(String route, String cause); }### Answer:
@Test public void testGetStats() { ErrorStatsManager sm = new ErrorStatsManager(); assertNotNull(sm); sm.putStats("test", "cause"); assertNotNull(sm.getStats("test", "cause")); } |
### Question:
ErrorStatsData implements NamedCount { @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ErrorStatsData that = (ErrorStatsData) o; return !(errorCause != null ? !errorCause.equals(that.errorCause) : that.errorCause != null); } ErrorStatsData(String route, String cause); @Override boolean equals(Object o); @Override int hashCode(); void update(); @Override String getName(); @Override long getCount(); }### Answer:
@Test public void testEquals() { ErrorStatsData sd = new ErrorStatsData("route", "test"); ErrorStatsData sd1 = new ErrorStatsData("route", "test"); ErrorStatsData sd2 = new ErrorStatsData("route", "test1"); ErrorStatsData sd3 = new ErrorStatsData("route", "test"); assertTrue(sd.equals(sd1)); assertTrue(sd1.equals(sd)); assertTrue(sd.equals(sd)); assertFalse(sd.equals(sd2)); assertFalse(sd2.equals(sd3)); } |
### Question:
StatsManager { @VisibleForTesting static final String extractClientIpFromXForwardedFor(String xForwardedFor) { return xForwardedFor.split(",")[0]; } static StatsManager getManager(); RouteStatusCodeMonitor getRouteStatusCodeMonitor(String route, int statusCode); void collectRequestStats(HttpRequestInfo req); void collectRouteStats(String route, int statusCode); }### Answer:
@Test public void extractsClientIpFromXForwardedFor() { final String ip1 = "hi"; final String ip2 = "hey"; assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(ip1)); assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s,%s", ip1, ip2))); assertEquals(ip1, StatsManager.extractClientIpFromXForwardedFor(String.format("%s, %s", ip1, ip2))); } |
### Question:
StatsManager { @VisibleForTesting static final boolean isIPv6(String ip) { return ip.split(":").length == 8; } static StatsManager getManager(); RouteStatusCodeMonitor getRouteStatusCodeMonitor(String route, int statusCode); void collectRequestStats(HttpRequestInfo req); void collectRouteStats(String route, int statusCode); }### Answer:
@Test public void isIPv6() { assertTrue(StatsManager.isIPv6("0:0:0:0:0:0:0:1")); assertTrue(StatsManager.isIPv6("2607:fb10:2:232:72f3:95ff:fe03:a6e7")); assertFalse(StatsManager.isIPv6("127.0.0.1")); assertFalse(StatsManager.isIPv6("10.2.233.134")); } |
### Question:
GroovyFileFilter implements FilenameFilter { public boolean accept(File dir, String name) { return name.endsWith(".groovy"); } boolean accept(File dir, String name); }### Answer:
@Test public void testGroovyFileFilter() { GroovyFileFilter filter = new GroovyFileFilter(); assertFalse(filter.accept(new File("/"), "file.mikey")); assertTrue(filter.accept(new File("/"), "file.groovy")); } |
### Question:
GroovyCompiler implements DynamicCodeCompiler { public Class<?> compile(String sCode, String sName) { GroovyClassLoader loader = getGroovyClassLoader(); LOG.warn("Compiling filter: " + sName); Class<?> groovyClass = loader.parseClass(sCode, sName); return groovyClass; } Class<?> compile(String sCode, String sName); Class<?> compile(File file); }### Answer:
@Test public void testLoadGroovyFromString() { GroovyCompiler compiler = Mockito.spy(new GroovyCompiler()); try { String code = "class test { public String hello(){return \"hello\" } } "; Class clazz = compiler.compile(code, "test"); assertNotNull(clazz); assertEquals(clazz.getName(), "test"); GroovyObject groovyObject = (GroovyObject) clazz.newInstance(); Object[] args = {}; String s = (String) groovyObject.invokeMethod("hello", args); assertEquals(s, "hello"); } catch (Exception e) { assertFalse(true); } } |
### Question:
FilterVerifier { public Class<?> compileGroovy(String sFilterCode) throws CompilationFailedException { GroovyClassLoader loader = new GroovyClassLoader(); return loader.parseClass(sFilterCode); } static FilterVerifier getInstance(); FilterInfo verifyFilter(String sFilterCode); Class<?> compileGroovy(String sFilterCode); }### Answer:
@Test public void testCompile() { Class<?> filterClass = FilterVerifier.INSTANCE.compileGroovy(sGoodGroovyScriptFilter); assertNotNull(filterClass); filterClass = FilterVerifier.INSTANCE.compileGroovy(sNotZuulFilterGroovy); assertNotNull(filterClass); assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.compileGroovy(sCompileFailCode)); } |
### Question:
FilterVerifier { public FilterInfo verifyFilter(String sFilterCode) throws CompilationFailedException, IllegalAccessException, InstantiationException { Class<?> groovyClass = compileGroovy(sFilterCode); Object instance = instantiateClass(groovyClass); checkZuulFilterInstance(instance); BaseFilter filter = (BaseFilter) instance; String filter_id = FilterInfo.buildFilterID(ZuulApplicationInfo.getApplicationName(), filter.filterType(), groovyClass.getSimpleName()); return new FilterInfo(filter_id, sFilterCode, filter.filterType(), groovyClass.getSimpleName(), filter.disablePropertyName(), "" + filter.filterOrder(), ZuulApplicationInfo.getApplicationName()); } static FilterVerifier getInstance(); FilterInfo verifyFilter(String sFilterCode); Class<?> compileGroovy(String sFilterCode); }### Answer:
@Test public void testVerify() throws Exception { FilterInfo filterInfo1 = FilterVerifier.INSTANCE.verifyFilter(sGoodGroovyScriptFilter); assertNotNull(filterInfo1); assertEquals(filterInfo1.getFilterID(), "null:filter:in"); assertEquals(filterInfo1.getFilterType(), FilterType.INBOUND); assertEquals(filterInfo1.getFilterName(), "filter"); assertFalse(filterInfo1.isActive()); assertFalse(filterInfo1.isCanary()); assertThrows(InstantiationException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sNotZuulFilterGroovy)); assertThrows(CompilationFailedException.class, () -> FilterVerifier.INSTANCE.verifyFilter(sCompileFailCode)); } |
### Question:
StripUntrustedProxyHeadersHandler extends ChannelInboundHandlerAdapter { @VisibleForTesting void stripXFFHeaders(HttpRequest req) { HttpHeaders headers = req.headers(); for (AsciiString headerName : HEADERS_TO_STRIP) { headers.remove(headerName); } } StripUntrustedProxyHeadersHandler(AllowWhen allowWhen); @Override void channelRead(ChannelHandlerContext ctx, Object msg); }### Answer:
@Test public void strip_match() { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); headers.add("x-forwarded-for", "abcd"); stripHandler.stripXFFHeaders(msg); assertFalse(headers.contains("x-forwarded-for")); } |
### Question:
ConfluenceExportMojo extends AbstractConfluenceExportMojo { @Override public void execute() throws MojoExecutionException, MojoFailureException { client = new DefaultHttpClient(); if (hasProxy()) { enableAxisProxy(); configureHttpClientProxy(); } initializeConfluenceTemplate(); boolean isVersion30AndAbove = isConfluenceVersion30andAbove(); try { confluenceTemplate.export(client, exportSpaces, isVersion30AndAbove, this.outputDirectory); } catch (RemoteException e) { throw new MojoExecutionException(e.getMessage(), e); } catch (IOException e) { throw new MojoExecutionException(e.getMessage() , e); } catch (ServiceException e) { throw new MojoExecutionException(e.getMessage() , e.getLinkedCause()); } catch (HttpException e){ throw new MojoExecutionException(e.getMessage() , e); } finally{ client.getConnectionManager().shutdown(); } } @Override void execute(); }### Answer:
@Test @Ignore public void testExportHtml() throws Exception { mojo.exportSpaces = new ArrayList<ExportSpace>(); configureExportHTML(); mojo.execute(); }
@Test @Ignore public void testExportPDF() throws Exception { mojo.exportSpaces = new ArrayList<ExportSpace>(); configureExportPDF(); mojo.execute(); }
@Test public void testExportHTMLandPDF() throws Exception { mojo.exportSpaces = new ArrayList<ExportSpace>(); configureExportHTML(); configureExportPDF(); mojo.execute(); } |
### Question:
HelloServiceImpl implements HelloService { @Override public String hello(String name) { return "Hello " + name; } @Override String hello(String name); }### Answer:
@Test void hello(@Autowired HelloService helloService) { TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME)); }
@Test void testApplicationContext(@Autowired ApplicationContext applicationContext) { HelloService helloService = applicationContext.getBean(HelloService.class); TestCase.assertNotNull(helloService); TestCase.assertEquals("Hello " + NAME, helloService.hello(NAME)); } |
### Question:
HelloServiceImpl implements HelloService { @Override public String hello(String name) { return "Hello " + name; } @Override String hello(String name); @Override int increase(int value); @Override boolean remoteRequest(); }### Answer:
@Test @DisplayName("测试service层的hello方法") void hello() { log.info("execute hello"); assertThat(helloService.hello(NAME)).isEqualTo("Hello " + NAME); } |
### Question:
HelloServiceImpl implements HelloService { @Override public int increase(int value) { return value + 1; } @Override String hello(String name); @Override int increase(int value); @Override boolean remoteRequest(); }### Answer:
@Test @DisplayName("测试service层的increase方法\uD83D\uDE31") void increase() { log.info("execute increase"); assertThat(helloService.increase(1)).isEqualByComparingTo(2); } |
### Question:
HelloServiceImpl implements HelloService { @Override public boolean remoteRequest() { try { Thread.sleep(1000); } catch (InterruptedException interruptedException) { interruptedException.printStackTrace(); } return true; } @Override String hello(String name); @Override int increase(int value); @Override boolean remoteRequest(); }### Answer:
@Test @Timeout(unit = TimeUnit.MILLISECONDS, value = 500) void remoteRequest() { assertThat(helloService.remoteRequest()).isEqualTo(true); } |
### Question:
HelloController { @RequestMapping(value = "/{name}", method = RequestMethod.GET) public String hello(@PathVariable String name){ return helloService.hello(name); } @RequestMapping(value = "/{name}", method = RequestMethod.GET) String hello(@PathVariable String name); }### Answer:
@Test void hello() { } |
### Question:
UserController { @ApiOperation(value = "根据名称模糊查找所有user记录", notes="根据名称模糊查找所有user记录") @ApiImplicitParam(name = "name", value = "用户名", paramType = "path", required = true, dataType = "String") @RequestMapping(value = "/findbyname/{name}", method = RequestMethod.GET) public List<User> findByName(@PathVariable("name") String name){ return userService.findByName(name); } @ApiOperation(value = "新增user记录", notes="新增user记录") @RequestMapping(value = "/insertwithfields",method = RequestMethod.PUT) User create(@RequestBody User user); @ApiOperation(value = "删除指定ID的user记录", notes="删除指定ID的user记录") @ApiImplicitParam(name = "id", value = "用户ID", paramType = "path", required = true, dataType = "Integer") @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) int delete(@PathVariable int id); @ApiOperation(value = "根据名称模糊查找所有user记录", notes="根据名称模糊查找所有user记录") @ApiImplicitParam(name = "name", value = "用户名", paramType = "path", required = true, dataType = "String") @RequestMapping(value = "/findbyname/{name}", method = RequestMethod.GET) List<User> findByName(@PathVariable("name") String name); }### Answer:
@Test @Order(2) void findByName() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/user/findbyname/"+ testName).accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$", hasSize(1))) .andDo(print()); } |
### Question:
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { logger.info( "TAGWizard - FreeDB Started" ); Hashtable<String, String> props = new Hashtable<String, String>(); props.put( "TAGWizard", FreeDBTAGWizardPlugin.NAME ); bundleContext.registerService( TAGWizardPlugin.class.getName(), new FreeDBTAGWizardPlugin(), props ); } void start( BundleContext bundleContext ); void stop( BundleContext bundleContext ); }### Answer:
@Test public void testStart() { BundleContext bc = Mockito.mock( BundleContext.class ); Activator a = new Activator(); a.start( bc ); Dictionary<String, ?> props = new Hashtable<String, String>(); Mockito.verify( bc, Mockito.times( 1 ) ).registerService( Mockito.eq( TAGWizardPlugin.class.getName() ), Mockito.any( FreeDBTAGWizardPlugin.class ), Mockito.any( props.getClass() ) ); } |
### Question:
MessicRadioPluginIceCast2 implements MessicRadioPlugin { @Override public String getName() { return NAME; } @Override synchronized void startCast(); synchronized void castSong( MessicRadioSong mp3song ); synchronized void stopCast(); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); boolean isStarted(); @Override MessicRadioStatus getStatus(); @Override MessicRadioInfo getInfo(); static final String NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; static final String PARAMETER_ENABLE; static final String PARAMETER_HOST; static final String PARAMETER_PUBLIC_HOST; static final String PARAMETER_PUBLIC_PORT; static final String PARAMETER_PUBLIC_URLPATH; static final String PARAMETER_PORT; static final String PARAMETER_PASSWORD; static final String PARAMETER_USER; static final String PARAMETER_MOUNT; }### Answer:
@Test public void testGetName() { MessicRadioPluginIceCast2 d = new MessicRadioPluginIceCast2(); Assert.assertTrue( d.getName().equals( MessicRadioPluginIceCast2.NAME ) ); } |
### Question:
MessicRadioPluginIceCast2 implements MessicRadioPlugin { @Override public String getDescription( Locale locale ) { return EN_DESCRIPTION; } @Override synchronized void startCast(); synchronized void castSong( MessicRadioSong mp3song ); synchronized void stopCast(); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); boolean isStarted(); @Override MessicRadioStatus getStatus(); @Override MessicRadioInfo getInfo(); static final String NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; static final String PARAMETER_ENABLE; static final String PARAMETER_HOST; static final String PARAMETER_PUBLIC_HOST; static final String PARAMETER_PUBLIC_PORT; static final String PARAMETER_PUBLIC_URLPATH; static final String PARAMETER_PORT; static final String PARAMETER_PASSWORD; static final String PARAMETER_USER; static final String PARAMETER_MOUNT; }### Answer:
@Test public void testDescription() { MessicRadioPluginIceCast2 i = new MessicRadioPluginIceCast2(); String desc = i.getDescription( Locale.ENGLISH ); Assert.assertTrue( desc.equals( MessicRadioPluginIceCast2.EN_DESCRIPTION ) ); } |
### Question:
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { logger.info( "MusicInfo - Duck Duck Go Started" ); Hashtable<String, String> props = new Hashtable<String, String>(); props.put( MusicInfoPlugin.MUSIC_INFO_PLUGIN_NAME, MusicInfoDuckDuckGoImages.NAME ); bundleContext.registerService( MusicInfoPlugin.class.getName(), new MusicInfoDuckDuckGoImages(), props ); } void start( BundleContext bundleContext ); void stop( BundleContext bundleContext ); }### Answer:
@Test public void testStart() { BundleContext bc = Mockito.mock( BundleContext.class ); Activator a = new Activator(); a.start( bc ); Dictionary<String, ?> props = new Hashtable<String, String>(); Mockito.verify( bc, Mockito.times( 1 ) ).registerService( Mockito.eq( MusicInfoPlugin.class.getName() ), Mockito.any( MusicInfoDuckDuckGoImages.class ), Mockito.any( props.getClass() ) ); } |
### Question:
MusicInfoDuckDuckGoImages implements MusicInfoPlugin { @Override public String getName() { return NAME; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetName() { MusicInfoDuckDuckGoImages d = new MusicInfoDuckDuckGoImages(); Assert.assertTrue( d.getName().equals( MusicInfoDuckDuckGoImages.NAME ) ); } |
### Question:
MusicInfoDuckDuckGoImages implements MusicInfoPlugin { @Override public String getDescription( Locale locale ) { return EN_DESCRIPTION; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testDescription() { MusicInfoDuckDuckGoImages i = new MusicInfoDuckDuckGoImages(); String desc = i.getDescription( Locale.ENGLISH ); Assert.assertTrue( desc.equals( MusicInfoDuckDuckGoImages.EN_DESCRIPTION ) ); } |
### Question:
MusicInfoDuckDuckGoImages implements MusicInfoPlugin { protected String constructURL( String[] phrases ) { String baseUrl = "https: for ( String phrase : phrases ) { baseUrl = baseUrl + "\"" + phrase + "\" "; } return baseUrl; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testConstructURL() { MusicInfoDuckDuckGoImages i = new MusicInfoDuckDuckGoImages(); String surl = i.constructURL( new String[] { "test", "another test" } ); System.out.println( surl ); Assert.assertTrue( surl.trim().equals( "https: } |
### Question:
MusicInfoDuckDuckGoImages implements MusicInfoPlugin { @Override public byte[] getProviderIcon() { InputStream is = MusicInfoDuckDuckGoImages.class.getResourceAsStream( "/org/messic/server/api/musicinfo/duckduckgoimages/9129e7ed.png" ); try { return readInputStream( is ); } catch ( IOException e ) { return null; } } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetProviderIcon() { MusicInfoDuckDuckGoImages i = new MusicInfoDuckDuckGoImages(); Assert.assertTrue( i.getProviderIcon() != null ); Assert.assertTrue( i.getProviderIcon().length > 0 ); } |
### Question:
MusicInfoDuckDuckGoImages implements MusicInfoPlugin { @Override public String getProviderName() { return PROVIDER_NAME; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetProviderName() { MusicInfoDuckDuckGoImages i = new MusicInfoDuckDuckGoImages(); Assert.assertTrue( i.getProviderName().equals( MusicInfoDuckDuckGoImages.PROVIDER_NAME ) ); } |
### Question:
FreeDBTAGWizardPlugin implements TAGWizardPlugin { @Override public String getName() { return NAME; } @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override List<Album> getAlbumInfo( Album albumHelpInfo, File[] files ); static byte[] readInputStream( InputStream is ); static final String NAME; static final String DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetName() { FreeDBTAGWizardPlugin d = new FreeDBTAGWizardPlugin(); Assert.assertTrue( d.getName().equals( FreeDBTAGWizardPlugin.NAME ) ); }
@Test public void testGetProviderName() { FreeDBTAGWizardPlugin i = new FreeDBTAGWizardPlugin(); Assert.assertTrue( i.getName().equals( FreeDBTAGWizardPlugin.NAME ) ); } |
### Question:
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { logger.info( "MusicInfo - Discogs Started" ); Hashtable<String, String> props = new Hashtable<String, String>(); props.put( MusicInfoPlugin.MUSIC_INFO_PLUGIN_NAME, MusicInfoDiscogsTagWizardPlugin.NAME ); bundleContext.registerService( MusicInfoPlugin.class.getName(), new MusicInfoDiscogsTagWizardPlugin(), props ); } void start( BundleContext bundleContext ); void stop( BundleContext bundleContext ); }### Answer:
@Test public void testStart() { BundleContext bc = Mockito.mock( BundleContext.class ); Activator a = new Activator(); a.start( bc ); Dictionary<String, ?> props = new Hashtable<String, String>(); Mockito.verify( bc, Mockito.times( 1 ) ).registerService( Mockito.eq( MusicInfoPlugin.class.getName() ), Mockito.any( MusicInfoDiscogsTagWizardPlugin.class ), Mockito.any( props.getClass() ) ); } |
### Question:
MusicInfoDiscogsTagWizardPlugin implements MusicInfoPlugin { @Override public String getName() { return NAME; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetName() { MusicInfoDiscogsTagWizardPlugin d = new MusicInfoDiscogsTagWizardPlugin(); Assert.assertTrue( d.getName().equals( MusicInfoDiscogsTagWizardPlugin.NAME ) ); } |
### Question:
MusicInfoDiscogsTagWizardPlugin implements MusicInfoPlugin { @Override public String getDescription( Locale locale ) { return EN_DESCRIPTION; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testDescription() { MusicInfoDiscogsTagWizardPlugin i = new MusicInfoDiscogsTagWizardPlugin(); String desc = i.getDescription( Locale.ENGLISH ); Assert.assertTrue( desc.equals( MusicInfoDiscogsTagWizardPlugin.EN_DESCRIPTION ) ); } |
### Question:
MusicInfoDiscogsTagWizardPlugin implements MusicInfoPlugin { @Override public byte[] getProviderIcon() { InputStream is = MusicInfoDiscogsTagWizardPlugin.class.getResourceAsStream( "/org/messic/server/api/musicinfo/discogs/discogs.png" ); try { return readInputStream( is ); } catch ( IOException e ) { return null; } } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetProviderIcon() { MusicInfoDiscogsTagWizardPlugin i = new MusicInfoDiscogsTagWizardPlugin(); Assert.assertTrue( i.getProviderIcon() != null ); Assert.assertTrue( i.getProviderIcon().length > 0 ); } |
### Question:
MusicInfoDiscogsTagWizardPlugin implements MusicInfoPlugin { @Override public String getProviderName() { return PROVIDER_NAME; } @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); static byte[] readInputStream( InputStream is ); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetProviderName() { MusicInfoDiscogsTagWizardPlugin i = new MusicInfoDiscogsTagWizardPlugin(); Assert.assertTrue( i.getProviderName().equals( MusicInfoDiscogsTagWizardPlugin.PROVIDER_NAME ) ); } |
### Question:
MusicInfoWikipediaPlugin implements MusicInfoPlugin { public String search( String query ) throws IOException, SAXException { return search( new Locale( "en", "en" ), query ); } String search( String query ); static byte[] readInputStream( InputStream is ); @Override String getName(); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override String getDescription( Locale locale ); @Override String getAuthorInfo( Locale locale, String authorName ); @Override String getAlbumInfo( Locale locale, String authorName, String albumName ); @Override String getSongInfo( Locale locale, String authorName, String albumName, String songName ); @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override byte[] getProviderIcon(); @Override String getProviderName(); static final String NAME; static final String PROVIDER_NAME; static final String EN_DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testSearch() throws IOException, SAXException { MusicInfoWikipediaPlugin miwp = new MusicInfoWikipediaPlugin(); String result = miwp.search( "radiohead" ); Assert.assertTrue( result.length() > 0 ); } |
### Question:
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { logger.info( "TAGWizard - Discogs Started" ); Hashtable<String, String> props = new Hashtable<String, String>(); props.put( "TAGWizard", DiscogsTAGWizardPlugin.NAME ); bundleContext.registerService( TAGWizardPlugin.class.getName(), new DiscogsTAGWizardPlugin(), props ); } void start( BundleContext bundleContext ); void stop( BundleContext bundleContext ); }### Answer:
@Test public void testStart() { BundleContext bc = Mockito.mock( BundleContext.class ); Activator a = new Activator(); a.start( bc ); Dictionary<String, ?> props = new Hashtable<String, String>(); Mockito.verify( bc, Mockito.times( 1 ) ).registerService( Mockito.eq( TAGWizardPlugin.class.getName() ), Mockito.any( DiscogsTAGWizardPlugin.class ), Mockito.any( props.getClass() ) ); } |
### Question:
DiscogsTAGWizardPlugin implements TAGWizardPlugin { @Override public String getName() { return NAME; } @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override List<Album> getAlbumInfo( Album albumHelpInfo, File[] files ); static byte[] readInputStream( InputStream is ); static final String NAME; static final String DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testGetName() { DiscogsTAGWizardPlugin d = new DiscogsTAGWizardPlugin(); Assert.assertTrue( d.getName().equals( DiscogsTAGWizardPlugin.NAME ) ); }
@Test public void testGetProviderName() { DiscogsTAGWizardPlugin i = new DiscogsTAGWizardPlugin(); Assert.assertTrue( i.getName().equals( DiscogsTAGWizardPlugin.NAME ) ); } |
### Question:
DiscogsTAGWizardPlugin implements TAGWizardPlugin { @Override public String getDescription( Locale locale ) { return DESCRIPTION; } @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override List<Album> getAlbumInfo( Album albumHelpInfo, File[] files ); static byte[] readInputStream( InputStream is ); static final String NAME; static final String DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testDescription() { DiscogsTAGWizardPlugin i = new DiscogsTAGWizardPlugin(); String desc = i.getDescription( Locale.ENGLISH ); Assert.assertTrue( desc.equals( DiscogsTAGWizardPlugin.DESCRIPTION ) ); } |
### Question:
FreeDBTAGWizardPlugin implements TAGWizardPlugin { @Override public String getDescription( Locale locale ) { return DESCRIPTION; } @Override float getVersion(); @Override float getMinimumMessicVersion(); @Override String getName(); @Override String getDescription( Locale locale ); @Override Properties getConfiguration(); @Override void setConfiguration( Properties properties ); @Override List<Album> getAlbumInfo( Album albumHelpInfo, File[] files ); static byte[] readInputStream( InputStream is ); static final String NAME; static final String DESCRIPTION; static final float VERSION; static final float MINIMUM_MESSIC_VERSION; }### Answer:
@Test public void testDescription() { FreeDBTAGWizardPlugin i = new FreeDBTAGWizardPlugin(); String desc = i.getDescription( Locale.ENGLISH ); Assert.assertTrue( desc.equals( FreeDBTAGWizardPlugin.DESCRIPTION ) ); } |
### Question:
MessicDataSource extends BasicDataSource { @Override public synchronized void setUrl( String url ) { String musicFolder = System.getProperty( "messic.musicfolder" ); if ( musicFolder == null || musicFolder.length() <= 0 ) { musicFolder = System.getProperty( "user.home" ) + File.separatorChar + "messic-data"; } File f = new File( musicFolder ); if ( !f.exists() ) { f.mkdirs(); } String messic_path = f.getAbsolutePath(); messic_path = messic_path.replaceAll( "\\\\", "\\\\\\\\" ); String newURL = url.replaceAll( "MESSIC_PATH", messic_path ); databasePath = messic_path; super.setUrl( newURL ); } @Override synchronized void setUrl( String url ); static String databasePath; }### Answer:
@Test public void testSetUrl() { MessicDataSource mds = new MessicDataSource(); String urlTest = "jdbc:h2:MESSIC_PATH/db;DB_CLOSE_DELAY=-1"; mds.setUrl( urlTest ); Assert.assertTrue( !mds.getUrl().equals( urlTest ) ); } |
### Question:
Activator implements BundleActivator { public void start( BundleContext bundleContext ) { try { String sversion = LibShout.get().getVersion(); if ( !sversion.equals( "2.3.1" ) ) { logger.warn( "icecast2 version " + sversion ); } logger.info( "Radio - Icecast2 Started" ); Hashtable<String, String> props = new Hashtable<String, String>(); props.put( MessicRadioPlugin.MESSIC_RADIO_PLUGIN_NAME, MessicRadioPluginIceCast2.NAME ); bundleContext.registerService( MessicRadioPlugin.class.getName(), new MessicRadioPluginIceCast2(), props ); } catch ( Exception e ) { logger.info( "Radio - Icecast2 Not Available" ); } catch ( Error e ) { logger.info( "Radio - Icecast2 Not Available" ); } } void start( BundleContext bundleContext ); void stop( BundleContext bundleContext ); }### Answer:
@Test public void testStart() { } |
### Question:
RingStream implements Iterable<E>, Iterator<E> { public Stream<E> streamLimited(int count) { return streamUnlimited().limit(count); } @SafeVarargs RingStream(E... elements); @Override boolean hasNext(); @Override Iterator<E> iterator(); @Override E next(); int size(); Stream<E> streamAll(); Stream<E> streamLimited(int count); Stream<E> streamUnlimited(); @SafeVarargs final RingStream<E> with(E... others); }### Answer:
@Test public void testLimitedStream() { RingStream<String> s = new RingStream<>("foo", "bar", "baz"); assertTrue(s.streamLimited(2).noneMatch("baz"::equals)); assertTrue(s.streamLimited(2).noneMatch("bar"::equals)); assertTrue(s.streamLimited(2).noneMatch("foo"::equals)); } |
### Question:
MsgDeliveryTagMapping { public void basicAck(long deliveryTag, boolean multiple) throws IOException { Map<Long, MsgResponse> acks = multiple ? deliveryTags.headMap(deliveryTag, true).descendingMap() : deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(acks, MsgResult.ACK, multiple, false); acks.clear(); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }### Answer:
@Test void basicAck() { when(envelope.getDeliveryTag()).thenReturn(40L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(40L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicAck(e.getDeliveryTag(), false)); assertDoesNotThrow(() -> verify(channel).basicAck(40L, false)); } |
### Question:
MsgDeliveryTagMapping { void basicNack(long deliveryTag, boolean multiple, boolean requeue) throws IOException { Map<Long, MsgResponse> nacks = multiple ? deliveryTags.headMap(deliveryTag, true).descendingMap() : deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(nacks, MsgResult.NACK, multiple, requeue); nacks.clear(); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }### Answer:
@Test void basicNack() { when(envelope.getDeliveryTag()).thenReturn(41L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(41L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicNack(e.getDeliveryTag(), false, false)); assertDoesNotThrow(() -> verify(channel).basicNack(41L, false, false)); } |
### Question:
MsgDeliveryTagMapping { void basicReject(long deliveryTag, boolean requeue) throws IOException { Map<Long, MsgResponse> rejections = deliveryTags.subMap(deliveryTag, deliveryTag + 1); eachChannelOnce(rejections, MsgResult.REJECT, false, requeue); rejections.clear(); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }### Answer:
@Test void basicReject() { when(envelope.getDeliveryTag()).thenReturn(43L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(43L, e.getDeliveryTag()); assertDoesNotThrow(() -> map.basicReject(e.getDeliveryTag(), false)); assertDoesNotThrow(() -> verify(channel).basicReject(43L, false)); } |
### Question:
MsgDeliveryTagMapping { Consumer createConsumerDecorator(Consumer delegate, Channel channel) { return new MappingConsumer(this, delegate, channel); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }### Answer:
@Test void createConsumerDecorator() { Consumer c = map.createConsumerDecorator(callback, channel); } |
### Question:
MsgDeliveryTagMapping { Envelope envelopeWithPseudoDeliveryTag(Channel channel, Envelope envelope) { long tag = mapDelivery(channel, envelope.getDeliveryTag()); return new Envelope( tag, envelope.isRedeliver(), envelope.getExchange(), envelope.getRoutingKey()); } MsgDeliveryTagMapping(); void basicAck(long deliveryTag, boolean multiple); }### Answer:
@Test void mapEnvelope() { when(envelope.getDeliveryTag()).thenReturn(42L); Envelope e = map.envelopeWithPseudoDeliveryTag(channel, envelope); assertNotEquals(42L, e.getDeliveryTag()); } |
### Question:
Utility { static byte[] encode(BigInteger n) { byte[] encodedN; if (n.signum() == 0) { encodedN = new byte[0]; } else { byte[] nAsByteArray = n.toByteArray(); int firstNonZeroIndex = 0; while ((nAsByteArray[firstNonZeroIndex] == 0) && (firstNonZeroIndex < nAsByteArray.length)) { firstNonZeroIndex++; } encodedN = new byte[nAsByteArray.length - firstNonZeroIndex]; System.arraycopy(nAsByteArray, firstNonZeroIndex, encodedN, 0, nAsByteArray.length - firstNonZeroIndex); } return encodedN; } private Utility(); static byte[] reverse(byte[] source); static byte[] toLEBytes(int i); }### Answer:
@Test public void testEncode() { assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA, 0xBE), Utility.encode(BigInteger.valueOf(0xCAFEBABE))); assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA), Utility.encode(BigInteger.valueOf(0x00CAFEBA))); assertArrayEquals(TestUtility.cba(0xCA, 0xFE), Utility.encode(BigInteger.valueOf(0x0000CAFE))); assertArrayEquals(TestUtility.cba(0xCA), Utility.encode(BigInteger.valueOf(0x000000CA))); assertArrayEquals(new byte[0], Utility.encode(BigInteger.valueOf(0))); } |
### Question:
NumberTheory { static int countLowZeroBits(BigInteger n) { int lowZero = 0; if (n.signum() > 0) { byte[] bytes = n.toByteArray(); for (int i = bytes.length - 1; i >= 0; i--) { byte x = bytes[i]; if (x != 0) { lowZero += countTrailingZeros(x); break; } else { lowZero += 8; } } } return lowZero; } private NumberTheory(); }### Answer:
@Test public void testCountLowZeroBits() { assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b0))); assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(-1))); assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(-1000))); assertEquals(8, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b100000000))); assertEquals(7, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b110000000))); assertEquals(0, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b11111111))); assertEquals(1, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b11111110))); assertEquals(2, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b100))); assertEquals(16, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b10000000000000000))); assertEquals(17, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b100000000000000000))); assertEquals(15, NumberTheory.countLowZeroBits(BigInteger.valueOf(0b1000000000000000))); } |
### Question:
NumberTheory { static int countTrailingZeros(byte n) { for (int i = 0; i != 8; ++i) { if (((n >> i) & 0x01) > 0) { return i; } } return 8; } private NumberTheory(); }### Answer:
@Test public void testCountTrailingZeros() { assertEquals(8, NumberTheory.countTrailingZeros((byte) 0b0)); assertEquals(0, NumberTheory.countTrailingZeros((byte) 0b1)); assertEquals(1, NumberTheory.countTrailingZeros((byte) 0b11111110)); assertEquals(6, NumberTheory.countTrailingZeros((byte) 0b11000000)); assertEquals(4, NumberTheory.countTrailingZeros((byte) 0b00010000)); assertEquals(1, NumberTheory.countTrailingZeros((byte) 0b10101010)); } |
### Question:
Utility { public static byte[] reverse(byte[] source) { int len = source.length; byte[] destination = new byte[len]; for (int i = 0; i < len; i++) { destination[len - i - 1] = source[i]; } return destination; } private Utility(); static byte[] reverse(byte[] source); static byte[] toLEBytes(int i); }### Answer:
@Test public void testReverse() { assertArrayEquals(new byte[0], Utility.reverse(new byte[0])); assertArrayEquals(TestUtility.cba(0xCA, 0xFE, 0xBA, 0xBE), Utility.reverse(TestUtility.cba(0xBE, 0xBA, 0xFE, 0xCA))); assertArrayEquals(TestUtility.cba(0xCA), Utility.reverse(TestUtility.cba(0xCA))); } |
### Question:
HealthMeterRegistry extends SimpleMeterRegistry { public static Builder builder(HealthConfig config) { return new Builder(config); } protected HealthMeterRegistry(HealthConfig config, Collection<ServiceLevelObjective> serviceLevelObjectives,
Collection<MeterFilter> serviceLevelObjectiveFilters,
Clock clock, ThreadFactory threadFactory); static Builder builder(HealthConfig config); Collection<ServiceLevelObjective> getServiceLevelObjectives(); void start(ThreadFactory threadFactory); void stop(); @Override void close(); }### Answer:
@Test void onlyMetricsThatAreServiceLevelIndicatorsAreRegistered() { HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) .clock(new MockClock()) .serviceLevelObjectives( ServiceLevelObjective .build("counter.throughput") .count(search -> search.name("my.counter")) .isGreaterThan(1) ) .build(); assertThat(registry.getMeters()).isEmpty(); registry.counter("my.counter", "k", "v").increment(); assertThat(registry.getMeters().size()).isEqualTo(1); registry.counter("another.counter").increment(); assertThat(registry.getMeters().size()).isEqualTo(1); }
@Test void applyRequiredBinders() { HealthMeterRegistry registry = HealthMeterRegistry.builder(HealthConfig.DEFAULT) .clock(new MockClock()) .serviceLevelObjectives( ServiceLevelObjective .build("counter.throughput") .requires(new JvmMemoryMetrics()) .value(search -> search.name("jvm.memory.used")) .isGreaterThan(1) ) .build(); assertThat(registry.getMeters().stream().map(m -> m.getId().getName())) .containsOnly("jvm.memory.used") .isNotEmpty(); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.