index
int64
0
0
repo_id
stringlengths
26
205
file_path
stringlengths
51
246
content
stringlengths
8
433k
__index_level_0__
int64
0
10k
0
Create_ds/spectator/spectator-perf/src/test/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/test/java/com/netflix/spectator/perf/AtlasMemoryUseTest.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import org.junit.jupiter.api.Disabled; @Disabled public class AtlasMemoryUseTest extends MemoryUseTest { public AtlasMemoryUseTest() { super("atlas"); } }
6,100
0
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator/perf/TagValueExplosion.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import java.util.function.Consumer; /** * Tests the ability to cope with a tag value explosion. This is a single tag value that has * many distinct values that are typically only updated once. */ final class TagValueExplosion implements Consumer<Registry> { @Override public void accept(Registry registry) { Id baseId = registry.createId("tagValueExplosion"); for (int i = 0; i < 1_000_000; ++i) { registry.counter(baseId.withTag("i", "" + i)).increment(); } } }
6,101
0
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator/perf/TagKeyExplosion.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import java.util.function.Consumer; /** * Tests the ability to cope with an explosion of tag keys. */ final class TagKeyExplosion implements Consumer<Registry> { @Override public void accept(Registry registry) { for (int i = 0; i < 1000000; ++i) { Id id = registry.createId("tagKeyExplosion").withTag("k-" + i, "foo"); registry.counter(id).increment(); } } }
6,102
0
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator/perf/ManyTags.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import java.util.Random; import java.util.function.Consumer; /** * Tests the memory overhead of many tag permutations. In general this covers: 1) the overhead * per meter, and 2) whether or not strings are interned when added to the tag sets. */ final class ManyTags implements Consumer<Registry> { @Override public void accept(Registry registry) { Random random = new Random(42); for (int i = 0; i < 10000; ++i) { Id id = registry.createId("manyTagsTest"); for (int j = 0; j < 20; ++j) { String v = "" + random.nextInt(10); id = id.withTag("" + j, v); } registry.counter(id).increment(); } } }
6,103
0
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator/perf/Main.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import com.netflix.spectator.api.Clock; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.atlas.AtlasRegistry; import com.netflix.spectator.servo.ServoRegistry; import java.util.HashMap; import java.util.Map; import java.util.function.Consumer; import org.openjdk.jol.info.GraphLayout; /** * Runs some basic tests against Spectator registry implementations to help gauge the * performance. This is used for automated tests around the memory usage and can also be * used for capturing flame graphs or with flight recorder to get CPU profile information. */ public final class Main { private Main() { } private static Registry createRegistry(String type) { Registry registry = null; switch (type) { case "noop": registry = new NoopRegistry(); break; case "default": registry = new DefaultRegistry(); break; case "atlas": registry = new AtlasRegistry(Clock.SYSTEM, System::getProperty); break; case "servo": registry = new ServoRegistry(); break; default: throw new IllegalArgumentException("unknown registry type: '" + type + "'"); } return registry; } private static final Map<String, Consumer<Registry>> TESTS = new HashMap<>(); static { TESTS.put("many-tags", new ManyTags()); TESTS.put("name-explosion", new NameExplosion()); TESTS.put("tag-key-explosion", new TagKeyExplosion()); TESTS.put("tag-value-explosion", new TagValueExplosion()); } /** * Run a test for a given type of registry. * * @param type * Should be one of `noop`, `default`, `atlas`, or `servo`. * @param test * Test name to run. See the `TESTS` map for available options. */ public static Registry run(String type, String test) { Registry registry = createRegistry(type); TESTS.get(test).accept(registry); return registry; } /** Run a test and output the memory footprint of the registry. */ @SuppressWarnings("PMD") public static void main(String[] args) { if (args.length < 2) { System.out.println("Usage: perf <registry> <test>"); System.exit(1); } Registry registry = run(args[0], args[1]); GraphLayout igraph = GraphLayout.parseInstance(registry); System.out.println(igraph.toFootprint()); } }
6,104
0
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator
Create_ds/spectator/spectator-perf/src/main/java/com/netflix/spectator/perf/NameExplosion.java
/* * Copyright 2014-2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spectator.perf; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import java.util.function.Consumer; /** * Tests the ability to cope with a name explosion. Some users try to mangle everything * into the name including things like timestamps, retry numbers, etc. If these values are * not bounded it can cause problems over time. */ final class NameExplosion implements Consumer<Registry> { @Override public void accept(Registry registry) { for (int i = 0; i < 1000000; ++i) { Id id = registry.createId("nameExplosion-" + i); registry.counter(id).increment(); } } }
6,105
0
Create_ds/RxGroups/sample/src/test/java/com/airbnb
Create_ds/RxGroups/sample/src/test/java/com/airbnb/rxgroups/ExampleUnitTest.java
package com.airbnb.rxgroups; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
6,106
0
Create_ds/RxGroups/sample/src/main/java/com/airbnb
Create_ds/RxGroups/sample/src/main/java/com/airbnb/rxgroups/SampleApplication.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import android.app.Application; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; public class SampleApplication extends Application { private final ObservableManager observableManager = new ObservableManager(); private final Observable<Long> timerObservable = Observable.interval(1, 1, TimeUnit.SECONDS); @Override public void onCreate() { super.onCreate(); } ObservableManager observableManager() { return observableManager; } Observable<Long> timerObservable() { return timerObservable; } }
6,107
0
Create_ds/RxGroups/sample/src/main/java/com/airbnb
Create_ds/RxGroups/sample/src/main/java/com/airbnb/rxgroups/MainActivity.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; public class MainActivity extends AppCompatActivity { private static final String IS_RUNNING = "IS_RUNNING"; private static final String TAG = "MainActivity"; private GroupLifecycleManager groupLifecycleManager; private TextView output; private Observable<Long> timerObservable; private boolean isRunning; private boolean isLocked; @AutoResubscribe final AutoResubscribingObserver<Long> observer = new AutoResubscribingObserver<Long>() { @Override public void onComplete() { Log.d(TAG, "onCompleted()"); } @Override public void onError(Throwable e) { Log.e(TAG, "onError()", e); } @Override public void onNext(Long l) { Log.d(TAG, "Current Thread=" + Thread.currentThread().getName() + ", onNext()=" + l); output.setText(output.getText() + " " + l); } }; private Drawable alarmOffDrawable; private Drawable alarmDrawable; private Drawable lockDrawable; private Drawable unlockDrawable; private FloatingActionButton startStop; private FloatingActionButton lockUnlock; private ObservableGroup observableGroup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); startStop = (FloatingActionButton) findViewById(R.id.fab); lockUnlock = (FloatingActionButton) findViewById(R.id.fab_pause_resume); alarmOffDrawable = ContextCompat.getDrawable(this, R.drawable.ic_alarm_off_black_24dp); alarmDrawable = ContextCompat.getDrawable(this, R.drawable.ic_alarm_black_24dp); lockDrawable = ContextCompat.getDrawable(this, R.drawable.ic_lock_outline_black_24dp); unlockDrawable = ContextCompat.getDrawable(this, R.drawable.ic_lock_open_black_24dp); output = (TextView) findViewById(R.id.txt_output); setSupportActionBar(toolbar); startStop.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickStartStopTimer(v); } }); lockUnlock.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickLockUnlockGroup(v); } }); SampleApplication application = (SampleApplication) getApplication(); ObservableManager manager = application.observableManager(); groupLifecycleManager = GroupLifecycleManager.onCreate(manager, savedInstanceState, this); timerObservable = application.timerObservable(); observableGroup = groupLifecycleManager.group(); if (savedInstanceState != null && savedInstanceState.getBoolean(IS_RUNNING)) { isRunning = true; startStop.setImageDrawable(alarmOffDrawable); } } private void onClickLockUnlockGroup(View view) { if (isRunning) { if (isLocked) { Toast.makeText(this, "Group unlocked", Toast.LENGTH_SHORT).show(); lockUnlock.setImageDrawable(unlockDrawable); observableGroup.unlock(); } else { Toast.makeText(this, "Group locked", Toast.LENGTH_SHORT).show(); lockUnlock.setImageDrawable(lockDrawable); observableGroup.lock(); } isLocked = !isLocked; } } private void onClickStartStopTimer(View view) { if (!isRunning) { Toast.makeText(this, "Started timer", Toast.LENGTH_SHORT).show(); isRunning = true; startStop.setImageDrawable(alarmOffDrawable); timerObservable .observeOn(AndroidSchedulers.mainThread()) .compose(groupLifecycleManager.transform(observer)) .subscribe(observer); } else { Toast.makeText(this, "Stopped timer", Toast.LENGTH_SHORT).show(); isRunning = false; startStop.setImageDrawable(alarmDrawable); observableGroup.cancelAllObservablesForObserver(observer); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); groupLifecycleManager.onSaveInstanceState(outState); outState.putBoolean(IS_RUNNING, isRunning); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume()"); groupLifecycleManager.onResume(); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause()"); groupLifecycleManager.onPause(); } @Override protected void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy()"); groupLifecycleManager.onDestroy(this); } }
6,108
0
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb/rxgroups/SubscriptionProxyTest.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import org.junit.Test; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.observers.TestObserver; import io.reactivex.subjects.PublishSubject; import io.reactivex.subjects.ReplaySubject; import static org.assertj.core.api.Assertions.assertThat; public class SubscriptionProxyTest { @Test public void testInitialState() { Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception { emitter.onNext(1234); emitter.onComplete(); } }); SubscriptionProxy<Integer> proxy = SubscriptionProxy.create(observable); assertThat(proxy.isDisposed()).isEqualTo(false); assertThat(proxy.isCancelled()).isEqualTo(false); } @Test public void testSubscriptionState() { TestObserver<String> observer = new TestObserver<>(); PublishSubject<String> subject = PublishSubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); assertThat(proxy.isDisposed()).isEqualTo(false); assertThat(proxy.isCancelled()).isEqualTo(false); proxy.dispose(); assertThat(proxy.isDisposed()).isEqualTo(true); assertThat(proxy.isCancelled()).isEqualTo(false); proxy.cancel(); assertThat(proxy.isDisposed()).isEqualTo(true); assertThat(proxy.isCancelled()).isEqualTo(true); } @Test public void testSubscribe() { TestObserver<Integer> observer = new TestObserver<>(); Observable<Integer> observable = Observable.create(new ObservableOnSubscribe<Integer>() { @Override public void subscribe(@NonNull ObservableEmitter<Integer> emitter) throws Exception { emitter.onNext(1234); emitter.onComplete(); } }); SubscriptionProxy<Integer> proxy = SubscriptionProxy.create(observable); proxy.subscribe(observer); observer.assertComplete(); observer.assertValue(1234); } @Test public void testUnsubscribe() { TestObserver<String> observer = new TestObserver<>(); PublishSubject<String> subject = PublishSubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); proxy.dispose(); subject.onNext("Avanti!"); subject.onComplete(); assertThat(proxy.isDisposed()).isEqualTo(true); observer.awaitTerminalEvent(10, TimeUnit.MILLISECONDS); observer.assertNotComplete(); observer.assertNoValues(); } private static class TestOnUnsubscribe implements Action { boolean called = false; @Override public void run() { called = true; } } @Test public void testCancelShouldUnsubscribeFromSourceObservable() { TestObserver<String> observer = new TestObserver<>(); final TestOnUnsubscribe onUnsubscribe = new TestOnUnsubscribe(); Observable<String> observable = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception { emitter.setDisposable(new Disposable() { @Override public void dispose() { onUnsubscribe.run(); } @Override public boolean isDisposed() { return onUnsubscribe.called; } }); } }); SubscriptionProxy<String> proxy = SubscriptionProxy.create(observable); proxy.subscribe(observer); proxy.cancel(); assertThat(proxy.isDisposed()).isEqualTo(true); assertThat(proxy.isCancelled()).isEqualTo(true); assertThat(onUnsubscribe.called).isEqualTo(true); } @Test public void testUnsubscribeShouldNotUnsubscribeFromSourceObservable() { TestObserver<String> observer = new TestObserver<>(); final TestOnUnsubscribe dispose = new TestOnUnsubscribe(); Observable<String> sourceObservable = Observable.create(new ObservableOnSubscribe<String>() { @Override public void subscribe(@NonNull ObservableEmitter<String> emitter) throws Exception { emitter.setDisposable(new Disposable() { @Override public void dispose() { dispose.run(); } @Override public boolean isDisposed() { return dispose.called; } }); } }); SubscriptionProxy<String> proxy = SubscriptionProxy.create(sourceObservable); proxy.subscribe(observer); proxy.dispose(); assertThat(proxy.isDisposed()).isEqualTo(true); assertThat(proxy.isCancelled()).isEqualTo(false); assertThat(dispose.called).isEqualTo(false); } @Test public void testUnsubscribeBeforeEmit() { TestObserver<String> observer = new TestObserver<>(); ReplaySubject<String> subject = ReplaySubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); proxy.dispose(); observer.assertNotComplete(); observer.assertNoValues(); subject.onNext("Avanti!"); subject.onComplete(); // disposable observables may not be resused in RxJava2 observer = new TestObserver<>(); proxy.subscribe(observer); observer.assertComplete(); observer.assertValue("Avanti!"); } @Test public void shouldCacheResultsWhileUnsubscribedAndDeliverAfterResubscription() { TestObserver<String> observer = new TestObserver<>(); ReplaySubject<String> subject = ReplaySubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); proxy.dispose(); observer.assertNoValues(); subject.onNext("Avanti!"); subject.onComplete(); // disposable observables may not be resused in RxJava2 observer = new TestObserver<>(); proxy.subscribe(observer); observer.awaitTerminalEvent(3, TimeUnit.SECONDS); observer.assertValue("Avanti!"); } @Test public void shouldRedeliverSameResultsToDifferentSubscriber() { // Use case: When rotating an activity, ObservableManager will re-subscribe original request's // Observable to a new Observer, which is a member of the new activity instance. In this // case, we may want to redeliver any previous results (if the request is still being // managed by ObservableManager). TestObserver<String> observer = new TestObserver<>(); ReplaySubject<String> subject = ReplaySubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); subject.onNext("Avanti!"); subject.onComplete(); proxy.dispose(); TestObserver<String> newSubscriber = new TestObserver<>(); proxy.subscribe(newSubscriber); newSubscriber.awaitTerminalEvent(3, TimeUnit.SECONDS); newSubscriber.assertComplete(); newSubscriber.assertValue("Avanti!"); observer.assertComplete(); observer.assertValue("Avanti!"); } @Test public void multipleSubscribesForSameObserverShouldBeIgnored() { TestObserver<String> observer = new TestObserver<>(); PublishSubject<String> subject = PublishSubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); proxy.subscribe(observer); proxy.dispose(); subject.onNext("Avanti!"); subject.onComplete(); assertThat(proxy.isDisposed()).isEqualTo(true); observer.awaitTerminalEvent(10, TimeUnit.MILLISECONDS); observer.assertNotComplete(); observer.assertNoValues(); } @Test public void shouldKeepDeliveringEventsAfterResubscribed() { TestObserver<String> observer = new TestObserver<>(); ReplaySubject<String> subject = ReplaySubject.create(); SubscriptionProxy<String> proxy = SubscriptionProxy.create(subject); proxy.subscribe(observer); subject.onNext("Avanti 1"); proxy.dispose(); observer = new TestObserver<>(); proxy.subscribe(observer); subject.onNext("Avanti!"); observer.assertValues("Avanti 1", "Avanti!"); } }
6,109
0
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb/rxgroups/ObservableManagerTest.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import org.junit.Test; import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; public class ObservableManagerTest { private final ObservableManager observableManager = new ObservableManager(); @Test public void testNewGroup() { ObservableGroup group = observableManager.newGroup(); assertThat(group.id()).isEqualTo(1); } @Test public void testGetGroup() { ObservableGroup originalGroup = observableManager.newGroup(); ObservableGroup group = observableManager.getGroup(originalGroup.id()); assertThat(group.id()).isEqualTo(1); } @Test public void testGetGroupThrowsIfNonExistent() { try { observableManager.getGroup(1); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testGetGroupThrowsIfDestroyed() { try { ObservableGroup group = observableManager.newGroup(); group.destroy(); observableManager.getGroup(1); fail(); } catch (IllegalArgumentException ignored) { } } @Test public void testIdsAreNotReused() { for (int i = 1; i < 10; i++) { ObservableGroup group = observableManager.newGroup(); assertThat(group.id()).isEqualTo(i); group.destroy(); } } @Test public void testEquality() { ObservableGroup originalGroup = observableManager.newGroup(); ObservableGroup group1 = observableManager.getGroup(originalGroup.id()); ObservableGroup group2 = observableManager.getGroup(originalGroup.id()); assertThat(group1).isEqualTo(group2); } @Test public void testDifferentGroups() { ObservableGroup group1 = observableManager.getGroup(observableManager.newGroup().id()); ObservableGroup group2 = observableManager.getGroup(observableManager.newGroup().id()); assertThat(group1).isNotEqualTo(group2); } @Test public void testGetGroupThrowsAfterDestroyed() { ObservableGroup group = observableManager.newGroup(); observableManager.destroy(group); try { observableManager.getGroup(group.id()); fail(); } catch (IllegalArgumentException ignored) { } } }
6,110
0
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb/rxgroups/ObservableGroupTest.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.concurrent.Callable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Function; import io.reactivex.observers.TestObserver; import io.reactivex.plugins.RxJavaPlugins; import io.reactivex.schedulers.Schedulers; import io.reactivex.subjects.PublishSubject; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class ObservableGroupTest { private final ObservableManager observableManager = new ObservableManager(); private final TestAutoResubscribingObserver fooObserver = new TestAutoResubscribingObserver("foo"); private final TestAutoResubscribingObserver barObserver = new TestAutoResubscribingObserver("bar"); @Before public void setUp() throws IOException { RxJavaPlugins.setInitIoSchedulerHandler(new Function<Callable<Scheduler>, Scheduler>() { @Override public Scheduler apply(@NonNull Callable<Scheduler> schedulerCallable) throws Exception { return Schedulers.trampoline(); } }); } @Test public void shouldNotHaveObservable() { ObservableGroup group = observableManager.newGroup(); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldAddRequestByObserverTag() { ObservableGroup group = observableManager.newGroup(); ObservableGroup group2 = observableManager.newGroup(); Observable<String> sourceObservable = Observable.never(); sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver); assertThat(group.hasObservables(fooObserver)).isEqualTo(true); assertThat(group2.hasObservables(fooObserver)).isEqualTo(false); assertThat(group.hasObservables(barObserver)).isEqualTo(false); } @Test public void shouldNotBeCompleted() { ObservableGroup group = observableManager.newGroup(); TestObserver<Object> subscriber = new TestObserver<>(); Observable<String> sourceObservable = Observable.never(); sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver); subscriber.assertNotComplete(); } @Test public void shouldBeSubscribed() { ObservableGroup group = observableManager.newGroup(); Observable<String> sourceObservable = Observable.never(); sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver); assertThat(group.subscription(fooObserver).isCancelled()).isEqualTo(false); } @Test public void shouldDeliverSuccessfulEvent() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestObserver<String> subscriber = new TestObserver<>(); sourceObservable.compose(group.transform(subscriber)).subscribe(subscriber); subscriber.assertNotComplete(); sourceObservable.onNext("Foo Bar"); sourceObservable.onComplete(); subscriber.assertComplete(); subscriber.assertValue("Foo Bar"); } @Test public void shouldDeliverError() throws Exception { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); Observable<String> sourceObservable = Observable.error(new RuntimeException("boom")); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); testObserver.assertError(RuntimeException.class); } @Test public void shouldSeparateObservablesByGroupId() { ObservableGroup group = observableManager.newGroup(); ObservableGroup group2 = observableManager.newGroup(); Observable<String> observable1 = Observable.never(); Observable<String> observable2 = Observable.never(); observable1.compose(group.transform(barObserver)).subscribe(barObserver); assertThat(group.hasObservables(barObserver)).isEqualTo(true); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); assertThat(group2.hasObservables(barObserver)).isEqualTo(false); assertThat(group2.hasObservables(fooObserver)).isEqualTo(false); observable2.compose(group2.transform(fooObserver)).subscribe(fooObserver); assertThat(group.hasObservables(barObserver)).isEqualTo(true); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); assertThat(group2.hasObservables(barObserver)).isEqualTo(false); assertThat(group2.hasObservables(fooObserver)).isEqualTo(true); } @Test public void shouldClearObservablesByGroupId() { ObservableGroup group = observableManager.newGroup(); ObservableGroup group2 = observableManager.newGroup(); Observable<String> observable1 = Observable.never(); Observable<String> observable2 = Observable.never(); observable1.compose(group.transform(fooObserver)).subscribe(fooObserver); observable2.compose(group2.transform(fooObserver)).subscribe(fooObserver); observableManager.destroy(group); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); assertThat(group2.hasObservables(fooObserver)).isEqualTo(true); assertThat(group.subscription(fooObserver)).isNull(); assertThat(group2.subscription(fooObserver).isCancelled()).isEqualTo(false); observableManager.destroy(group2); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); assertThat(group2.hasObservables(fooObserver)).isEqualTo(false); assertThat(group.subscription(fooObserver)).isNull(); assertThat(group2.subscription(fooObserver)).isNull(); } @Test public void shouldClearObservablesWhenLocked() { ObservableGroup group = observableManager.newGroup(); Observable<String> observable1 = Observable.never(); Observable<String> observable2 = Observable.never(); TestObserver<String> subscriber1 = new TestObserver<>(); TestObserver<String> subscriber2 = new TestObserver<>(); observable1.compose(group.transform(subscriber1)).subscribe(subscriber1); observable2.compose(group.transform(subscriber2)).subscribe(subscriber2); group.dispose(); observableManager.destroy(group); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); assertThat(group.hasObservables(barObserver)).isEqualTo(false); } @Test public void shouldClearQueuedResults() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestObserver<String> subscriber1 = new TestObserver<>(); sourceObservable.compose(group.transform(subscriber1)).subscribe(subscriber1); group.dispose(); sourceObservable.onNext("Hello"); sourceObservable.onComplete(); observableManager.destroy(group); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldRemoveObservablesAfterTermination() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestObserver<String> subscriber = new TestObserver<>(); sourceObservable.compose(group.transform(subscriber)).subscribe(subscriber); sourceObservable.onNext("Roberto Gomez Bolanos is king"); sourceObservable.onComplete(); subscriber.assertComplete(); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldRemoveResponseAfterErrorDelivery() throws InterruptedException { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); sourceObservable.onError(new RuntimeException("BOOM!")); testObserver.assertError(Exception.class); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldNotDeliverResultWhileUnsubscribed() throws Exception { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); group.dispose(); sourceObservable.onNext("Roberto Gomez Bolanos"); sourceObservable.onComplete(); testObserver.assertNotComplete(); assertThat(group.hasObservables(testObserver)).isEqualTo(true); } @Test public void shouldDeliverQueuedEventsWhenResubscribed() throws Exception { ObservableGroup group = observableManager.newGroup(); TestAutoResubscribingObserver resubscribingObserver = new TestAutoResubscribingObserver("foo"); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(resubscribingObserver)) .subscribe(resubscribingObserver); group.dispose(); sourceObservable.onNext("Hello World"); sourceObservable.onComplete(); resubscribingObserver.assertionTarget.assertNotComplete(); resubscribingObserver.assertionTarget.assertNoValues(); // TestObserver cannot be reused after being disposed in RxJava2 resubscribingObserver = new TestAutoResubscribingObserver("foo"); group.observable(resubscribingObserver).subscribe(resubscribingObserver); resubscribingObserver.assertionTarget.assertComplete(); resubscribingObserver.assertionTarget.assertValue("Hello World"); assertThat(group.hasObservables(resubscribingObserver)).isEqualTo(false); } @Test public void shouldDeliverQueuedErrorWhenResubscribed() throws Exception { ObservableGroup group = observableManager.newGroup(); TestAutoResubscribingObserver resubscribingObserver = new TestAutoResubscribingObserver("foo"); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(resubscribingObserver)) .subscribe(resubscribingObserver); group.dispose(); sourceObservable.onError(new Exception("Exploded")); resubscribingObserver.assertionTarget.assertNotComplete(); resubscribingObserver.assertionTarget.assertNoValues(); resubscribingObserver = new TestAutoResubscribingObserver("foo"); group.observable(resubscribingObserver).subscribe(resubscribingObserver); resubscribingObserver.assertionTarget.assertError(Exception.class); assertThat(group.hasObservables(resubscribingObserver)).isEqualTo(false); } @Test public void shouldNotDeliverEventsWhenResubscribedIfLocked() { ObservableGroup group = observableManager.newGroup(); TestAutoResubscribingObserver testObserver = new TestAutoResubscribingObserver("foo"); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); group.dispose(); sourceObservable.onNext("Hello World"); sourceObservable.onComplete(); group.lock(); testObserver = new TestAutoResubscribingObserver("foo"); group.observable(testObserver).subscribe(testObserver); testObserver.assertionTarget.assertNotComplete(); testObserver.assertionTarget.assertNoValues(); group.unlock(); testObserver.assertionTarget.assertComplete(); testObserver.assertionTarget.assertNoErrors(); testObserver.assertionTarget.assertValue("Hello World"); assertThat(group.hasObservables(testObserver)).isEqualTo(false); } @Test public void shouldUnsubscribeByContext() throws Exception { ObservableGroup group = observableManager.newGroup(); ObservableGroup group2 = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestObserver<String> testObserver = new TestObserver<>(); sourceObservable.compose(group2.transform(testObserver)).subscribe(testObserver); group.dispose(); sourceObservable.onNext("Gremio Foot-ball Porto Alegrense"); sourceObservable.onComplete(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue("Gremio Foot-ball Porto Alegrense"); assertThat(group2.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldNotDeliverEventsAfterCancelled() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestObserver<String> testObserver = new TestObserver<>(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); observableManager.destroy(group); sourceObservable.onNext("Gremio Foot-ball Porto Alegrense"); sourceObservable.onComplete(); testObserver.assertNotComplete(); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldNotRemoveSubscribersForOtherIds() throws Exception { ObservableGroup group = observableManager.newGroup(); ObservableGroup group2 = observableManager.newGroup(); PublishSubject<String> subject1 = PublishSubject.create(); TestAutoResubscribingObserver testSubscriber1 = new TestAutoResubscribingObserver("foo"); PublishSubject<String> subject2 = PublishSubject.create(); TestAutoResubscribingObserver testSubscriber2 = new TestAutoResubscribingObserver("bar"); subject1.compose(group.transform(testSubscriber1)).subscribe(testSubscriber1); subject2.compose(group2.transform(testSubscriber2)).subscribe(testSubscriber2); group.dispose(); subject1.onNext("Florinda Mesa"); subject1.onComplete(); subject2.onNext("Carlos Villagran"); subject2.onComplete(); testSubscriber1.assertionTarget.assertNotComplete(); testSubscriber2.assertionTarget.assertNoErrors(); testSubscriber2.assertionTarget.assertValue("Carlos Villagran"); } @Test public void shouldOverrideExistingSubscriber() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); TestAutoResubscribingObserver testSubscriber1 = new TestAutoResubscribingObserver("foo"); TestAutoResubscribingObserver testSubscriber2 = new TestAutoResubscribingObserver("foo"); sourceObservable.compose(group.transform(testSubscriber1)).subscribe(testSubscriber1); sourceObservable.compose(group.transform(testSubscriber2)).subscribe(testSubscriber2); sourceObservable.onNext("Ruben Aguirre"); sourceObservable.onComplete(); testSubscriber1.assertionTarget.assertNotComplete(); testSubscriber1.assertionTarget.assertNoValues(); testSubscriber2.assertionTarget.assertComplete(); testSubscriber2.assertionTarget.assertValue("Ruben Aguirre"); } @Test public void shouldQueueMultipleRequests() throws Exception { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> subject1 = PublishSubject.create(); TestObserver<String> testSubscriber1 = new TestObserver<>(); PublishSubject<String> subject2 = PublishSubject.create(); TestObserver<String> testSubscriber2 = new TestObserver<>(); subject1.compose(group.transform(testSubscriber1)).subscribe(testSubscriber1); subject2.compose(group.transform(testSubscriber2)).subscribe(testSubscriber2); group.dispose(); subject1.onNext("Chespirito"); subject1.onComplete(); subject2.onNext("Edgar Vivar"); subject2.onComplete(); testSubscriber1.assertNotComplete(); testSubscriber2.assertNotComplete(); assertThat(group.hasObservables(testSubscriber1)).isEqualTo(true); assertThat(group.hasObservables(testSubscriber2)).isEqualTo(true); } @Test public void shouldNotDeliverResultWhileLocked() throws Exception { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); group.lock(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); sourceObservable.onNext("Chespirito"); sourceObservable.onComplete(); testObserver.assertNotComplete(); testObserver.assertNoValues(); assertThat(group.hasObservables(testObserver)).isEqualTo(true); } @Test public void shouldAutoResubscribeAfterUnlock() throws InterruptedException { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); group.lock(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); sourceObservable.onNext("Chespirito"); sourceObservable.onComplete(); group.unlock(); testObserver.assertComplete(); testObserver.assertNoErrors(); testObserver.assertValue("Chespirito"); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void shouldAutoResubscribeAfterLockAndUnlock() { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); group.lock(); sourceObservable.onNext("Chespirito"); sourceObservable.onComplete(); group.unlock(); testObserver.assertTerminated(); testObserver.assertNoErrors(); testObserver.assertValue("Chespirito"); assertThat(group.hasObservables(fooObserver)).isEqualTo(false); } @Test public void testUnsubscribeWhenLocked() { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); group.lock(); group.dispose(); sourceObservable.onNext("Chespirito"); sourceObservable.onComplete(); group.unlock(); testObserver.assertNotComplete(); testObserver.assertNoValues(); assertThat(group.hasObservables(testObserver)).isEqualTo(true); } @Test public void testAddThrowsAfterDestroyed() { ObservableGroup group = observableManager.newGroup(); Observable<String> source = PublishSubject.create(); TestObserver<String> observer = new TestObserver<>(); group.destroy(); source.compose(group.transform(observer)).subscribe(observer); observer.assertError(IllegalStateException.class); } @Test public void testResubscribeThrowsAfterDestroyed() { ObservableGroup group = observableManager.newGroup(); Observable<String> source = PublishSubject.create(); TestObserver<String> observer = new TestObserver<>(); try { source.compose(group.transform(observer)).subscribe(observer); group.dispose(); group.destroy(); group.observable(fooObserver).subscribe(new TestObserver<>()); fail(); } catch (IllegalStateException ignored) { } } @Test public void shouldReplaceObservablesOfSameTagAndSameGroupId() { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> observable1 = PublishSubject.create(); PublishSubject<String> observable2 = PublishSubject.create(); TestAutoResubscribingObserver observer1 = new TestAutoResubscribingObserver("foo"); TestAutoResubscribingObserver observer2 = new TestAutoResubscribingObserver("foo"); observable1.compose(group.transform(observer1)).subscribe(observer1); observable2.compose(group.transform(observer2)).subscribe(observer2); assertThat(group.subscription(fooObserver).isCancelled()).isFalse(); assertThat(group.hasObservables(fooObserver)).isTrue(); observable1.onNext("Hello World 1"); observable1.onComplete(); observable2.onNext("Hello World 2"); observable2.onComplete(); observer2.assertionTarget.awaitTerminalEvent(); observer2.assertionTarget.assertComplete(); observer2.assertionTarget.assertValue("Hello World 2"); observer1.assertionTarget.assertNoValues(); } /** * The same observable tag can be used so long as it is associated with a different observer tag. */ @Test public void shouldNotReplaceObservableOfSameTagAndSameGroupIdAndDifferentObservers() { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> observable1 = PublishSubject.create(); TestObserver<String> observer1 = new TestObserver<>(); TestObserver<String> observer2 = new TestObserver<>(); String sharedObservableTag = "sharedTag"; observable1.compose(group.transform(observer1, sharedObservableTag)).subscribe(observer1); observable1.compose(group.transform(observer2, sharedObservableTag)).subscribe(observer2); assertThat(group.subscription(observer1, sharedObservableTag).isCancelled()).isFalse(); assertThat(group.hasObservables(observer1)).isTrue(); assertThat(group.subscription(observer2, sharedObservableTag).isCancelled()).isFalse(); assertThat(group.hasObservables(observer2)).isTrue(); observable1.onNext("Hello World 1"); observable1.onComplete(); observer2.assertComplete(); observer2.assertValue("Hello World 1"); observer1.assertComplete(); observer1.assertValue("Hello World 1"); } @Test public void testCancelAndReAddSubscription() { ObservableGroup group = observableManager.newGroup(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver); group.cancelAllObservablesForObserver(fooObserver); assertThat(group.subscription(fooObserver)).isNull(); sourceObservable.compose(group.transform(fooObserver)).subscribe(fooObserver); assertThat(group.subscription(fooObserver).isCancelled()).isFalse(); } @Test public void testDisposingObserver() { ObservableGroup group = observableManager.newGroup(); TestObserver<String> testObserver = new TestObserver<>(); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); testObserver.dispose(); sourceObservable.onNext("Chespirito"); testObserver.assertNoValues(); assertThat(group.hasObservables(testObserver)).isEqualTo(true); } @Test public void testDisposingObserverResubscribe() { ObservableGroup group = observableManager.newGroup(); TestAutoResubscribingObserver testObserver = new TestAutoResubscribingObserver("foo"); PublishSubject<String> sourceObservable = PublishSubject.create(); sourceObservable.compose(group.transform(testObserver)).subscribe(testObserver); testObserver.dispose(); sourceObservable.onNext("Chespirito"); testObserver.assertionTarget.assertNoValues(); testObserver = new TestAutoResubscribingObserver("foo"); group.resubscribe(testObserver); testObserver.assertionTarget.assertValue("Chespirito"); } }
6,111
0
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb/rxgroups/NonResubscribableTagTest.java
package com.airbnb.rxgroups; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class NonResubscribableTagTest { @Test public void testMatch() { Object test = new Object(); final String tag = NonResubscribableTag.create(test); assertThat(NonResubscribableTag.isNonResubscribableTag(tag)).isTrue(); } @Test public void testMatchInnerclass() { InnerClass test = new InnerClass(); final String tag = NonResubscribableTag.create(test); assertThat(NonResubscribableTag.isNonResubscribableTag(tag)).isTrue(); } @Test public void testNoMatch() { String tag = "stableTag"; assertThat(NonResubscribableTag.isNonResubscribableTag(tag)).isFalse(); } class InnerClass { } }
6,112
0
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/test/java/com/airbnb/rxgroups/ResubscribeHelperTest.java
package com.airbnb.rxgroups; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class ResubscribeHelperTest { static class BaseClass { boolean baseInitialized; } static class MiddleClass extends BaseClass { boolean middleInitialized; } private static class LeafClass extends MiddleClass { boolean leafInitialized; } @Test public void leafClassInitDoesIntializeEntireHierarchy() { LeafClass leafClass = new LeafClass(); ResubscribeHelper.initializeAutoTaggingAndResubscription(leafClass, new ObservableGroup(1)); assertThat(leafClass.baseInitialized).isTrue(); assertThat(leafClass.middleInitialized).isTrue(); assertThat(leafClass.leafInitialized).isTrue(); } @Test public void leafClassOnlyInitDoesNotInitializeEntireHierarchy() { LeafClass leafClass = new LeafClass(); ResubscribeHelper.initializeAutoTaggingAndResubscriptionInTargetClassOnly(leafClass, LeafClass.class, new ObservableGroup(1)); assertThat(leafClass.baseInitialized).isFalse(); assertThat(leafClass.middleInitialized).isFalse(); assertThat(leafClass.leafInitialized).isTrue(); } //CHECKSTYLE:OFF @SuppressWarnings("unused") public static class BaseClass_ObservableResubscriber { boolean initialized = false; public BaseClass_ObservableResubscriber(BaseClass target, ObservableGroup group) { target.baseInitialized = true; } } @SuppressWarnings("unused") public static class MiddleClass_ObservableResubscriber { boolean initialized = false; public MiddleClass_ObservableResubscriber(MiddleClass target, ObservableGroup group) { target.middleInitialized = true; } } @SuppressWarnings("unused") public static class LeafClass_ObservableResubscriber { boolean initialized = false; public LeafClass_ObservableResubscriber(LeafClass target, ObservableGroup group) { target.leafInitialized = true; } } //CHECKSTYLE:ON }
6,113
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/Preconditions.java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.airbnb.rxgroups; import javax.annotation.Nullable; /** * Static convenience methods that help a method or constructor check whether it was invoked * correctly (whether its <i>preconditions</i> have been met). These methods generally accept a * {@code boolean} expression which is expected to be {@code true} (or in the case of {@code * checkNotNull}, an object reference which is expected to be non-null). When {@code false} (or * {@code null}) is passed instead, the {@code Preconditions} method throws an unchecked exception, * which helps the calling method communicate to <i>its</i> caller that <i>that</i> caller has made * a mistake. Example: <pre> {@code * * /** * * Returns the positive square root of the given value. * * * * @throws IllegalArgumentException if the value is negative * *}{@code / * public static double sqrt(double value) { * Preconditions.checkArgument(value >= 0.0, "negative value: %s", value); * // calculate the square root * } * * void exampleBadCaller() { * double d = sqrt(-1.0); * }}</pre> * * In this example, {@code checkArgument} throws an {@code IllegalArgumentException} to indicate * that {@code exampleBadCaller} made an error in <i>its</i> call to {@code sqrt}. * * <h3>Warning about performance</h3> * * <p>The goal of this class is to improve readability of code, but in some circumstances this may * come at a significant performance cost. Remember that parameter values for message construction * must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even * when the precondition check then succeeds (as it should almost always do in production). In some * circumstances these wasted CPU cycles and allocations can add up to a real problem. * Performance-sensitive precondition checks can always be converted to the customary form: * <pre> {@code * * if (value < 0.0) { * throw new IllegalArgumentException("negative value: " + value); * }}</pre> * * <h3>Other types of preconditions</h3> * * <p>Not every type of precondition failure is supported by these methods. Continue to throw * standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link * UnsupportedOperationException} in the situations they are intended for. * * <h3>Non-preconditions</h3> * * <p>It is of course possible to use the methods of this class to check for invalid conditions * which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is * misleading to future readers of the code and of stack traces. See * <a href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional * failures explained</a> in the Guava User Guide for more advice. * * <h3>{@code java.util.Objects.requireNonNull()}</h3> * * <p>Projects which use {@code com.google.common} should generally avoid the use of {@link * java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link * #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation. * (The same goes for the message-accepting overloads.) * * <h3>Only {@code %s} is supported</h3> * * <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is * supported, not the full range of {@link java.util.Formatter} specifiers. * * <h3>More information</h3> * * <p>See the Guava User Guide on * <a href="https://github.com/google/guava/wiki/PreconditionsExplained">using {@code * Preconditions}</a>. * * @author Kevin Bourrillion * @since 2.0 */ public final class Preconditions { private Preconditions() { } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkArgument( boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkState( boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull( T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } return reference; } /* * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { * throw new BadException(messageExpression); * } * * refactored so that messageExpression is moved to a separate String-returning method. * * if (guardExpression) { * throw new BadException(badMsg(...)); * } * * The alternative natural refactorings into void or Exception-returning methods are much slower. * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This * is a hotspot optimizer bug, which should be fixed, but that's a separate, big project). * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a * RangeCheckMicroBenchmark in the JDK that was used to test this. * * But the methods in this class want to throw different exceptions, depending on the args, so it * appears that this pattern is not directly applicable. But we can use the ridiculous, devious * trick of throwing an exception in the middle of the construction of another exception. Hotspot * is fine with that. */ /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); } return index; } private static String badElementIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index >= size return format("%s (%s) must be less than size (%s)", desc, index, size); } } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return format("%s (%s) must not be greater than size (%s)", desc, index, size); } } /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * * @param start a user-supplied index identifying a starting position in an array, list or string * @param end a user-supplied index identifying a ending position in an array, list or string * @param size the size of that array, list or string * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size}, * or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) if (start < 0 || end < start || end > size) { throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); } } private static String badPositionIndexes(int start, int end, int size) { if (start < 0 || start > size) { return badPositionIndex(start, size, "start index"); } if (end < 0 || end > size) { return badPositionIndex(end, size, "end index"); } // end < start return format("end index (%s) must not be less than start index (%s)", end, start); } /** * Substitutes each {@code %s} in {@code template} with an argument. These are matched by * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than * placeholders, the unmatched arguments will be appended to the end of the formatted message in * square braces. * * @param template a non-null string containing 0 or more {@code %s} placeholders. * @param args the arguments to be substituted into the message template. Arguments are converted * to strings using {@link String#valueOf(Object)}. Arguments can be null. */ // Note that this is somewhat-improperly used from Verify.java as well. static String format(String template, @Nullable Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } }
6,114
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/GroupSubscriptionTransformer.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.ObservableSource; import io.reactivex.ObservableTransformer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; /** * Transforms an existing {@link Observable} by returning a new {@link Observable} that is * automatically added to the provided {@link ObservableGroup} with the specified {@code * observableTag} when subscribed to. */ class GroupSubscriptionTransformer<T> implements ObservableTransformer<T, T> { private final ObservableGroup group; private final String observableTag; private final String observerTag; GroupSubscriptionTransformer(ObservableGroup group, String observerTag, String observableTag) { this.group = group; this.observableTag = observableTag; this.observerTag = observerTag; } @Override public ObservableSource<T> apply(@NonNull final Observable<T> sourceObservable) { return Observable.create(new ObservableOnSubscribe<T>() { @Override public void subscribe(@NonNull final ObservableEmitter<T> emitter) throws Exception { group.add(observerTag, observableTag, sourceObservable, emitter); emitter.setDisposable(managedObservableDisposable); } }); } private Disposable managedObservableDisposable = new Disposable() { @Override public void dispose() { ManagedObservable managedObservable = group.getObservablesForObserver(observerTag).get(observableTag); if (managedObservable != null) { managedObservable.dispose(); } } @Override public boolean isDisposed() { ManagedObservable managedObservable = group.getObservablesForObserver(observerTag).get(observableTag); return managedObservable == null || managedObservable.isDisposed(); } }; }
6,115
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/SubscriptionProxy.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.Observer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.internal.functions.Functions; import io.reactivex.observables.ConnectableObservable; import io.reactivex.observers.DisposableObserver; /** * This class is a middle man between an {@link Observable} and an {@link ObservableEmitter} or * {@link DisposableObserver}. The class allows the emitter to unsubscribe and resubscribe from the * source observable without terminating source observable. This works like a lock/unlock events * mechanism. This is useful for expensive operations, such as network requests, which should not be * cancelled even if a given Observer should be unsubscribed. * Cancellation is usually more suited for lifecycle events like Activity.onDestroy() */ final class SubscriptionProxy<T> { private final Observable<T> proxy; private final Disposable sourceDisposable; private final CompositeDisposable disposableList; private Disposable disposable; private SubscriptionProxy(Observable<T> sourceObservable, Action onTerminate) { final ConnectableObservable<T> replay = sourceObservable.replay(); sourceDisposable = replay.connect(); proxy = replay.doOnTerminate(onTerminate); disposableList = new CompositeDisposable(sourceDisposable); } static <T> SubscriptionProxy<T> create(Observable<T> observable, Action onTerminate) { return new SubscriptionProxy<>(observable, onTerminate); } static <T> SubscriptionProxy<T> create(Observable<T> observable) { return create(observable, Functions.EMPTY_ACTION); } @SuppressWarnings("unused") Disposable subscribe(Observer<? super T> observer) { dispose(); disposable = proxy.subscribeWith(disposableWrapper(observer)); disposableList.add(disposable); return disposable; } Disposable subscribe(ObservableEmitter<? super T> emitter) { dispose(); disposable = proxy.subscribeWith(disposableWrapper(emitter)); disposableList.add(disposable); return disposable; } void cancel() { disposableList.dispose(); } void dispose() { if (disposable != null) { disposableList.remove(disposable); } } boolean isDisposed() { return disposable != null && disposable.isDisposed(); } boolean isCancelled() { return isDisposed() && sourceDisposable.isDisposed(); } Observable<T> observable() { return proxy; } DisposableObserver<? super T> disposableWrapper(final ObservableEmitter<? super T> emitter) { return new DisposableObserver<T>() { @Override public void onNext(@NonNull T t) { if (!emitter.isDisposed()) { emitter.onNext(t); } } @Override public void onError(@NonNull Throwable e) { if (!emitter.isDisposed()) { emitter.onError(e); } } @Override public void onComplete() { if (!emitter.isDisposed()) { emitter.onComplete(); } } }; } DisposableObserver<? super T> disposableWrapper(final Observer<? super T> observer) { return new DisposableObserver<T>() { @Override public void onNext(@NonNull T t) { observer.onNext(t); } @Override public void onError(@NonNull Throwable e) { observer.onError(e); } @Override public void onComplete() { observer.onComplete(); } }; } }
6,116
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/TestAutoResubscribingObserver.java
package com.airbnb.rxgroups; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.observers.TestObserver; class TestAutoResubscribingObserver extends AutoResubscribingObserver<String> implements Disposable { public final TestObserver<String> assertionTarget; TestAutoResubscribingObserver(String tag) { this.setTag(tag); assertionTarget = new TestObserver<>(); } @Override public void onSubscribe(@NonNull Disposable d) { assertionTarget.onSubscribe(d); } @Override public void onComplete() { super.onComplete(); assertionTarget.onComplete(); } @Override public void onError(Throwable e) { super.onError(e); assertionTarget.onError(e); } @Override public void onNext(String s) { super.onNext(s); assertionTarget.onNext(s); } @Override public void dispose() { assertionTarget.dispose(); } @Override public boolean isDisposed() { return assertionTarget.isDisposed(); } }
6,117
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/AutoResubscribingObserver.java
package com.airbnb.rxgroups; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; /** * A {@link io.reactivex.Observer} which has a stable tag. Must be used with {@link AutoResubscribe} * annotation to set the tag before observer is used. */ public abstract class AutoResubscribingObserver<T> implements TaggedObserver<T> { private String tag; public final String getTag() { return tag; } void setTag(String tag) { this.tag = tag; } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(T t) { } @Override public void onSubscribe(@NonNull Disposable d) { } }
6,118
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/AutoTaggableObserver.java
package com.airbnb.rxgroups; import io.reactivex.Observer; /** * {@link Observer} with a unique tag which can be automatically set during * {@link ObservableGroup#initializeAutoTaggingAndResubscription(Object)} * when used with {@link AutoResubscribe} or {@link AutoTag}. */ public interface AutoTaggableObserver<T> extends TaggedObserver<T> { void setTag(String tag); }
6,119
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/AutoResubscribe.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Used on {@link io.reactivex.Observer} fields to indicate that they should be automatically * subscribed to a certain Observable, or multiple Observables if they still haven't completed yet. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface AutoResubscribe { /** * @return A custom tag to use instead of auto-generated tag. * This tag should be unique within the RxGroup. */ String customTag() default ""; }
6,120
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/AutoTag.java
package com.airbnb.rxgroups; /** * Used on {@link AutoTaggableObserver} fields to indicate that a unique tag should automatically be * injected into the Observer. Unlike {@link AutoResubscribe} this annotation does <i>not</i> * signify that the Observer should be resubscribed upon initialization. */ public @interface AutoTag { /** * @return A custom tag to use instead of auto-generated tag. * This tag should be unique within the RxGroup. */ String customTag() default ""; }
6,121
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/ResubscribeHelper.java
package com.airbnb.rxgroups; import com.airbnb.rxgroups.processor.ProcessorHelper; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.Nullable; class ResubscribeHelper { private static final Map<Class<?>, Constructor<?>> BINDINGS = new LinkedHashMap<>(); /** * Initializes all helper classes in {@code target} class hierarchy. */ static void initializeAutoTaggingAndResubscription(Object target, ObservableGroup group) { Class<?> cls = target.getClass(); String clsName = cls.getName(); while (cls != null && !clsName.startsWith("android.") && !clsName.startsWith("java.")) { initializeAutoTaggingAndResubscriptionInTargetClassOnly(target, cls, group); cls = cls.getSuperclass(); if (cls != null) { clsName = cls.getName(); } } } static void initializeAutoTaggingAndResubscriptionInTargetClassOnly(Object target, Class<?> targetClass, ObservableGroup group) { Constructor<?> constructor = findConstructorForClass(targetClass); if (constructor == null) { return; } invokeConstructor(constructor, target, group); } private static void invokeConstructor(Constructor<?> constructor, Object target, ObservableGroup group) { try { constructor.newInstance(target, group); } catch (IllegalAccessException e) { throw new RuntimeException("Unable to invoke " + constructor, e); } catch (InstantiationException e) { throw new RuntimeException("Unable to invoke " + constructor, e); } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } if (cause instanceof Error) { throw (Error) cause; } throw new RuntimeException("Unable to create resubscribeAll instance.", cause); } } @Nullable private static Constructor<?> findConstructorForClass(Class<?> cls) { Constructor<?> bindingCtor = BINDINGS.get(cls); if (bindingCtor != null || BINDINGS.containsKey(cls)) { return bindingCtor; } String clsName = cls.getName(); if (clsName.startsWith("android.") || clsName.startsWith("java.")) { BINDINGS.put(cls, bindingCtor); return null; } try { Class<?> bindingClass = Class.forName(clsName + ProcessorHelper.GENERATED_CLASS_NAME_SUFFIX); //noinspection unchecked bindingCtor = bindingClass.getConstructor(cls, ObservableGroup.class); } catch (ClassNotFoundException e) { bindingCtor = findConstructorForClass(cls.getSuperclass()); } catch (NoSuchMethodException e) { throw new RuntimeException("Unable to find binding constructor for " + clsName, e); } BINDINGS.put(cls, bindingCtor); return bindingCtor; } }
6,122
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/GroupResubscriptionTransformer.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableOnSubscribe; import io.reactivex.ObservableSource; import io.reactivex.ObservableTransformer; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; class GroupResubscriptionTransformer<T> implements ObservableTransformer<T, T> { private final ManagedObservable<T> managedObservable; GroupResubscriptionTransformer(ManagedObservable<T> managedObservable) { this.managedObservable = managedObservable; } @Override public ObservableSource<T> apply(@NonNull final Observable<T> ignored) { return Observable.create(new ObservableOnSubscribe<T>() { @Override public void subscribe(@NonNull final ObservableEmitter<T> emitter) throws Exception { emitter.setDisposable(new Disposable() { @Override public void dispose() { managedObservable.dispose(); } @Override public boolean isDisposed() { return managedObservable.isDisposed(); } }); managedObservable.resubscribe(emitter); } }); } }
6,123
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/Utils.java
package com.airbnb.rxgroups; import io.reactivex.Observer; final class Utils { static String getObserverTag(Observer<?> observer) { if (observer instanceof TaggedObserver) { String definedTag = ((TaggedObserver) observer).getTag(); if (definedTag != null) { return definedTag; } } return NonResubscribableTag.create(observer); } }
6,124
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/BaseObservableResubscriber.java
package com.airbnb.rxgroups; public class BaseObservableResubscriber { protected void setTag(AutoResubscribingObserver target, String tag) { target.setTag(tag); } protected void setTag(AutoTaggableObserver target, String tag) { target.setTag(tag); } }
6,125
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/TaggedObserver.java
package com.airbnb.rxgroups; import io.reactivex.Observer; /** * An {@link Observer} which as a string "tag" which * uniquely identifies this Observer. */ public interface TaggedObserver<T> extends Observer<T> { /** * @return A string which uniquely identifies this Observer. In order to use * {@link ObservableGroup#resubscribe(TaggedObserver, String)} the tag must be * stable across lifecycles of the observer. */ String getTag(); }
6,126
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/ObservableManager.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import io.reactivex.Observable; /** * Easily keep reference to {@link Observable}s across lifecycle changes. Observables are grouped by * a unique group id, which allows you to manage and reclaim subscriptions made with the same id. * Subscribe to observables, and then lock or unlock their observers to control when you get the * event back. Events will be held in a queue until an Observer is added and the group is unlocked. */ @SuppressWarnings("WeakerAccess") public class ObservableManager { /** Map ids to a group of observables. */ private final Map<Long, ObservableGroup> observableGroupMap = new ConcurrentHashMap<>(); private final AtomicLong nextId = new AtomicLong(1); private final UUID uuid = UUID.randomUUID(); /** * @return an existing group provided groupId. Throws {@link IllegalStateException} if no group * with the provided groupId exists or it is already destroyed. */ public ObservableGroup getGroup(long groupId) { ObservableGroup observableGroup = observableGroupMap.get(groupId); if (observableGroup == null) { throw new IllegalArgumentException("Group not found with groupId=" + groupId); } if (observableGroup.isDestroyed()) { throw new IllegalArgumentException("Group is already destroyed with groupId=" + groupId); } return observableGroup; } /** @return a new {@link ObservableGroup} with a unique groupId */ public ObservableGroup newGroup() { long id = nextId.getAndIncrement(); ObservableGroup observableGroup = new ObservableGroup(id); observableGroupMap.put(id, observableGroup); return observableGroup; } UUID id() { return uuid; } /** * Clears the provided group. References will be released, and no future results will be returned. * Once a group is destroyed it is an error to use it again. */ public void destroy(ObservableGroup group) { group.destroy(); observableGroupMap.remove(group.id()); } }
6,127
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/ObservableGroup.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.ObservableTransformer; import io.reactivex.Observer; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; /** * A helper class for {@link ObservableManager} that groups {@link Observable}s to be managed * together. For example, a fragment will probably want to group all of its requests together so it * can lock/unlock/clear them all at once according to its lifecycle. <p> Requests are added to a * {@link ObservableGroup} with an observer, and that observer will be called when a response is * ready. If the {@link ObservableGroup} is locked when the response arrives, or if the observer was * removed, the response will be queued and delivered when the {@link ObservableGroup} is unlocked * and a observer is added. <p> Each {@link Observer} can only be subscribed to * the same proxiedObservable tag once. If a {@link Observer} is already subscribed to * the given tag, the original subscription will be cancelled and discarded. */ @SuppressWarnings("WeakerAccess") public class ObservableGroup { private final Map<String, Map<String, ManagedObservable<?>>> groupMap = new ConcurrentHashMap<>(); private final long groupId; private boolean locked; private boolean destroyed; ObservableGroup(long groupId) { this.groupId = groupId; } public long id() { return groupId; } /** * Sets a unique tag on all Observer fields of {@code target} * that are annotated with {@link AutoTag} or {@link AutoResubscribe}. * All fields declared in superclasses of {@code target} will also be set. * <p> * Subscribe all Observer fields on the {@code target} and in superclasses * that are annotated with {@link AutoResubscribe} * and that have their corresponding Observable in flight. * <p> * Resubscribes all Observer fields on the target that are annotated with * {@link AutoResubscribe} and that have their corresponding Observable in flight. */ public void initializeAutoTaggingAndResubscription(final Object target) { Preconditions.checkNotNull(target, "Target cannot be null"); ResubscribeHelper.initializeAutoTaggingAndResubscription(target, this); } /** * Unlike {@link #initializeAutoTaggingAndResubscription(Object)} superclasses will * <b>not</b> be initialized; only the fields in {@code targetClass} will be initialized. * <p> * Sets a unique tag on all Observer fields of {@code target} * that are annotated with {@link AutoTag} or {@link AutoResubscribe}. * <p> * Subscribe all Observer fields on the {@code target} * that are annotated with {@link AutoResubscribe} * and that have their corresponding Observable in flight. * <p> * Resubscribes all Observer fields on the target that are annotated with * {@link AutoResubscribe} and that have their corresponding Observable in flight. * <p> */ public <T> void initializeAutoTaggingAndResubscriptionInTargetClassOnly(T target, Class<T> targetClass) { Preconditions.checkNotNull(target, "Target cannot be null"); ResubscribeHelper.initializeAutoTaggingAndResubscriptionInTargetClassOnly(target, targetClass, this); } /** * Adds an {@link Observable} and {@link Observer} to this group and subscribes to it. If an * {@link Observable} with the same tag is already added, the previous one will be canceled and * removed before adding and subscribing to the new one. */ <T> ManagedObservable<T> add(final String observerTag, final String observableTag, Observable<T> observable, ObservableEmitter<? super T> observer) { checkNotDestroyed(); final Map<String, ManagedObservable<?>> existingObservables = getObservablesForObserver(observerTag); ManagedObservable<?> previousObservable = existingObservables.get(observableTag); if (previousObservable != null) { cancelAndRemove(observerTag, observableTag); } ManagedObservable<T> managedObservable = new ManagedObservable<>(observerTag, observableTag, observable, observer, new Action() { @Override public void run() { existingObservables.remove(observableTag); } }); existingObservables.put(observableTag, managedObservable); if (!locked) { managedObservable.unlock(); } return managedObservable; } Map<String, ManagedObservable<?>> getObservablesForObserver( Observer<?> observer) { return getObservablesForObserver(Utils.getObserverTag(observer)); } Map<String, ManagedObservable<?>> getObservablesForObserver(String observerTag) { Map<String, ManagedObservable<?>> map = groupMap.get(observerTag); if (map == null) { map = new ConcurrentHashMap<>(); groupMap.put(observerTag, map); } return map; } /** * Transforms an existing {@link Observable} by returning a new {@link Observable} that is * automatically added to this {@link ObservableGroup} with the provided {@code tag} when * subscribed to. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer, String observableTag) { return new GroupSubscriptionTransformer<>(this, Utils.getObserverTag(observer), observableTag); } /** * Transforms an existing {@link Observable} by returning a new {@link Observable} that is * automatically added to this {@link ObservableGroup}. * <p> Convenience method * for {@link #transform(Observer, String)} when {@code observer} only * is subscribed to one {@link Observable}. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer) { return transform(observer, Utils.getObserverTag(observer)); } /** * Cancels all subscriptions and releases references to Observables and Observers. No more * Observables can be added to this group after it has been destroyed and it becomes unusable. */ void destroy() { destroyed = true; for (Map<String, ManagedObservable<?>> observableMap : groupMap.values()) { for (ManagedObservable<?> managedObservable : observableMap.values()) { managedObservable.cancel(); } observableMap.clear(); } groupMap.clear(); } private void forAllObservables(Consumer<ManagedObservable<?>> action) { for (Map<String, ManagedObservable<?>> observableMap : groupMap.values()) { for (ManagedObservable<?> managedObservable : observableMap.values()) { try { action.accept(managedObservable); } catch (Exception e) { throw new RuntimeException(e); } } } } /** * Locks (prevents) Observables added to this group from emitting new events. Observables added * via {@link #transform(Observer, String)} while the group is locked will * **not** be subscribed until their respective group is unlocked. If it's never unlocked, then * the Observable will never be subscribed to at all. This does not clear references to existing * Observers. Please use {@link #dispose()} if you want to clear references to existing * Observers. */ public void lock() { locked = true; forAllObservables(new Consumer<ManagedObservable<?>>() { @Override public void accept(ManagedObservable<?> managedObservable) { managedObservable.lock(); } }); } /** * Unlocks (releases) Observables added to this group to emit new events until they are locked, * unsubscribed or cancelled. */ public void unlock() { locked = false; forAllObservables(new Consumer<ManagedObservable<?>>() { @Override public void accept(ManagedObservable<?> managedObservable) { managedObservable.unlock(); } }); } /** * Disposes all Observables managed by this group. Also clears any references to existing * {@link Observer} objects in order to avoid leaks. This does not disconnect from the upstream * Observable, so it can be resumed upon calling {@link #observable(Observer)} if * needed. */ public void dispose() { forAllObservables(new Consumer<ManagedObservable<?>>() { @Override public void accept(ManagedObservable<?> managedObservable) { managedObservable.dispose(); } }); } /** * Returns an existing {@link Observable} for the {@link TaggedObserver}. * <p> * <p> Does not change the locked status of this {@link ObservableGroup}. * If it is unlocked, and the Observable has already emitted events, * they will be immediately delivered. If it is locked then no events will be * delivered until it is unlocked. */ public <T> Observable<T> observable(Observer<? super T> observer) { return observable(observer, Utils.getObserverTag(observer)); } public <T> Observable<T> observable(Observer<? super T> observer, String observableTag) { checkNotDestroyed(); String observerTag = Utils.getObserverTag(observer); Map<String, ManagedObservable<?>> observables = getObservablesForObserver(observerTag); //noinspection unchecked ManagedObservable<T> managedObservable = (ManagedObservable<T>) observables.get( observableTag); if (managedObservable == null) { throw new IllegalStateException("No observable exists for observer: " + observerTag + " and observable: " + observableTag); } Observable<T> observable = managedObservable.proxiedObservable(); return observable.compose(new GroupResubscriptionTransformer<>(managedObservable)); } /** * @return a {@link SourceSubscription} with which the {@link Observer} can dispose from or * cancel before the {@link Observable} has completed. If no {@link Observable} is found for the * provided {@code observableTag}, {@code null} is returned instead. */ public SourceSubscription subscription(Observer<?> observer, String observableTag) { return subscription(Utils.getObserverTag(observer), observableTag); } /** * Convenience method for {@link #subscription(Observer, String)}, with * {@code observableTag} of {@link TaggedObserver#getTag()}. * <p> * <p> Use when the {@code observer} is associated with only one {@link Observable}. */ public SourceSubscription subscription(Observer<?> observer) { return subscription(observer, Utils.getObserverTag(observer)); } private SourceSubscription subscription(String observerTag, String observableTag) { Map<String, ManagedObservable<?>> observables = getObservablesForObserver(observerTag); return observables.get(observableTag); } public <T> void resubscribeAll(TaggedObserver<? super T> observer) { Map<String, ManagedObservable<?>> observables = getObservablesForObserver(observer); for (String observableTag : observables.keySet()) { observable(observer, observableTag).subscribe(observer); } } /** * Resubscribes the {@link TaggedObserver} to the observable identified by {@code observableTag}. */ public <T> void resubscribe(TaggedObserver<? super T> observer, String observableTag) { final Observable<T> observable = observable(observer, observableTag); if (observable != null) { observable.subscribe(observer); } } /** * Resubscribes the {@link TaggedObserver} to the observable * identified by {@code observableTag}. * <p> Convenience method * for {@link #resubscribe(TaggedObserver, String)} when {@code observer} only * is subscribed to one {@link Observable}. */ public <T> void resubscribe(TaggedObserver<? super T> observer) { resubscribe(observer, Utils.getObserverTag(observer)); } /** * Removes the {@link Observable} identified by {@code observableTag} for the given * {@link Observer} and cancels it subscription. * No more events will be delivered to its subscriber. * <p>If no Observable is found for the provided {@code observableTag}, nothing happens. */ public void cancelAndRemove(Observer<?> observer, String observableTag) { cancelAndRemove(Utils.getObserverTag(observer), observableTag); } /** * Removes all {@link Observable} for the given * {@link Observer} and cancels their subscriptions. * No more events will be delivered to its subscriber. */ public void cancelAllObservablesForObserver(Observer<?> observer) { cancelAllObservablesForObserver(Utils.getObserverTag(observer)); } private void cancelAllObservablesForObserver(String observerTag) { Map<String, ManagedObservable<?>> observables = getObservablesForObserver(observerTag); for (ManagedObservable<?> managedObservable : observables.values()) { managedObservable.cancel(); } observables.clear(); } /** * Removes the supplied {@link Observable} from this group and cancels it subscription. No more * events will be delivered to its subscriber. */ private void cancelAndRemove(String observerTag, String observableTag) { Map<String, ManagedObservable<?>> observables = getObservablesForObserver(observerTag); ManagedObservable<?> managedObservable = observables.get(observableTag); if (managedObservable != null) { managedObservable.cancel(); observables.remove(observableTag); } } /** * Returns whether the observer has an existing {@link Observable} with * the provided {@code observableTag}. */ public boolean hasObservable(Observer<?> observer, String observableTag) { return subscription(observer, observableTag) != null; } /** * Returns whether the observer has any existing {@link Observable}. */ public boolean hasObservables(Observer<?> observer) { return !getObservablesForObserver(observer).isEmpty(); } /** * Returns whether this group has been already destroyed or not. */ public boolean isDestroyed() { return destroyed; } private void checkNotDestroyed() { Preconditions.checkState(!destroyed, "Group is already destroyed! id=" + groupId); } @Override public String toString() { return "ObservableGroup{" + "groupMap=" + groupMap + ", groupId=" + groupId + ", locked=" + locked + ", destroyed=" + destroyed + '}'; } void removeNonResubscribableObservers() { for (String observerTag : groupMap.keySet()) { if (NonResubscribableTag.isNonResubscribableTag(observerTag)) { cancelAllObservablesForObserver(observerTag); } } } }
6,128
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/SourceSubscription.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import io.reactivex.disposables.Disposable; public interface SourceSubscription extends Disposable { /** * Indicates whether this {@code SourceSubscription} is currently cancelled, that is, whether the * underlying HTTP request associated to it has been cancelled. * * @return {@code true} if this {@code Subscription} is currently cancelled, {@code false} * otherwise */ boolean isCancelled(); /** * Stops the receipt of notifications on the {@link io.reactivex.Observer} that was registered * when this Subscription was received. This allows unregistering an {@link io.reactivex.Observer} * before it has finished receiving all events (i.e. before onCompleted is called). Also causes * the underlying HTTP request to be cancelled by unsubscribing from Retrofit's Observable. */ void cancel(); }
6,129
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/NonResubscribableTag.java
package com.airbnb.rxgroups; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Creates a tag of the form NonResubscribableTag_className#hashcode. */ class NonResubscribableTag { private static final String IDENTIFIER = NonResubscribableTag.class.getSimpleName(); private static final Pattern REGEX_MATCHER = Pattern.compile(IDENTIFIER + "_.*#\\d+"); private static final String TEMPLATE = IDENTIFIER + "_%s#%d"; static String create(Object object) { return String.format(TEMPLATE, object.getClass().getSimpleName(), object.hashCode()); } static boolean isNonResubscribableTag(String tag) { Matcher matcher = REGEX_MATCHER.matcher(tag); return matcher.find(); } }
6,130
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/ManagedObservable.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.functions.Action; /** * A wrapper for a {@link SubscriptionProxy} for use with the {@link ObservableGroup} to monitor a * subscription state by tag. */ class ManagedObservable<T> implements SourceSubscription { private final String observableTag; private final String observerTag; private final SubscriptionProxy<T> proxy; private boolean locked = true; private ObservableEmitter<? super T> observerEmitter; ManagedObservable(String observerTag, String observableTag, Observable<T> upstreamObservable, ObservableEmitter<? super T> observer, Action onTerminate) { this.observableTag = observableTag; this.observerTag = observerTag; this.observerEmitter = observer; proxy = SubscriptionProxy.create(upstreamObservable, onTerminate); } @Override public boolean isCancelled() { return proxy.isCancelled(); } @Override public void cancel() { proxy.cancel(); observerEmitter = null; } void lock() { locked = true; proxy.dispose(); } @Override public void dispose() { proxy.dispose(); observerEmitter = null; } @Override public boolean isDisposed() { return proxy.isDisposed(); } void unlock() { locked = false; if (observerEmitter != null) { proxy.subscribe(observerEmitter); } } Observable<T> proxiedObservable() { return proxy.observable(); } void resubscribe(ObservableEmitter<? super T> observerEmitter) { this.observerEmitter = Preconditions.checkNotNull(observerEmitter); if (!locked) { proxy.subscribe(observerEmitter); } } @Override public String toString() { return "ManagedObservable{" + "observableTag='" + observableTag + '\'' + ", observerTag='" + observerTag + '\'' + ", locked=" + locked + '}'; } }
6,131
0
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups
Create_ds/RxGroups/rxgroups/src/main/java/com/airbnb/rxgroups/processor/ProcessorHelper.java
package com.airbnb.rxgroups.processor; public class ProcessorHelper { public static final String GENERATED_CLASS_NAME_SUFFIX = "_ObservableResubscriber"; }
6,132
0
Create_ds/RxGroups/rxgroups-processor/src/main/java/com/airbnb/rxgroups
Create_ds/RxGroups/rxgroups-processor/src/main/java/com/airbnb/rxgroups/processor/ProcessorUtils.java
package com.airbnb.rxgroups.processor; import com.airbnb.rxgroups.AutoResubscribingObserver; import com.airbnb.rxgroups.AutoTaggableObserver; import com.airbnb.rxgroups.TaggedObserver; import javax.lang.model.element.Element; import javax.lang.model.type.TypeMirror; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; class ProcessorUtils { static boolean isResubscribingObserver(Element observerFieldElement, Types typeUtil, Elements elementUtil) { final TypeMirror autoResubscribingTypeMirror = elementUtil.getTypeElement( AutoResubscribingObserver.class.getCanonicalName()).asType(); return typeUtil.isAssignable(observerFieldElement.asType(), typeUtil.erasure( autoResubscribingTypeMirror)); } static boolean isTaggedObserver(Element observerFieldElement, Types typeUtil, Elements elementUtil) { final TypeMirror autoResubscribingTypeMirror = elementUtil.getTypeElement( TaggedObserver.class.getCanonicalName()).asType(); return typeUtil.isAssignable(observerFieldElement.asType(), typeUtil.erasure( autoResubscribingTypeMirror)); } static boolean isAutoTaggable(Element observerFieldElement, Types typeUtil, Elements elementUtil) { final TypeMirror autoResubscribingTypeMirror = elementUtil.getTypeElement( AutoTaggableObserver.class.getCanonicalName()).asType(); return typeUtil.isAssignable(observerFieldElement.asType(), typeUtil.erasure( autoResubscribingTypeMirror)); } }
6,133
0
Create_ds/RxGroups/rxgroups-processor/src/main/java/com/airbnb/rxgroups
Create_ds/RxGroups/rxgroups-processor/src/main/java/com/airbnb/rxgroups/processor/ResubscriptionProcessor.java
package com.airbnb.rxgroups.processor; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoResubscribingObserver; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.AutoTaggableObserver; import com.airbnb.rxgroups.BaseObservableResubscriber; import com.airbnb.rxgroups.ObservableGroup; import com.airbnb.rxgroups.TaggedObserver; import com.google.auto.service.AutoService; import com.google.common.collect.ImmutableSet; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.Processor; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import javax.tools.Diagnostic; import static com.airbnb.rxgroups.processor.ResubscriptionProcessor.ObserverType.AUTO_RESUBSCRIBE_OBSERVER; import static com.airbnb.rxgroups.processor.ResubscriptionProcessor.ObserverType.TAGGED_OBSERVER; import static javax.lang.model.element.ElementKind.CLASS; import static javax.lang.model.element.Modifier.PRIVATE; import static javax.lang.model.element.Modifier.PUBLIC; import static javax.lang.model.element.Modifier.STATIC; @AutoService(Processor.class) public class ResubscriptionProcessor extends AbstractProcessor { private Filer filer; private Messager messager; private Elements elementUtils; private Types typeUtils; private final List<Exception> loggedExceptions = new ArrayList<>(); @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); elementUtils = processingEnv.getElementUtils(); typeUtils = processingEnv.getTypeUtils(); } @Override public Set<String> getSupportedAnnotationTypes() { return ImmutableSet.of(AutoResubscribe.class.getCanonicalName(), AutoTag.class.getCanonicalName()); } @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { LinkedHashMap<TypeElement, ClassToGenerateInfo> modelClassMap = new LinkedHashMap<>(); for (Element observer : roundEnv.getElementsAnnotatedWith(AutoResubscribe.class)) { try { processObserver(observer, modelClassMap, AutoResubscribe.class); } catch (Exception e) { logError(e); } } for (Element observer : roundEnv.getElementsAnnotatedWith(AutoTag.class)) { try { processObserver(observer, modelClassMap, AutoTag.class); } catch (Exception e) { logError(e); } } for (Map.Entry<TypeElement, ClassToGenerateInfo> modelEntry : modelClassMap.entrySet()) { try { generateClass(modelEntry.getValue()); } catch (Exception e) { logError(e); } } if (roundEnv.processingOver()) { for (Exception loggedException : loggedExceptions) { messager.printMessage(Diagnostic.Kind.ERROR, loggedException.toString()); } } // Let other processors access our annotations as well return false; } private void processObserver(Element observer, LinkedHashMap<TypeElement, ClassToGenerateInfo> info, Class<? extends Annotation> annotationClass) { validateObserverField(observer, annotationClass); TypeElement enclosingClass = (TypeElement) observer.getEnclosingElement(); ClassToGenerateInfo targetClass = getOrCreateTargetClass(info, enclosingClass); String observerName = observer.getSimpleName().toString(); boolean isAutoResubscribing = ProcessorUtils.isResubscribingObserver(observer, typeUtils, elementUtils); ObserverType observerType = isAutoResubscribing ? AUTO_RESUBSCRIBE_OBSERVER : TAGGED_OBSERVER; boolean isAutoTaggable = ProcessorUtils.isAutoTaggable(observer, typeUtils, elementUtils); boolean shouldAutoResubscribe = annotationClass == AutoResubscribe.class; String customTag = getCustomTag(observer, annotationClass); targetClass.addObserver(observerName, new ObserverInfo(observerType, customTag, isAutoTaggable, shouldAutoResubscribe)); } private String getCustomTag(Element observer, Class<? extends Annotation> annotationClass) { String customTag = ""; if (annotationClass == AutoResubscribe.class) { customTag = ((AutoResubscribe)observer.getAnnotation(annotationClass)).customTag(); } else if (annotationClass == AutoTag.class) { customTag = ((AutoTag)observer.getAnnotation(annotationClass)).customTag(); } return customTag; } private void validateObserverField(Element observerFieldElement, Class<? extends Annotation> annotationClass) { TypeElement enclosingClass = (TypeElement) observerFieldElement.getEnclosingElement(); if (annotationClass == AutoResubscribe.class && !ProcessorUtils.isTaggedObserver(observerFieldElement, typeUtils, elementUtils)) { logError("%s annotation may only be on %s types. (class: %s, field: %s)", annotationClass.getSimpleName(), TaggedObserver.class, enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } if (annotationClass == AutoTag.class && !(ProcessorUtils.isAutoTaggable(observerFieldElement, typeUtils, elementUtils) || ProcessorUtils.isResubscribingObserver(observerFieldElement, typeUtils, elementUtils))) { logError("%s annotation may only be on %s or %s types. (class: %s, field: %s)", annotationClass.getSimpleName(), AutoTaggableObserver.class, AutoResubscribingObserver.class, enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } // Verify method modifiers. Set<Modifier> modifiers = observerFieldElement.getModifiers(); if (modifiers.contains(PRIVATE) || modifiers.contains(STATIC)) { logError( "%s annotations must not be on private or static fields. (class: %s, field: " + "%s)", annotationClass.getSimpleName(), enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } // Nested classes must be static if (enclosingClass.getNestingKind().isNested()) { if (!enclosingClass.getModifiers().contains(STATIC)) { logError( "Nested classes with %s annotations must be static. (class: %s, field: %s)", annotationClass.getSimpleName(), enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } } // Verify containing type. if (enclosingClass.getKind() != CLASS) { logError("%s annotations may only be contained in classes. (class: %s, field: %s)", annotationClass.getSimpleName(), enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } // Verify containing class visibility is not private. if (enclosingClass.getModifiers().contains(PRIVATE)) { logError("%s annotations may not be contained in private classes. (class: %s, " + "field: %s)", annotationClass.getSimpleName(), enclosingClass.getSimpleName(), observerFieldElement.getSimpleName()); } } private ClassToGenerateInfo getOrCreateTargetClass( Map<TypeElement, ClassToGenerateInfo> modelClassMap, TypeElement classElement) { ClassToGenerateInfo classToGenerateInfo = modelClassMap.get(classElement); if (classToGenerateInfo == null) { ClassName generatedClassName = getGeneratedClassName(classElement); classToGenerateInfo = new ClassToGenerateInfo(classElement, generatedClassName); modelClassMap.put(classElement, classToGenerateInfo); } return classToGenerateInfo; } private ClassName getGeneratedClassName(TypeElement classElement) { String packageName = elementUtils.getPackageOf(classElement).getQualifiedName().toString(); int packageLen = packageName.length() + 1; String className = classElement.getQualifiedName().toString().substring(packageLen).replace('.', '$'); return ClassName.get(packageName, className + ProcessorHelper.GENERATED_CLASS_NAME_SUFFIX); } private void generateClass(ClassToGenerateInfo info) throws IOException { TypeSpec generatedClass = TypeSpec.classBuilder(info.generatedClassName) .superclass(BaseObservableResubscriber.class) .addJavadoc("Generated file. Do not modify!") .addModifiers(Modifier.PUBLIC) .addMethod(generateConstructor(info)) .build(); JavaFile.builder(info.generatedClassName.packageName(), generatedClass) .build() .writeTo(filer); } private MethodSpec generateConstructor(ClassToGenerateInfo info) { MethodSpec.Builder builder = MethodSpec.constructorBuilder() .addModifiers(PUBLIC) .addParameter(ParameterSpec.builder(TypeName.get(info.originalClassName.asType()) , "target").build()) .addParameter(ParameterSpec.builder(TypeName.get(ObservableGroup.class), "group") .build()); for (Map.Entry<String, ObserverInfo> observerNameAndType : info.observerNamesToType.entrySet()) { String observerName = observerNameAndType.getKey(); ObserverInfo observerInfo = observerNameAndType.getValue(); if (observerInfo.type == AUTO_RESUBSCRIBE_OBSERVER || observerInfo.autoTaggable) { String tag = "".equals(observerInfo.customTag) ? info.originalClassName.getSimpleName().toString() + "_" + observerName : observerInfo.customTag; builder.addStatement("setTag(target.$L, $S)", observerName, tag); } if (observerInfo.shouldAutoResubscribe) { builder.addStatement("group.resubscribeAll(target.$L)", observerName); } } return builder.build(); } private static class RxGroupsResubscriptionProcessorException extends Exception { RxGroupsResubscriptionProcessorException(String message) { super(message); } } private void logError(String msg, Object... args) { logError(new RxGroupsResubscriptionProcessorException(String.format(msg, args))); } enum ObserverType { TAGGED_OBSERVER, AUTO_RESUBSCRIBE_OBSERVER } private static class ObserverInfo { final ObserverType type; final String customTag; final boolean autoTaggable; final boolean shouldAutoResubscribe; ObserverInfo(ObserverType type, String customTag, boolean autoTaggable, boolean shouldAutoResubscribe) { this.type = type; this.customTag = customTag; this.autoTaggable = autoTaggable; this.shouldAutoResubscribe = shouldAutoResubscribe; } } /** * Exceptions are caught and logged, and not printed until all processing is done. This allows * generated classes to be created first and allows for easier to read compile time error * messages. */ private void logError(Exception e) { loggedExceptions.add(e); } private static class ClassToGenerateInfo { final Map<String, ObserverInfo> observerNamesToType = new LinkedHashMap<>(); private final TypeElement originalClassName; private final ClassName generatedClassName; public ClassToGenerateInfo(TypeElement originalClassName, ClassName generatedClassName) { this.originalClassName = originalClassName; this.generatedClassName = generatedClassName; } public void addObserver(String observerName, ObserverInfo type) { observerNamesToType.put(observerName, type); } } }
6,134
0
Create_ds/RxGroups/rxgroups-android/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups-android/src/test/java/com/airbnb/rxgroups/GroupLifecycleManagerTest.java
package com.airbnb.rxgroups; import android.app.Activity; import android.os.Build; import android.os.Bundle; import com.airbnb.rxgroups.android.BuildConfig; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Matchers; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.observers.TestObserver; import io.reactivex.subjects.PublishSubject; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.doCallRealMethod; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @Config(sdk = Build.VERSION_CODES.LOLLIPOP, constants = BuildConfig.class) @RunWith(RobolectricGradleTestRunner.class) public class GroupLifecycleManagerTest { private final PublishSubject<String> testSubject = PublishSubject.create(); private final ObservableManager observableManager = mock(ObservableManager.class); private final ObservableGroup group = mock(ObservableGroup.class); private final TestTarget target = new TestTarget(); static class TestTarget { @AutoResubscribe final TestAutoResubscribingObserver observer = new TestAutoResubscribingObserver("foo"); @AutoResubscribe final TaggedObserver taggedObserver = new TaggedObserver() { @Override public String getTag() { return "bar"; } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(Object o) { } }; } @Test public void testSubscribe() { when(observableManager.newGroup()).thenReturn(group); doCallRealMethod().when(group).initializeAutoTaggingAndResubscription(Matchers.any()); GroupLifecycleManager.onCreate(observableManager, null, target); verify(group).resubscribeAll(target.observer); verify(group).resubscribeAll(target.taggedObserver); } @Test public void testSubscribeNoObservables() { when(observableManager.newGroup()).thenReturn(group); GroupLifecycleManager.onCreate(observableManager, null, null); verify(group, never()).resubscribeAll(any(AutoResubscribingObserver.class)); } @Test public void testCreateWithNoNullTarget() { when(observableManager.newGroup()).thenReturn(group); GroupLifecycleManager.onCreate(observableManager, null, null); verify(group, never()).resubscribeAll(any(AutoResubscribingObserver.class)); verify(group, never()).resubscribeAll(any(TaggedObserver.class)); } public void testSubscribeInvalidTargetNoException() { when(observableManager.newGroup()).thenReturn(group); GroupLifecycleManager.onCreate(observableManager, null, new Object()); } @Test(expected = NullPointerException.class) public void testSubscribeNullTargetFails() { when(observableManager.newGroup()).thenReturn(group); GroupLifecycleManager groupLifecycleManager = GroupLifecycleManager.onCreate (observableManager, null, null); groupLifecycleManager.initializeAutoTaggingAndResubscription(null); } @Test public void testDestroyFinishingActivity() { when(observableManager.newGroup()).thenReturn(group); when(group.hasObservables(target.observer)).thenReturn(true); when(group.observable(target.observer)).thenReturn(testSubject); when(group.hasObservables(target.taggedObserver)).thenReturn(true); when(group.observable(target.taggedObserver)).thenReturn(testSubject); GroupLifecycleManager lifecycleManager = GroupLifecycleManager.onCreate(observableManager, null, target); Activity activity = mock(Activity.class); when(activity.isFinishing()).thenReturn(true); lifecycleManager.onDestroy(activity); verify(observableManager).destroy(group); } @Test public void testNonResubscribableObservablesRemovedAfterNonFinishingDestroy() { when(observableManager.newGroup()).thenReturn(new ObservableGroup(1)); GroupLifecycleManager lifecycleManager = GroupLifecycleManager.onCreate (observableManager, null, target); TestObserver<String> nonResubscribableObserver = new TestObserver<>(); PublishSubject.<String>create() .compose(lifecycleManager.group().transform(nonResubscribableObserver)) .subscribe(nonResubscribableObserver); assertThat(lifecycleManager.group().hasObservables(nonResubscribableObserver)).isTrue(); //Simulate a rotation Activity activity = mock(Activity.class); when(activity.isFinishing()).thenReturn(false); lifecycleManager.onSaveInstanceState(new Bundle()); lifecycleManager.onDestroy(activity); assertThat(lifecycleManager.group().hasObservables(nonResubscribableObserver)).isFalse(); } @Test public void testTaggedObserverNotRemovedAfterNonFinishingDestroy() { when(observableManager.newGroup()).thenReturn(new ObservableGroup(1)); GroupLifecycleManager lifecycleManager = GroupLifecycleManager.onCreate (observableManager, null, target); TaggedObserver<String> stableObserver = new TaggedObserver<String>() { @Override public String getTag() { return "stableTag"; } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(String s) { } }; PublishSubject.<String>create() .compose(lifecycleManager.group().transform(stableObserver)) .subscribe(stableObserver); assertThat(lifecycleManager.group().hasObservables(stableObserver)).isTrue(); //Simulate a rotation Activity activity = mock(Activity.class); when(activity.isFinishing()).thenReturn(false); lifecycleManager.onSaveInstanceState(new Bundle()); lifecycleManager.onDestroy(activity); assertThat(lifecycleManager.group().hasObservables(stableObserver)).isTrue(); } }
6,135
0
Create_ds/RxGroups/rxgroups-android/src/main/java/com/airbnb
Create_ds/RxGroups/rxgroups-android/src/main/java/com/airbnb/rxgroups/GroupLifecycleManager.java
/* * Copyright (C) 2016 Airbnb, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.airbnb.rxgroups; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.os.Parcel; import android.os.Parcelable; import java.util.UUID; import javax.annotation.Nullable; import io.reactivex.ObservableTransformer; import io.reactivex.Observer; /** * Manges unlocking, locking, and destroying observables based on the lifecycle of an activity or * fragment. An Activity or fragment must call: * <ul> * <li>{@link #onCreate(ObservableManager, Bundle, Object)}</li> * <li>{@link #onResume()}</li> * <li>{@link #onPause()}</li> * <li>{@link #onDestroy(Activity)}</li> * <li>{@link #onSaveInstanceState(Bundle)}</li> * </ul> * in corresponding methods. */ @SuppressWarnings("WeakerAccess") public class GroupLifecycleManager { private static final String KEY_STATE = "KEY_GROUPLIFECYCLEMANAGER_STATE"; private final ObservableManager observableManager; private final ObservableGroup group; private boolean hasSavedState; private GroupLifecycleManager(ObservableManager observableManager, ObservableGroup group) { this.observableManager = observableManager; this.group = group; } /** Call this method from your Activity or Fragment's onCreate method */ public static GroupLifecycleManager onCreate(ObservableManager observableManager, @Nullable Bundle savedState, @Nullable Object target) { ObservableGroup group; if (savedState != null) { State state = savedState.getParcelable(KEY_STATE); Preconditions.checkState(state != null, "Must call onSaveInstanceState() first"); // First check the instance ID before restoring state. If it's not the same instance, // then we have to create a new group since the previous one is already destroyed. // Android can sometimes reuse the same instance after saving state and we can't reliably // determine when that happens. This is a workaround for that behavior. if (state.managerId != observableManager.id()) { group = observableManager.newGroup(); } else { group = observableManager.getGroup(state.groupId); } } else { group = observableManager.newGroup(); } group.lock(); GroupLifecycleManager manager = new GroupLifecycleManager(observableManager, group); if (target != null) { manager.initializeAutoTaggingAndResubscription(target); } return manager; } /** @return the {@link ObservableGroup} associated to this instance */ public ObservableGroup group() { return group; } /** * Calls {@link ObservableGroup#transform(Observer)} for the group managed by * this instance. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer) { return group.transform(observer); } /** * Calls {@link ObservableGroup#transform(Observer, String)} for the group managed by * this instance. */ public <T> ObservableTransformer<? super T, T> transform(Observer<? super T> observer, String observableTag) { return group.transform(observer, observableTag); } /** * Call {@link ObservableGroup#hasObservables(Observer)} for the group managed by * this instance. */ public boolean hasObservables(Observer<?> observer) { return group.hasObservables(observer); } /** * Call {@link ObservableGroup#hasObservable(Observer, String)} for the group managed by * this instance. */ public boolean hasObservable(Observer<?> observer, String observableTag) { return group.hasObservable(observer, observableTag); } /** * Calls * {@link ObservableGroup#initializeAutoTaggingAndResubscription(Object)} (Object, Class)} * for the group managed by this instance. */ public void initializeAutoTaggingAndResubscription(Object target) { Preconditions.checkNotNull(target, "Target cannot be null"); group.initializeAutoTaggingAndResubscription(target); } /** * Calls * {@link ObservableGroup#initializeAutoTaggingAndResubscriptionInTargetClassOnly(Object, Class)} * for the group managed by this instance. */ public <T> void initializeAutoTaggingAndResubscriptionInTargetClassOnly(T target, Class<T> targetClass) { group.initializeAutoTaggingAndResubscriptionInTargetClassOnly(target, targetClass); } /** * Calls {@link ObservableGroup#cancelAllObservablesForObserver(Observer)} (Observer)} * for the group associated with this instance. */ public void cancelAllObservablesForObserver(Observer<?> observer) { group.cancelAllObservablesForObserver(observer); } /** * Calls {@link ObservableGroup#cancelAndRemove(Observer, String)} for the group * associated with this instance. */ public void cancelAndRemove(Observer<?> observer, String observableTag) { group.cancelAndRemove(observer, observableTag); } private void onDestroy(boolean isFinishing) { if (isFinishing) { observableManager.destroy(group); } else { group().removeNonResubscribableObservers(); group.dispose(); } } /** Call this method from your Activity or Fragment's onDestroy method */ public void onDestroy(@Nullable Activity activity) { // We need to track whether the current Activity is finishing or not in order to decide if we // should destroy the ObservableGroup. If the Activity is not finishing, then we should not // destroy it, since we know that we're probably restoring state at some point and reattaching // to the existing ObservableGroup. If saveState() was not called, then it's likely that we're // being destroyed and are not ever coming back. However, this isn't perfect, especially // when using fragments in a ViewPager. We might want to allow users to explicitly destroy it // instead, in order to mitigate this issue. // Also in some situations it seems like an Activity can be recreated even though its // isFinishing() property is set to true. For this reason, we must also check // isChangingConfigurations() to make sure it's safe to destroy the group. onDestroy(!hasSavedState || (activity != null && activity.isFinishing() && !activity.isChangingConfigurations())); } /** Call this method from your Activity or Fragment's onDestroy method */ public void onDestroy(Fragment fragment) { onDestroy(fragment.getActivity()); } /** Call this method from your Activity or Fragment's onResume method */ public void onResume() { hasSavedState = false; unlock(); } /** Call this method from your Activity or Fragment's onPause method */ public void onPause() { lock(); } private void lock() { group.lock(); } private void unlock() { group.unlock(); } /** Call this method from your Activity or Fragment's onSaveInstanceState method */ public void onSaveInstanceState(Bundle outState) { hasSavedState = true; outState.putParcelable(KEY_STATE, new State(observableManager.id(), group.id())); } static class State implements Parcelable { final UUID managerId; final long groupId; State(UUID managerId, long groupId) { this.managerId = managerId; this.groupId = groupId; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeSerializable(managerId); dest.writeLong(groupId); } public static final Parcelable.Creator<State> CREATOR = new Parcelable.Creator<State>() { @Override public State[] newArray(int size) { return new State[size]; } @Override public State createFromParcel(Parcel source) { return new State((UUID) source.readSerializable(), source.readLong()); } }; } }
6,136
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/PlainObserver_Fail_AutoTag.java
package test; import com.airbnb.rxgroups.AutoTag; import io.reactivex.Observer; public class PlainObserver_Fail_AutoTag { @AutoTag public Observer<Object> taggedObserver = new Observer<Object>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } }; }
6,137
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoResubscribingObserver_Pass_All.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.AutoResubscribingObserver; public class AutoResubscribingObserver_Pass_All { @AutoResubscribe AutoResubscribingObserver<Object> observer = new AutoResubscribingObserver<Object>() { }; @AutoTag AutoResubscribingObserver<Object> observer1 = new AutoResubscribingObserver<Object>() { }; }
6,138
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/TaggedObserver_Pass_AutoResubscribe.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.TaggedObserver; import io.reactivex.disposables.Disposable; public class TaggedObserver_Pass_AutoResubscribe { @AutoResubscribe public TaggedObserver<Object> taggedObserver = new TaggedObserver<Object>() { @Override public String getTag() { return "stableTag"; } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } @Override public void onSubscribe(Disposable d) { } }; }
6,139
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoResubscribingObserver_Fail_Private_AutoTag.java
package test; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.AutoResubscribingObserver; public class AutoResubscribingObserver_Fail_Private_AutoTag { @AutoTag private AutoResubscribingObserver<Object> observer = new AutoResubscribingObserver<Object>() { }; }
6,140
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/TaggedObserver_Fail_AutoTag.java
package test; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.TaggedObserver; public class TaggedObserver_Fail_AutoTag { @AutoTag public TaggedObserver<Object> taggedObserver = new TaggedObserver<Object>() { @Override public String getTag() { return "stableTag"; } @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } }; }
6,141
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/PlainObserver_Fail_AutoResubscribe.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import io.reactivex.Observer; public class PlainObserver_Fail_AutoResubscribe { @AutoResubscribe public Observer<Object> taggedObserver = new Observer<Object>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Object o) { } }; }
6,142
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoResubscribingObserver_Fail_Private.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoResubscribingObserver; public class AutoResubscribingObserver_Fail_Private { @AutoResubscribe private AutoResubscribingObserver<Object> observer = new AutoResubscribingObserver<Object>() { }; }
6,143
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoResubscribingObserver_Fail_NonStatic.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoResubscribingObserver; public class AutoResubscribingObserver_Fail_NonStatic { class Inner { @AutoResubscribe private AutoResubscribingObserver<Object> observer = new AutoResubscribingObserver<Object>() { }; } }
6,144
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoTaggableObserver_Pass_All.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.AutoTaggableObserverImpl; public class AutoTaggableObserver_Pass_All { @AutoResubscribe public AutoTaggableObserverImpl<Object> resubscribeObserver = new AutoTaggableObserverImpl<Object>(); @AutoTag public AutoTaggableObserverImpl<Object> autoTag = new AutoTaggableObserverImpl<Object>(); }
6,145
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test
Create_ds/RxGroups/rxgroups-annotation-test/src/test/resources/AutoTaggableObserver_Pass_All_CustomTag.java
package test; import com.airbnb.rxgroups.AutoResubscribe; import com.airbnb.rxgroups.AutoTag; import com.airbnb.rxgroups.AutoTaggableObserverImpl; public class AutoTaggableObserver_Pass_All_CustomTag { @AutoResubscribe(customTag = "tag1") public AutoTaggableObserverImpl<Object> resubscribeObserver = new AutoTaggableObserverImpl<Object>(); @AutoTag(customTag = "tag2") public AutoTaggableObserverImpl<Object> autoTag = new AutoTaggableObserverImpl<Object>(); }
6,146
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups-annotation-test/src/test/java/com/airbnb/rxgroups/AutoTaggableObserverImpl.java
package com.airbnb.rxgroups; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; public class AutoTaggableObserverImpl<T> implements AutoTaggableObserver<T> { @Override public void setTag(String tag) { } @Override public String getTag() { return null; } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onNext(T t) { } }
6,147
0
Create_ds/RxGroups/rxgroups-annotation-test/src/test/java/com/airbnb
Create_ds/RxGroups/rxgroups-annotation-test/src/test/java/com/airbnb/rxgroups/ResubscriptionProcessorTest.java
package com.airbnb.rxgroups; import com.airbnb.rxgroups.processor.ResubscriptionProcessor; import com.google.common.truth.Truth; import com.google.testing.compile.JavaFileObjects; import com.google.testing.compile.JavaSourceSubjectFactory; import org.junit.Test; import javax.tools.JavaFileObject; public class ResubscriptionProcessorTest { @Test public void autoResubscribeObserver_worksWithAll() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoResubscribingObserver_Pass_All.java"); JavaFileObject resubscriberSource = JavaFileObjects.forSourceString("test.AutoResubscribingObserver_Pass_All", "" + "package test;\n" + "import com.airbnb.rxgroups.BaseObservableResubscriber;\n" + "import com.airbnb.rxgroups.ObservableGroup;\n" + "public class AutoResubscribingObserver_Pass_All_ObservableResubscriber extends BaseObservableResubscriber {\n" + " public AutoResubscribingObserver_Pass_All_ObservableResubscriber(AutoResubscribingObserver_Pass_All target, ObservableGroup group) {\n" + " setTag(target.observer, \"AutoResubscribingObserver_Pass_All_observer\");\n" + " group.resubscribeAll(target.observer);\n" + " setTag(target.observer1, \"AutoResubscribingObserver_Pass_All_observer1\");\n" + " }\n" + "}\n" + "" ); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .compilesWithoutWarnings() .and() .generatesSources(resubscriberSource); } @Test public void taggedObserver_worksWithAutoResubscribe() throws Exception { JavaFileObject source = JavaFileObjects.forResource("TaggedObserver_Pass_AutoResubscribe.java"); JavaFileObject resubscriberSource = JavaFileObjects.forSourceString("test.TaggedObserver_Pass_AutoResubscribe_ObservableResubscriber", "" + "package test;\n" + "import com.airbnb.rxgroups.BaseObservableResubscriber;\n" + "import com.airbnb.rxgroups.ObservableGroup;\n" + "public class TaggedObserver_Pass_AutoResubscribe_ObservableResubscriber extends BaseObservableResubscriber {\n" + " public TaggedObserver_ObservableResubscriber(TaggedObserver_Pass_AutoResubscribe target, ObservableGroup group) {\n" + " group.resubscribeAll(target.taggedObserver);\n" + " }\n" + "}\n" + "" ); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .compilesWithoutWarnings() .and() .generatesSources(resubscriberSource); } @Test public void autoTaggableObserver_worksWithAll() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoTaggableObserver_Pass_All.java"); JavaFileObject resubscriberSource = JavaFileObjects.forSourceString("test.AutoTaggableObserver_Pass_All", "" + "package test;\n" + "import com.airbnb.rxgroups.BaseObservableResubscriber;\n" + "import com.airbnb.rxgroups.ObservableGroup;\n" + "\n" + "public class AutoTaggableObserver_Pass_All_ObservableResubscriber extends BaseObservableResubscriber {\n" + " public AutoTaggableObserver_Pass_All_ObservableResubscriber(AutoTaggableObserver_Pass_All target, ObservableGroup group) {\n" + " setTag(target.resubscribeObserver, \"AutoTaggableObserver_Pass_All_resubscribeObserver\");\n" + " group.resubscribeAll(target.resubscribeObserver);\n" + " setTag(target.autoTag, \"AutoTaggableObserver_Pass_All_autoTag\");\n" + " }\n" + "}\n" + "" ); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .compilesWithoutWarnings() .and() .generatesSources(resubscriberSource); } @Test public void autoTaggableObserver_worksWithAll_customTag() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoTaggableObserver_Pass_All_CustomTag.java"); JavaFileObject resubscriberSource = JavaFileObjects.forSourceString("test.AutoTaggableObserver_Pass_All_CustomTag", "" + "package test;\n" + "import com.airbnb.rxgroups.BaseObservableResubscriber;\n" + "import com.airbnb.rxgroups.ObservableGroup;\n" + "\n" + "public class AutoTaggableObserver_Pass_All_CustomTag_ObservableResubscriber extends BaseObservableResubscriber {\n" + " public AutoTaggableObserver_Pass_All_CustomTag_ObservableResubscriber(AutoTaggableObserver_Pass_All_CustomTag target, ObservableGroup group) {\n" + " setTag(target.resubscribeObserver, \"tag1\");\n" + " group.resubscribeAll(target.resubscribeObserver);\n" + " setTag(target.autoTag, \"tag2\");\n" + " }\n" + "}\n" + "" ); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .compilesWithoutWarnings() .and() .generatesSources(resubscriberSource); } @Test public void plainObserverFails_autoResubscribe() throws Exception { JavaFileObject source = JavaFileObjects.forResource("PlainObserver_Fail_AutoResubscribe.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining("AutoResubscribe annotation may only be on interface com.airbnb.rxgroups.TaggedObserver types."); } @Test public void plainObserverFails_autoTag() throws Exception { JavaFileObject source = JavaFileObjects.forResource("PlainObserver_Fail_AutoTag.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining(" AutoTag annotation may only be on interface com.airbnb.rxgroups.AutoTaggableObserver or class com.airbnb.rxgroups.AutoResubscribingObserver types."); } @Test public void taggedObserverFails_autoTag() throws Exception { JavaFileObject source = JavaFileObjects.forResource("TaggedObserver_Fail_AutoTag.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining("AutoTag annotation may only be on interface com.airbnb.rxgroups.AutoTaggableObserver or class com.airbnb.rxgroups.AutoResubscribingObserver types."); } @Test public void privateObserver_fail() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoResubscribingObserver_Fail_Private.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining("AutoResubscribe annotations must not be on private or static fields."); } @Test public void privateObserver_fail_autoTag() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoResubscribingObserver_Fail_Private_AutoTag.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining("AutoTag annotations must not be on private or static fields."); } @Test public void privateObserver_fail_nonStatic() throws Exception { JavaFileObject source = JavaFileObjects.forResource("AutoResubscribingObserver_Fail_NonStatic.java"); Truth.assertAbout(JavaSourceSubjectFactory.javaSource()).that(source) .withCompilerOptions("-Xlint:-processing") .processedWith(new ResubscriptionProcessor()) .failsToCompile() .withErrorContaining("AutoResubscribe annotations must not be on private or static fields."); } }
6,148
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/CloseOnIdleStateHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.zuul.netty.server.http2.DummyChannelHandler; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.timeout.IdleStateEvent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class CloseOnIdleStateHandlerTest { private Registry registry = new DefaultRegistry(); private Id counterId; private final String listener = "test-idle-state"; @BeforeEach void setup() { counterId = registry.createId("server.connections.idle.timeout").withTags("id", listener); } @Test void incrementCounterOnIdleStateEvent() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(new DummyChannelHandler()); channel.pipeline().addLast(new CloseOnIdleStateHandler(registry, listener)); channel.pipeline() .context(DummyChannelHandler.class) .fireUserEventTriggered(IdleStateEvent.ALL_IDLE_STATE_EVENT); final Counter idleTimeouts = (Counter) registry.get(counterId); assertEquals(1, idleTimeouts.count()); } }
6,149
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/HttpServerLifecycleChannelHandlerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common; import com.google.common.truth.Truth; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; import com.netflix.netty.common.HttpLifecycleChannelHandler.State; import com.netflix.netty.common.HttpServerLifecycleChannelHandler.HttpServerLifecycleInboundChannelHandler; import com.netflix.netty.common.HttpServerLifecycleChannelHandler.HttpServerLifecycleOutboundChannelHandler; import io.netty.buffer.ByteBuf; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import io.netty.util.ReferenceCountUtil; import org.junit.jupiter.api.Test; class HttpServerLifecycleChannelHandlerTest { final class AssertReasonHandler extends ChannelInboundHandlerAdapter { CompleteEvent completeEvent; @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) { assert evt instanceof CompleteEvent; this.completeEvent = (CompleteEvent) evt; } public CompleteEvent getCompleteEvent() { return completeEvent; } } @Test void completionEventReasonIsUpdatedOnPipelineReject() { final EmbeddedChannel channel = new EmbeddedChannel(new HttpServerLifecycleOutboundChannelHandler()); final AssertReasonHandler reasonHandler = new AssertReasonHandler(); channel.pipeline().addLast(reasonHandler); channel.attr(HttpLifecycleChannelHandler.ATTR_STATE).set(State.STARTED); // emulate pipeline rejection channel.attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT).set(Boolean.TRUE); // Fire close channel.pipeline().close(); Truth.assertThat(reasonHandler.getCompleteEvent().getReason()).isEqualTo(CompleteReason.PIPELINE_REJECT); } @Test void completionEventReasonIsCloseByDefault() { final EmbeddedChannel channel = new EmbeddedChannel(new HttpServerLifecycleOutboundChannelHandler()); final AssertReasonHandler reasonHandler = new AssertReasonHandler(); channel.pipeline().addLast(reasonHandler); channel.attr(HttpLifecycleChannelHandler.ATTR_STATE).set(State.STARTED); // Fire close channel.pipeline().close(); Truth.assertThat(reasonHandler.getCompleteEvent().getReason()).isEqualTo(CompleteReason.CLOSE); } @Test void pipelineRejectReleasesIfNeeded() { EmbeddedChannel channel = new EmbeddedChannel(new HttpServerLifecycleInboundChannelHandler()); ByteBuf buffer = UnpooledByteBufAllocator.DEFAULT.buffer(); try { Truth.assertThat(buffer.refCnt()).isEqualTo(1); FullHttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/whatever", buffer); channel.attr(HttpLifecycleChannelHandler.ATTR_STATE).set(State.STARTED); channel.writeInbound(httpRequest); Truth.assertThat(channel.attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT) .get()) .isEqualTo(Boolean.TRUE); Truth.assertThat(buffer.refCnt()).isEqualTo(0); } finally { if (buffer.refCnt() != 0) { ReferenceCountUtil.release(buffer); } } } }
6,150
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/SourceAddressChannelHandlerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common; import org.junit.AssumptionViolatedException; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link SourceAddressChannelHandler}. */ class SourceAddressChannelHandlerTest { @Test void ipv6AddressScopeIdRemoved() throws Exception { Inet6Address address = Inet6Address.getByAddress("localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, 2); assertEquals(2, address.getScopeId()); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); assertEquals("0:0:0:0:0:0:0:1", addressString); } @Test void ipv4AddressString() throws Exception { InetAddress address = Inet4Address.getByAddress("localhost", new byte[] {127, 0, 0, 1}); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); assertEquals("127.0.0.1", addressString); } @Test void failsOnUnresolved() { InetSocketAddress address = InetSocketAddress.createUnresolved("localhost", 8080); String addressString = SourceAddressChannelHandler.getHostAddress(address); assertNull(null, addressString); } @Test void mapsIpv4AddressFromIpv6Address() throws Exception { // Can't think of a reason why this would ever come up, but testing it just in case. // ::ffff:127.0.0.1 Inet6Address address = Inet6Address.getByAddress( "localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xFF, (byte) 0xFF, 127, 0, 0, 1}, -1); assertEquals(0, address.getScopeId()); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); assertEquals("127.0.0.1", addressString); } @Test void ipv6AddressScopeNameRemoved() throws Exception { List<NetworkInterface> nics = Collections.list(NetworkInterface.getNetworkInterfaces()); Assumptions.assumeTrue(!nics.isEmpty(), "No network interfaces"); List<Throwable> failures = new ArrayList<>(); for (NetworkInterface nic : nics) { Inet6Address address; try { address = Inet6Address.getByAddress( "localhost", new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, nic); } catch (UnknownHostException e) { // skip, the nic doesn't match failures.add(e); continue; } assertTrue(address.toString().contains("%"), address.toString()); String addressString = SourceAddressChannelHandler.getHostAddress(new InetSocketAddress(address, 8080)); assertEquals("0:0:0:0:0:0:0:1", addressString); return; } AssumptionViolatedException failure = new AssumptionViolatedException("No Compatible Nics were found"); failures.forEach(failure::addSuppressed); throw failure; } }
6,151
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/metrics/InstrumentedResourceLeakDetectorTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.metrics; import io.netty.buffer.ByteBuf; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) class InstrumentedResourceLeakDetectorTest { InstrumentedResourceLeakDetector<Object> leakDetector; @BeforeEach void setup() { leakDetector = new InstrumentedResourceLeakDetector<>(ByteBuf.class, 1); } @Test void test() { leakDetector.reportTracedLeak("test", "test"); assertEquals(1, leakDetector.leakCounter.get()); leakDetector.reportTracedLeak("test", "test"); assertEquals(2, leakDetector.leakCounter.get()); leakDetector.reportTracedLeak("test", "test"); assertEquals(3, leakDetector.leakCounter.get()); } }
6,152
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/throttle/MaxInboundConnectionsHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.throttle; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.zuul.netty.server.http2.DummyChannelHandler; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; class MaxInboundConnectionsHandlerTest { private Registry registry = new DefaultRegistry(); private String listener = "test-throttled"; private Id counterId; @BeforeEach void setup() { counterId = registry.createId("server.connections.throttled").withTags("id", listener); } @Test void verifyPassportStateAndAttrs() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(new DummyChannelHandler()); channel.pipeline().addLast(new MaxInboundConnectionsHandler(registry, listener, 1)); // Fire twice to increment current conns. count channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); final Counter throttledCount = (Counter) registry.get(counterId); assertEquals(1, throttledCount.count()); assertEquals( PassportState.SERVER_CH_THROTTLING, CurrentPassport.fromChannel(channel).getState()); assertTrue(channel.attr(MaxInboundConnectionsHandler.ATTR_CH_THROTTLED).get()); } }
6,153
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/StripUntrustedProxyHeadersHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.proxyprotocol; import com.google.common.collect.ImmutableList; import com.netflix.netty.common.proxyprotocol.StripUntrustedProxyHeadersHandler.AllowWhen; import com.netflix.netty.common.ssl.SslHandshakeInfo; import com.netflix.zuul.netty.server.ssl.SslHandshakeInfoHandler; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.ssl.ClientAuth; import io.netty.util.AttributeKey; import io.netty.util.DefaultAttributeMap; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Strip Untrusted Proxy Headers Handler Test * * @author Arthur Gonigberg * @since May 27, 2020 */ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) class StripUntrustedProxyHeadersHandlerTest { @Mock private ChannelHandlerContext channelHandlerContext; @Mock private HttpRequest msg; private HttpHeaders headers; @Mock private Channel channel; @Mock private SslHandshakeInfo sslHandshakeInfo; @BeforeEach void before() { when(channelHandlerContext.channel()).thenReturn(channel); DefaultAttributeMap attributeMap = new DefaultAttributeMap(); attributeMap.attr(SslHandshakeInfoHandler.ATTR_SSL_INFO).set(sslHandshakeInfo); when(channel.attr(any())).thenAnswer(arg -> attributeMap.attr((AttributeKey) arg.getArguments()[0])); headers = new DefaultHttpHeaders(); when(msg.headers()).thenReturn(headers); headers.add(HttpHeaderNames.HOST, "netflix.com"); } @Test void allow_never() throws Exception { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.NEVER); stripHandler.channelRead(channelHandlerContext, msg); verify(stripHandler).stripXFFHeaders(any()); } @Test void allow_always() throws Exception { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.ALWAYS); stripHandler.channelRead(channelHandlerContext, msg); verify(stripHandler, never()).stripXFFHeaders(any()); verify(stripHandler).checkBlacklist(any(), any()); } @Test void allow_mtls_noCert() throws Exception { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); stripHandler.channelRead(channelHandlerContext, msg); verify(stripHandler).stripXFFHeaders(any()); } @Test void allow_mtls_cert() throws Exception { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); when(sslHandshakeInfo.getClientAuthRequirement()).thenReturn(ClientAuth.REQUIRE); stripHandler.channelRead(channelHandlerContext, msg); verify(stripHandler, never()).stripXFFHeaders(any()); verify(stripHandler).checkBlacklist(any(), any()); } @Test void blacklist_noMatch() { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); stripHandler.checkBlacklist(msg, ImmutableList.of("netflix.net")); verify(stripHandler, never()).stripXFFHeaders(any()); } @Test void blacklist_match() { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); stripHandler.checkBlacklist(msg, ImmutableList.of("netflix.com")); verify(stripHandler).stripXFFHeaders(any()); } @Test void blacklist_match_casing() { StripUntrustedProxyHeadersHandler stripHandler = getHandler(AllowWhen.MUTUAL_SSL_AUTH); stripHandler.checkBlacklist(msg, ImmutableList.of("NeTfLiX.cOm")); verify(stripHandler).stripXFFHeaders(any()); } @Test 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")); } private StripUntrustedProxyHeadersHandler getHandler(AllowWhen allowWhen) { return spy(new StripUntrustedProxyHeadersHandler(allowWhen)); } }
6,154
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/ElbProxyProtocolChannelHandlerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.proxyprotocol; import com.google.common.net.InetAddresses; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.haproxy.HAProxyMessage; import io.netty.handler.codec.haproxy.HAProxyProtocolVersion; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) class ElbProxyProtocolChannelHandlerTest { private Registry registry; @BeforeEach void setup() { registry = new DefaultRegistry(); } @Test void noProxy() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, false)); ByteBuf buf = Unpooled.wrappedBuffer( "PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertEquals(dropped, buf); buf.release(); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context("HAProxyMessageChannelHandler")); assertNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); assertNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } @Test void extraDataForwarded() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf = Unpooled.wrappedBuffer( "PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\nPOTATO".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object msg = channel.readInbound(); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); ByteBuf readBuf = (ByteBuf) msg; assertEquals("POTATO", new String(ByteBufUtil.getBytes(readBuf), StandardCharsets.US_ASCII)); readBuf.release(); } @Test void passThrough_ProxyProtocolEnabled_nonProxyBytes() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); // Note that the bytes aren't prefixed by PROXY, as required by the spec ByteBuf buf = Unpooled.wrappedBuffer( "TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertEquals(dropped, buf); buf.release(); assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context("HAProxyMessageChannelHandler")); assertNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); assertNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertNull(channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } @Test void incrementCounterWhenPPEnabledButNonHAPMMessage() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); final int port = 7007; channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(port); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); // Note that the bytes aren't prefixed by PROXY, as required by the spec ByteBuf buf = Unpooled.wrappedBuffer( "TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertEquals(dropped, buf); buf.release(); final Counter counter = registry.counter( "zuul.hapm.decode", "success", "false", "port", String.valueOf(port), "needs_more_data", "false"); assertEquals(1, counter.count()); } @Disabled @Test void detectsSplitPpv1Message() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf1 = Unpooled.wrappedBuffer("PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); ByteBuf buf2 = Unpooled.wrappedBuffer("192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf2); Object msg = channel.readInbound(); assertTrue(msg instanceof HAProxyMessage); buf1.release(); buf2.release(); ((HAProxyMessage) msg).release(); // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); } @Test void tracksSplitMessage() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); int port = 7007; channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(port); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf1 = Unpooled.wrappedBuffer("PROXY TCP4".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf1); Object msg = channel.readInbound(); assertEquals(buf1, msg); buf1.release(); // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.class)); Counter counter = registry.counter( "zuul.hapm.decode", "success", "false", "port", String.valueOf(port), "needs_more_data", "true"); assertEquals(1, counter.count()); } @Test void negotiateProxy_ppv1_ipv4() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf = Unpooled.wrappedBuffer( "PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertNull(dropped); // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNull(channel.pipeline().context(HAProxyMessageChannelHandler.class)); assertEquals( HAProxyProtocolVersion.V1, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. assertNotNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertEquals( "124.123.111.111", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertEquals( "192.168.0.1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } @Test void negotiateProxy_ppv1_ipv6() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf = Unpooled.wrappedBuffer("PROXY TCP6 ::1 ::2 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertNull(dropped); // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertEquals( HAProxyProtocolVersion.V1, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. assertNotNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertEquals( "::2", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("::2"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertEquals( "::1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("::1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } @Test void negotiateProxy_ppv2_ipv4() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(7007); channel.pipeline() .addLast(ElbProxyProtocolChannelHandler.NAME, new ElbProxyProtocolChannelHandler(registry, true)); ByteBuf buf = Unpooled.wrappedBuffer(new byte[] { 0x0D, 0x0A, 0x0D, 0x0A, 0x00, 0x0D, 0x0A, 0x51, 0x55, 0x49, 0x54, 0x0A, 0x21, 0x11, 0x00, 0x0C, (byte) 0xC0, (byte) 0xA8, 0x00, 0x01, 0x7C, 0x7B, 0x6F, 0x6F, 0x27, 0x18, 0x01, (byte) 0xbb }); channel.writeInbound(buf); Object dropped = channel.readInbound(); assertNull(dropped); // The handler should remove itself. assertNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertEquals( HAProxyProtocolVersion.V2, channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_VERSION).get()); // TODO(carl-mastrangelo): this check is in place, but it should be removed. The message is not properly GC'd // in later versions of netty. assertNotNull( channel.attr(HAProxyMessageChannelHandler.ATTR_HAPROXY_MESSAGE).get()); assertEquals( "124.123.111.111", channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("124.123.111.111"), 443), channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).get()); assertEquals( "192.168.0.1", channel.attr(SourceAddressChannelHandler.ATTR_SOURCE_ADDRESS).get()); assertEquals( new InetSocketAddress(InetAddresses.forString("192.168.0.1"), 10008), channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get()); } }
6,155
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common
Create_ds/zuul/zuul-core/src/test/java/com/netflix/netty/common/proxyprotocol/HAProxyMessageChannelHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.netty.common.proxyprotocol; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.haproxy.HAProxyMessageDecoder; import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class HAProxyMessageChannelHandlerTest { @Test void setClientDestPortForHAPM() { EmbeddedChannel channel = new EmbeddedChannel(); // This is normally done by Server. channel.attr(Server.CONN_DIMENSIONS).set(Attrs.newInstance()); // This is to emulate `ElbProxyProtocolChannelHandler` channel.pipeline() .addLast(HAProxyMessageDecoder.class.getSimpleName(), new HAProxyMessageDecoder()) .addLast(HAProxyMessageChannelHandler.class.getSimpleName(), new HAProxyMessageChannelHandler()); ByteBuf buf = Unpooled.wrappedBuffer( "PROXY TCP4 192.168.0.1 124.123.111.111 10008 443\r\n".getBytes(StandardCharsets.US_ASCII)); channel.writeInbound(buf); Object result = channel.readInbound(); assertNull(result); InetSocketAddress destAddress = channel.attr( SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) .get(); InetSocketAddress srcAddress = (InetSocketAddress) channel.attr(SourceAddressChannelHandler.ATTR_REMOTE_ADDR).get(); assertEquals("124.123.111.111", destAddress.getHostString()); assertEquals(443, destAddress.getPort()); assertEquals("192.168.0.1", srcAddress.getHostString()); assertEquals(10008, srcAddress.getPort()); Attrs attrs = channel.attr(Server.CONN_DIMENSIONS).get(); Integer port = HAProxyMessageChannelHandler.HAPM_DEST_PORT.get(attrs); assertEquals(443, port.intValue()); String sourceIpVersion = HAProxyMessageChannelHandler.HAPM_SRC_IP_VERSION.get(attrs); assertEquals("v4", sourceIpVersion); String destIpVersion = HAProxyMessageChannelHandler.HAPM_DEST_IP_VERSION.get(attrs); assertEquals("v4", destIpVersion); } }
6,156
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/DynamicFilterLoaderTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul; import com.netflix.zuul.filters.BaseSyncFilter; import com.netflix.zuul.filters.FilterRegistry; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.MutableFilterRegistry; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.ZuulMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.io.File; import java.util.Collection; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; class DynamicFilterLoaderTest { @Mock private File file; @Mock private DynamicCodeCompiler compiler; private final FilterRegistry registry = new MutableFilterRegistry(); private final FilterFactory filterFactory = new DefaultFilterFactory(); private DynamicFilterLoader loader; private final TestZuulFilter filter = new TestZuulFilter(); @BeforeEach void before() throws Exception { MockitoAnnotations.initMocks(this); loader = new DynamicFilterLoader(registry, compiler, filterFactory); doReturn(TestZuulFilter.class).when(compiler).compile(file); when(file.getAbsolutePath()).thenReturn("/filters/in/SomeFilter.groovy"); } @Test void testGetFilterFromFile() throws Exception { assertTrue(loader.putFilter(file)); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(1, filters.size()); } @Test void testPutFiltersForClasses() throws Exception { loader.putFiltersForClasses(new String[] {TestZuulFilter.class.getName()}); Collection<ZuulFilter<?, ?>> filters = registry.getAllFilters(); assertEquals(1, filters.size()); } @Test 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()); } @Test 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); assertEquals(1, list.size()); ZuulFilter<?, ?> filter = list.iterator().next(); assertTrue(filter != null); assertEquals(FilterType.INBOUND, filter.filterType()); } @Test void testGetFilterFromString() throws Exception { String string = ""; doReturn(TestZuulFilter.class).when(compiler).compile(string, string); ZuulFilter filter = loader.getFilter(string, string); assertNotNull(filter); assertEquals(TestZuulFilter.class, filter.getClass()); // assertTrue(loader.filterInstanceMapSize() == 1); } private static final class TestZuulFilter extends BaseSyncFilter { TestZuulFilter() { super(); } @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(ZuulMessage msg) { return false; } @Override public ZuulMessage apply(ZuulMessage msg) { return null; } } }
6,157
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/StaticFilterLoaderTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul; import com.google.common.collect.ImmutableSet; import com.google.common.truth.Truth; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.http.HttpInboundSyncFilter; import com.netflix.zuul.message.http.HttpRequestMessage; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import java.util.SortedSet; class StaticFilterLoaderTest { private static final FilterFactory factory = new DefaultFilterFactory(); @Test 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); } @Test 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); } @Filter(order = 0, type = FilterType.INBOUND) static class DummyFilter1 extends HttpInboundSyncFilter { @Override public String filterName() { return "Batman"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter(HttpRequestMessage msg) { return true; } @Override public HttpRequestMessage apply(HttpRequestMessage input) { return input; } } @Filter(order = 1, type = FilterType.INBOUND) static class DummyFilter2 extends HttpInboundSyncFilter { @Override public String filterName() { return "Robin"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter(HttpRequestMessage msg) { return true; } @Override public HttpRequestMessage apply(HttpRequestMessage input) { return input; } } @Filter(order = 1, type = FilterType.INBOUND) static class DummyFilter22 extends HttpInboundSyncFilter { @Override public String filterName() { return "Williams"; } @Override public int filterOrder() { return 1; } @Override public boolean shouldFilter(HttpRequestMessage msg) { return true; } @Override public HttpRequestMessage apply(HttpRequestMessage input) { return input; } } }
6,158
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/FilterFileManagerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.junit.jupiter.MockitoExtension; import java.io.File; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Tests for {@link FilterFileManager}. */ @ExtendWith(MockitoExtension.class) class FilterFileManagerTest { @Mock private File nonGroovyFile; @Mock private File groovyFile; @Mock private File directory; @Mock private FilterLoader filterLoader; @BeforeEach void before() { MockitoAnnotations.initMocks(this); } @Test void testFileManagerInit() throws Exception { FilterFileManager.FilterFileManagerConfig config = new FilterFileManager.FilterFileManagerConfig( new String[] {"test", "test1"}, new String[] {"com.netflix.blah.SomeFilter"}, 1, (dir, name) -> false); FilterFileManager manager = new FilterFileManager(config, filterLoader); manager = spy(manager); doNothing().when(manager).manageFiles(); manager.init(); verify(manager, atLeast(1)).manageFiles(); verify(manager, times(1)).startPoller(); assertNotNull(manager.poller); } }
6,159
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/AttrsTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul; import com.google.common.truth.Truth; import com.netflix.zuul.Attrs.Key; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; class AttrsTest { @Test void keysAreUnique() { Attrs attrs = Attrs.newInstance(); Key<String> key1 = Attrs.newKey("foo"); key1.put(attrs, "bar"); Key<String> key2 = Attrs.newKey("foo"); key2.put(attrs, "baz"); Truth.assertThat(attrs.keySet()).containsExactly(key1, key2); } @Test void newKeyFailsOnNull() { assertThrows(NullPointerException.class, () -> Attrs.newKey(null)); } @Test void attrsPutFailsOnNull() { Attrs attrs = Attrs.newInstance(); Key<String> key = Attrs.newKey("foo"); assertThrows(NullPointerException.class, () -> key.put(attrs, null)); } @Test void attrsPutReplacesOld() { Attrs attrs = Attrs.newInstance(); Key<String> key = Attrs.newKey("foo"); key.put(attrs, "bar"); key.put(attrs, "baz"); assertEquals("baz", key.get(attrs)); Truth.assertThat(attrs.keySet()).containsExactly(key); } @Test void getReturnsNull() { Attrs attrs = Attrs.newInstance(); Key<String> key = Attrs.newKey("foo"); assertNull(key.get(attrs)); } @Test void getOrDefault_picksDefault() { Attrs attrs = Attrs.newInstance(); Key<String> key = Attrs.newKey("foo"); assertEquals("bar", key.getOrDefault(attrs, "bar")); } @Test void getOrDefault_failsOnNullDefault() { Attrs attrs = Attrs.newInstance(); Key<String> key = Attrs.newKey("foo"); key.put(attrs, "bar"); assertThrows(NullPointerException.class, () -> key.getOrDefault(attrs, null)); } }
6,160
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/filters/BaseFilterTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters; import com.netflix.zuul.message.ZuulMessage; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * Tests for {@link BaseFilter}. Currently named BaseFilter2Test as there is an existing * class named BaseFilterTest. */ class BaseFilterTest { @Mock private BaseFilter f1; @Mock private BaseFilter f2; @Mock private ZuulMessage req; @BeforeEach void before() { MockitoAnnotations.initMocks(this); } @Test void testShouldFilter() { class TestZuulFilter extends BaseSyncFilter { @Override public int filterOrder() { return 0; } @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public boolean shouldFilter(ZuulMessage req) { return false; } @Override public ZuulMessage apply(ZuulMessage req) { return null; } } TestZuulFilter tf1 = spy(new TestZuulFilter()); TestZuulFilter tf2 = spy(new TestZuulFilter()); when(tf1.shouldFilter(req)).thenReturn(true); when(tf2.shouldFilter(req)).thenReturn(false); } }
6,161
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/filters/common/GZipResponseFilterTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.common; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpHeaderNames; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.zip.GZIPInputStream; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class GZipResponseFilterTest { private final SessionContext context = new SessionContext(); private final Headers originalRequestHeaders = new Headers(); @Mock private HttpRequestMessage request; @Mock private HttpRequestMessage originalRequest; GZipResponseFilter filter; HttpResponseMessage response; @BeforeEach void setup() { // when(request.getContext()).thenReturn(context); when(originalRequest.getHeaders()).thenReturn(originalRequestHeaders); filter = Mockito.spy(new GZipResponseFilter()); response = new HttpResponseMessageImpl(context, request, 99); response.getHeaders().set(HttpHeaderNames.CONTENT_TYPE, "text/html"); when(response.getInboundRequest()).thenReturn(originalRequest); } @Test void prepareResponseBody_NeedsGZipping() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); // Force GZip for small response response.setHasBody(true); assertTrue(filter.shouldFilter(response)); final HttpResponseMessage result = filter.apply(response); final HttpContent hc1 = filter.processContentChunk( response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); final HttpContent hc2 = filter.processContentChunk(response, new DefaultLastHttpContent()); final byte[] body = new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; final int hc1Len = hc1.content().readableBytes(); final int hc2Len = hc2.content().readableBytes(); hc1.content().readBytes(body, 0, hc1Len); hc2.content().readBytes(body, hc1Len, hc2Len); String bodyStr; // Check body is a gzipped version of the origin body. try (ByteArrayInputStream bais = new ByteArrayInputStream(body); GZIPInputStream gzis = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { int b; while ((b = gzis.read()) != -1) { baos.write(b); } bodyStr = baos.toString("UTF-8"); } assertEquals("blah", bodyStr); assertEquals("gzip", result.getHeaders().getFirst("Content-Encoding")); // Check Content-Length header has been removed assertEquals(0, result.getHeaders().getAll("Content-Length").size()); } @Test void prepareResponseBody_NeedsGZipping_gzipDeflate() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip,deflate"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); Mockito.when(filter.isRightSizeForGzip(response)).thenReturn(true); // Force GZip for small response response.setHasBody(true); assertTrue(filter.shouldFilter(response)); final HttpResponseMessage result = filter.apply(response); final HttpContent hc1 = filter.processContentChunk( response, new DefaultHttpContent(Unpooled.wrappedBuffer(originBody)).retain()); final HttpContent hc2 = filter.processContentChunk(response, new DefaultLastHttpContent()); final byte[] body = new byte[hc1.content().readableBytes() + hc2.content().readableBytes()]; final int hc1Len = hc1.content().readableBytes(); final int hc2Len = hc2.content().readableBytes(); hc1.content().readBytes(body, 0, hc1Len); hc2.content().readBytes(body, hc1Len, hc2Len); String bodyStr; // Check body is a gzipped version of the origin body. try (ByteArrayInputStream bais = new ByteArrayInputStream(body); GZIPInputStream gzis = new GZIPInputStream(bais); ByteArrayOutputStream baos = new ByteArrayOutputStream()) { int b; while ((b = gzis.read()) != -1) { baos.write(b); } bodyStr = baos.toString("UTF-8"); } assertEquals("blah", bodyStr); assertEquals("gzip", result.getHeaders().getFirst("Content-Encoding")); // Check Content-Length header has been removed assertEquals(0, result.getHeaders().getAll("Content-Length").size()); } @Test void prepareResponseBody_alreadyZipped() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip,deflate"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); response.getHeaders().set("Content-Type", "application/json"); response.getHeaders().set("Content-Encoding", "gzip"); response.setHasBody(true); assertFalse(filter.shouldFilter(response)); } @Test void prepareResponseBody_alreadyDeflated() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip,deflate"); byte[] originBody = "blah".getBytes(); response.getHeaders().set("Content-Length", Integer.toString(originBody.length)); response.getHeaders().set("Content-Type", "application/json"); response.getHeaders().set("Content-Encoding", "deflate"); response.setHasBody(true); assertFalse(filter.shouldFilter(response)); } @Test 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 void prepareChunkedEncodedResponseBody_NeedsGZipping() throws Exception { originalRequestHeaders.set("Accept-Encoding", "gzip"); response.getHeaders().set("Transfer-Encoding", "chunked"); response.setHasBody(true); assertTrue(filter.shouldFilter(response)); } }
6,162
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/filters
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/filters/endpoint/ProxyEndpointTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.filters.endpoint; import com.netflix.appinfo.InstanceInfo; import com.netflix.spectator.api.Spectator; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.netty.NettyRequestAttemptFactory; import com.netflix.zuul.netty.server.MethodBinding; import com.netflix.zuul.origins.BasicNettyOriginManager; import com.netflix.zuul.passport.CurrentPassport; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.local.LocalAddress; import io.netty.handler.codec.http.HttpResponse; import io.netty.handler.codec.http.HttpResponseStatus; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class ProxyEndpointTest { ProxyEndpoint proxyEndpoint; HttpRequestMessage request; @BeforeEach void setup() { ChannelHandlerContext chc = mock(ChannelHandlerContext.class); NettyRequestAttemptFactory attemptFactory = mock(NettyRequestAttemptFactory.class); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", null, null, "192.168.0.2", "https", 7002, "localhost", new LocalAddress("777"), false); request.setBody("Hello There".getBytes()); request.getContext() .set(CommonContextKeys.ORIGIN_MANAGER, new BasicNettyOriginManager(Spectator.globalRegistry())); request.getContext().setRouteVIP("some-vip"); request.getContext().put(CommonContextKeys.PASSPORT, CurrentPassport.create()); proxyEndpoint = new ProxyEndpoint(request, chc, null, MethodBinding.NO_OP_BINDING, attemptFactory); } @Test void testRetryWillResetBodyReader() { assertEquals("Hello There", new String(request.getBody())); // move the body readerIndex to the end to mimic nettys behavior after writing to the origin channel request.getBodyContents() .forEach((b) -> b.content().readerIndex(b.content().capacity())); HttpResponse response = mock(HttpResponse.class); when(response.status()).thenReturn(new HttpResponseStatus(503, "Retry")); InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder() .setAppName("app") .setHostName("localhost") .setPort(443) .build(); DiscoveryResult discoveryResult = DiscoveryResult.from(instanceInfo, true); // when retrying a response, the request body reader should have it's indexes reset proxyEndpoint.handleOriginNonSuccessResponse(response, discoveryResult); assertEquals("Hello There", new String(request.getBody())); } }
6,163
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/context/SessionContextTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.context; import com.google.common.truth.Truth; import com.netflix.zuul.context.SessionContext.Key; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; @ExtendWith(MockitoExtension.class) class SessionContextTest { @Test void testBoolean() { SessionContext context = new SessionContext(); assertEquals(Boolean.FALSE, context.getBoolean("boolean_test")); assertEquals(true, context.getBoolean("boolean_test", true)); } @Test void keysAreUnique() { SessionContext context = new SessionContext(); Key<String> key1 = SessionContext.newKey("foo"); context.put(key1, "bar"); Key<String> key2 = SessionContext.newKey("foo"); context.put(key2, "baz"); Truth.assertThat(context.keys()).containsExactly(key1, key2); } @Test void newKeyFailsOnNull() { assertThrows(NullPointerException.class, () -> SessionContext.newKey(null)); } @Test void putFailsOnNull() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); assertThrows(NullPointerException.class, () -> context.put(key, null)); } @Test void putReplacesOld() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); context.put(key, "bar"); context.put(key, "baz"); assertEquals("baz", context.get(key)); Truth.assertThat(context.keys()).containsExactly(key); } @Test void getReturnsNull() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); assertNull(context.get(key)); } @Test void getOrDefault_picksDefault() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); assertEquals("bar", context.getOrDefault(key, "bar")); } @Test void getOrDefault_failsOnNullDefault() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); context.put(key, "bar"); assertThrows(NullPointerException.class, () -> context.getOrDefault(key, null)); } @Test void remove() { SessionContext context = new SessionContext(); Key<String> key = SessionContext.newKey("foo"); context.put(key, "bar"); Truth.assertThat(context.get(key)).isEqualTo("bar"); String val = context.remove(key); Truth.assertThat(context.get(key)).isNull(); Truth.assertThat(val).isEqualTo("bar"); } }
6,164
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/context/DebugTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.context; import com.google.common.truth.Truth; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import com.netflix.zuul.message.util.HttpRequestBuilder; import io.netty.handler.codec.http.HttpMethod; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; import static com.netflix.zuul.context.Debug.addRequestDebug; import static com.netflix.zuul.context.Debug.addRoutingDebug; import static com.netflix.zuul.context.Debug.debugRequest; import static com.netflix.zuul.context.Debug.debugRouting; import static com.netflix.zuul.context.Debug.getRequestDebug; import static com.netflix.zuul.context.Debug.getRoutingDebug; import static com.netflix.zuul.context.Debug.setDebugRequest; import static com.netflix.zuul.context.Debug.setDebugRouting; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class DebugTest { private SessionContext ctx; private Headers headers; private HttpQueryParams params; private HttpRequestMessage request; private HttpResponseMessage response; @BeforeEach void setup() { ctx = new SessionContext(); headers = new Headers(); headers.add("lah", "deda"); params = new HttpQueryParams(); params.add("k1", "v1"); request = new HttpRequestBuilder(ctx) .withMethod(HttpMethod.POST) .withUri("/some/where") .withHeaders(headers) .withQueryParams(params) .build(); request.setBodyAsText("some text"); request.storeInboundRequest(); response = new HttpResponseMessageImpl(ctx, headers, request, 200); response.setBodyAsText("response text"); } @Test void testRequestDebug() { assertFalse(debugRouting(ctx)); assertFalse(debugRequest(ctx)); setDebugRouting(ctx, true); setDebugRequest(ctx, true); assertTrue(debugRouting(ctx)); assertTrue(debugRequest(ctx)); addRoutingDebug(ctx, "test1"); assertTrue(getRoutingDebug(ctx).contains("test1")); addRequestDebug(ctx, "test2"); assertTrue(getRequestDebug(ctx).contains("test2")); } @Test void testWriteInboundRequestDebug() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(true); Debug.writeDebugRequest(ctx, request, true).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", "REQUEST_INBOUND:: > HDR: Content-Length:13", "REQUEST_INBOUND:: > HDR: lah:deda"); } @Test void testWriteOutboundRequestDebug() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(true); Debug.writeDebugRequest(ctx, request, false).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "REQUEST_OUTBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", "REQUEST_OUTBOUND:: > HDR: Content-Length:13", "REQUEST_OUTBOUND:: > HDR: lah:deda"); } @Test void testWriteRequestDebug_WithBody() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(false); Debug.writeDebugRequest(ctx, request, true).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "REQUEST_INBOUND:: > LINE: POST /some/where?k1=v1 HTTP/1.1", "REQUEST_INBOUND:: > HDR: Content-Length:13", "REQUEST_INBOUND:: > HDR: lah:deda", "REQUEST_INBOUND:: > BODY: some text"); } @Test void testWriteInboundResponseDebug() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(true); Debug.writeDebugResponse(ctx, response, true).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "RESPONSE_INBOUND:: < STATUS: 200", "RESPONSE_INBOUND:: < HDR: Content-Length:13", "RESPONSE_INBOUND:: < HDR: lah:deda"); } @Test void testWriteOutboundResponseDebug() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(true); Debug.writeDebugResponse(ctx, response, false).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "RESPONSE_OUTBOUND:: < STATUS: 200", "RESPONSE_OUTBOUND:: < HDR: Content-Length:13", "RESPONSE_OUTBOUND:: < HDR: lah:deda"); } @Test void testWriteResponseDebug_WithBody() { ctx.setDebugRequest(true); ctx.setDebugRequestHeadersOnly(false); Debug.writeDebugResponse(ctx, response, true).toBlocking().single(); List<String> debugLines = getRequestDebug(ctx); Truth.assertThat(debugLines) .containsExactly( "RESPONSE_INBOUND:: < STATUS: 200", "RESPONSE_INBOUND:: < HDR: Content-Length:13", "RESPONSE_INBOUND:: < HDR: lah:deda", "RESPONSE_INBOUND:: < BODY: response text"); } @Test void testNoCMEWhenComparingContexts() { final SessionContext context = new SessionContext(); final SessionContext copy = new SessionContext(); context.set("foo", "bar"); Debug.compareContextState("testfilter", context, copy); } }
6,165
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/util/JsonUtilityTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.util; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit tests for {@link JsonUtility}. */ class JsonUtilityTest { // I'm using LinkedHashMap in the testing so I get consistent ordering for the expected results @Test void testSimpleOne() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\"}"; assertEquals(expected, json); } @Test void testSimpleTwo() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); jsonData.put("myKey2", "myValue2"); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\",\"myKey2\":\"myValue2\"}"; assertEquals(expected, json); } @Test void testNestedMapOne() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); Map<String, Object> jsonData2 = new LinkedHashMap<String, Object>(); jsonData2.put("myNestedKey", "myNestedValue"); jsonData.put("myNestedData", jsonData2); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\",\"myNestedData\":{\"myNestedKey\":\"myNestedValue\"}}"; assertEquals(expected, json); } @Test void testNestedMapTwo() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); Map<String, Object> jsonData2 = new LinkedHashMap<String, Object>(); jsonData2.put("myNestedKey", "myNestedValue"); jsonData2.put("myNestedKey2", "myNestedValue2"); jsonData.put("myNestedData", jsonData2); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\",\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\"}}"; assertEquals(expected, json); } @Test void testArrayOne() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); int[] numbers = {1, 2, 3, 4}; jsonData.put("myKey", numbers); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":[1,2,3,4]}"; assertEquals(expected, json); } @Test void testArrayTwo() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); String[] values = {"one", "two", "three", "four"}; jsonData.put("myKey", values); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":[\"one\",\"two\",\"three\",\"four\"]}"; assertEquals(expected, json); } @Test void testCollectionOne() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); ArrayList<String> values = new ArrayList<String>(); values.add("one"); values.add("two"); values.add("three"); values.add("four"); jsonData.put("myKey", values); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":[\"one\",\"two\",\"three\",\"four\"]}"; assertEquals(expected, json); } @Test void testMapAndList() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); jsonData.put("myKey", "myValue"); int[] numbers = {1, 2, 3, 4}; jsonData.put("myNumbers", numbers); Map<String, Object> jsonData2 = new LinkedHashMap<String, Object>(); jsonData2.put("myNestedKey", "myNestedValue"); jsonData2.put("myNestedKey2", "myNestedValue2"); String[] values = {"one", "two", "three", "four"}; jsonData2.put("myStringNumbers", values); jsonData.put("myNestedData", jsonData2); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"myKey\":\"myValue\",\"myNumbers\":[1,2,3,4],\"myNestedData\":{\"myNestedKey\":\"myNestedValue\",\"myNestedKey2\":\"myNestedValue2\",\"myStringNumbers\":[\"one\",\"two\",\"three\",\"four\"]}}"; assertEquals(expected, json); } @Test void testArrayOfMaps() { Map<String, Object> jsonData = new LinkedHashMap<String, Object>(); ArrayList<Map<String, Object>> messages = new ArrayList<Map<String, Object>>(); Map<String, Object> message1 = new LinkedHashMap<String, Object>(); message1.put("a", "valueA1"); message1.put("b", "valueB1"); messages.add(message1); Map<String, Object> message2 = new LinkedHashMap<String, Object>(); message2.put("a", "valueA2"); message2.put("b", "valueB2"); messages.add(message2); jsonData.put("messages", messages); String json = JsonUtility.jsonFromMap(jsonData); String expected = "{\"messages\":[{\"a\":\"valueA1\",\"b\":\"valueB1\"},{\"a\":\"valueA2\",\"b\":\"valueB2\"}]}"; assertEquals(expected, json); } }
6,166
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/util/HttpUtilsTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.util; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.ZuulMessageImpl; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link HttpUtils}. */ class HttpUtilsTest { @Test void detectsGzip() { assertTrue(HttpUtils.isCompressed("gzip")); } @Test void detectsDeflate() { assertTrue(HttpUtils.isCompressed("deflate")); } @Test void detectsCompress() { assertTrue(HttpUtils.isCompressed("compress")); } @Test void detectsBR() { assertTrue(HttpUtils.isCompressed("br")); } @Test void detectsNonGzip() { assertFalse(HttpUtils.isCompressed("identity")); } @Test void detectsGzipAmongOtherEncodings() { assertTrue(HttpUtils.isCompressed("gzip, deflate")); } @Test void acceptsGzip() { Headers headers = new Headers(); headers.add("Accept-Encoding", "gzip, deflate"); assertTrue(HttpUtils.acceptsGzip(headers)); } @Test void acceptsGzip_only() { Headers headers = new Headers(); headers.add("Accept-Encoding", "deflate"); assertFalse(HttpUtils.acceptsGzip(headers)); } @Test 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)); } @Test void getBodySizeIfKnown_returnsContentLengthValue() { SessionContext context = new SessionContext(); Headers headers = new Headers(); headers.add(com.netflix.zuul.message.http.HttpHeaderNames.CONTENT_LENGTH, "23450"); ZuulMessage msg = new ZuulMessageImpl(context, headers); assertThat(HttpUtils.getBodySizeIfKnown(msg)).isEqualTo(Integer.valueOf(23450)); } @Test void getBodySizeIfKnown_returnsResponseBodySize() { SessionContext context = new SessionContext(); Headers headers = new Headers(); HttpQueryParams queryParams = new HttpQueryParams(); HttpRequestMessage request = new HttpRequestMessageImpl( context, "http", "GET", "/path", queryParams, headers, "127.0.0.1", "scheme", 6666, "server-name"); request.storeInboundRequest(); HttpResponseMessage response = new HttpResponseMessageImpl(context, request, 200); response.setBodyAsText("Hello world"); assertThat(HttpUtils.getBodySizeIfKnown(response)).isEqualTo(Integer.valueOf(11)); } @Test void getBodySizeIfKnown_returnsNull() { SessionContext context = new SessionContext(); Headers headers = new Headers(); ZuulMessage msg = new ZuulMessageImpl(context, headers); assertThat(HttpUtils.getBodySizeIfKnown(msg)).isNull(); } }
6,167
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/util/VipUtilsTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.util; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; /** * Unit tests for {@link VipUtils}. */ class VipUtilsTest { @Test void testGetVIPPrefix() { assertThrows(NullPointerException.class, () -> { 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); }); } @Test void testExtractAppNameFromVIP() { assertThrows(NullPointerException.class, () -> { 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); }); } }
6,168
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message/ZuulMessageImplTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message; import com.netflix.zuul.context.SessionContext; import io.netty.buffer.Unpooled; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpContent; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) class ZuulMessageImplTest { private static final String TEXT1 = "Hello World!"; private static final String TEXT2 = "Goodbye World!"; @Test 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()); // Verify that values of the 2 messages are decoupled. msg1.getHeaders().set("k1", "v_new"); msg1.getContext().set("k1", "v_new"); assertEquals("v1", msg2.getHeaders().getFirst("k1")); assertEquals("v1", msg2.getContext().get("k1")); } @Test void testBufferBody2GetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("Hello ".getBytes()))); msg.bufferBodyContents(new DefaultLastHttpContent(Unpooled.copiedBuffer("World!".getBytes()))); final String body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals("Hello World!", body); assertEquals(0, msg.getHeaders().getAll("Content-Length").size()); } @Test void testBufferBody3GetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("Hello ".getBytes()))); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("World!".getBytes()))); msg.bufferBodyContents(new DefaultLastHttpContent()); final String body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals("Hello World!", body); assertEquals(0, msg.getHeaders().getAll("Content-Length").size()); } @Test void testBufferBody3GetBodyAsText() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("Hello ".getBytes()))); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("World!".getBytes()))); msg.bufferBodyContents(new DefaultLastHttpContent()); final String body = msg.getBodyAsText(); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals("Hello World!", body); assertEquals(0, msg.getHeaders().getAll("Content-Length").size()); } @Test void testSetBodyGetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.setBody(TEXT1.getBytes()); final String body = new String(msg.getBody()); assertEquals(TEXT1, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT1.length()), msg.getHeaders().getFirst("Content-Length")); } @Test void testSetBodyAsTextGetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.setBodyAsText(TEXT1); final String body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT1, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT1.length()), msg.getHeaders().getFirst("Content-Length")); } @Test void testSetBodyAsTextGetBodyAsText() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.setBodyAsText(TEXT1); final String body = msg.getBodyAsText(); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT1, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT1.length()), msg.getHeaders().getFirst("Content-Length")); } @Test void testMultiSetBodyAsTextGetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.setBodyAsText(TEXT1); String body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT1, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT1.length()), msg.getHeaders().getFirst("Content-Length")); msg.setBodyAsText(TEXT2); body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT2, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT2.length()), msg.getHeaders().getFirst("Content-Length")); } @Test void testMultiSetBodyGetBody() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.setBody(TEXT1.getBytes()); String body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT1, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT1.length()), msg.getHeaders().getFirst("Content-Length")); msg.setBody(TEXT2.getBytes()); body = new String(msg.getBody()); assertTrue(msg.hasBody()); assertTrue(msg.hasCompleteBody()); assertEquals(TEXT2, body); assertEquals(1, msg.getHeaders().getAll("Content-Length").size()); assertEquals(String.valueOf(TEXT2.length()), msg.getHeaders().getFirst("Content-Length")); } @Test void testResettingBodyReaderIndex() { final ZuulMessage msg = new ZuulMessageImpl(new SessionContext(), new Headers()); msg.bufferBodyContents(new DefaultHttpContent(Unpooled.copiedBuffer("Hello ".getBytes()))); msg.bufferBodyContents(new DefaultLastHttpContent(Unpooled.copiedBuffer("World!".getBytes()))); // replicate what happens in nettys tls channel writer which moves the reader index on the contained ByteBuf for (HttpContent c : msg.getBodyContents()) { c.content().readerIndex(c.content().capacity()); } assertArrayEquals(new byte[0], msg.getBody(), "body should be empty as readerIndex at end of buffers"); msg.resetBodyReader(); assertEquals("Hello World!", new String(msg.getBody())); } }
6,169
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message/HeadersTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message; import com.google.common.truth.Truth; import com.netflix.zuul.exception.ZuulException; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link Headers}. */ class HeadersTest { @Test void copyOf() { Headers headers = new Headers(); headers.set("Content-Length", "5"); Headers headers2 = Headers.copyOf(headers); headers2.add("Via", "duct"); Truth.assertThat(headers.getAll("Via")).isEmpty(); Truth.assertThat(headers2.size()).isEqualTo(2); Truth.assertThat(headers2.getAll("Content-Length")).containsExactly("5"); } @Test void getFirst_normalizesName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst("cOOkIE")).isEqualTo("this=that"); } @Test void getFirst_headerName_normalizesName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst(new HeaderName("cOOkIE"))).isEqualTo("this=that"); } @Test void getFirst_returnsNull() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst("Date")).isNull(); } @Test void getFirst_headerName_returnsNull() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst(new HeaderName("Date"))).isNull(); } @Test void getFirst_returnsDefault() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst("Date", "tuesday")).isEqualTo("tuesday"); } @Test void getFirst_headerName_returnsDefault() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getFirst(new HeaderName("Date"), "tuesday")).isEqualTo("tuesday"); } @Test void forEachNormalised() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=Frazzle"); Map<String, List<String>> result = new LinkedHashMap<>(); headers.forEachNormalised((k, v) -> result.computeIfAbsent(k, discard -> new ArrayList<>()).add(v)); Truth.assertThat(result) .containsExactly( "via", Collections.singletonList("duct"), "cookie", Arrays.asList("this=that", "frizzle=Frazzle")) .inOrder(); } @Test void getAll() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getAll("CookiE")) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void getAll_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Truth.assertThat(headers.getAll(new HeaderName("CookiE"))) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void setClearsExisting() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.set("cookIe", "dilly=dally"); Truth.assertThat(headers.getAll("CookiE")).containsExactly("dilly=dally"); Truth.assertThat(headers.size()).isEqualTo(2); } @Test void setClearsExisting_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.set(new HeaderName("cookIe"), "dilly=dally"); Truth.assertThat(headers.getAll("CookiE")).containsExactly("dilly=dally"); Truth.assertThat(headers.size()).isEqualTo(2); } @Test void setNullIsEmtpy() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.set("cookIe", null); Truth.assertThat(headers.getAll("CookiE")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setNullIsEmtpy_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.set(new HeaderName("cookIe"), null); Truth.assertThat(headers.getAll("CookiE")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setIfValidNullIsEmtpy() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfValid("cookIe", null); Truth.assertThat(headers.getAll("CookiE")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setIfValidNullIsEmtpy_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfValid(new HeaderName("cookIe"), null); Truth.assertThat(headers.getAll("CookiE")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setIfValidIgnoresInvalidValues() { Headers headers = new Headers(); headers.add("X-Valid-K1", "abc-xyz"); headers.add("X-Valid-K2", "def-xyz"); headers.add("X-Valid-K3", "xyz-xyz"); headers.setIfValid("X-Valid-K1", "abc\r\n-xy\r\nz"); headers.setIfValid("X-Valid-K2", "abc\r-xy\rz"); headers.setIfValid("X-Valid-K3", "abc\n-xy\nz"); Truth.assertThat(headers.getAll("X-Valid-K1")).containsExactly("abc-xyz"); Truth.assertThat(headers.getAll("X-Valid-K2")).containsExactly("def-xyz"); Truth.assertThat(headers.getAll("X-Valid-K3")).containsExactly("xyz-xyz"); Truth.assertThat(headers.size()).isEqualTo(3); } @Test void setIfValidIgnoresInvalidValues_headerName() { Headers headers = new Headers(); headers.add("X-Valid-K1", "abc-xyz"); headers.add("X-Valid-K2", "def-xyz"); headers.add("X-Valid-K3", "xyz-xyz"); headers.setIfValid(new HeaderName("X-Valid-K1"), "abc\r\n-xy\r\nz"); headers.setIfValid(new HeaderName("X-Valid-K2"), "abc\r-xy\rz"); headers.setIfValid(new HeaderName("X-Valid-K3"), "abc\n-xy\nz"); Truth.assertThat(headers.getAll("X-Valid-K1")).containsExactly("abc-xyz"); Truth.assertThat(headers.getAll("X-Valid-K2")).containsExactly("def-xyz"); Truth.assertThat(headers.getAll("X-Valid-K3")).containsExactly("xyz-xyz"); Truth.assertThat(headers.size()).isEqualTo(3); } @Test void setIfValidIgnoresInvalidKey() { Headers headers = new Headers(); headers.add("X-Valid-K1", "abc-xyz"); headers.setIfValid("X-K\r\ney-1", "abc-def"); headers.setIfValid("X-K\ney-2", "def-xyz"); headers.setIfValid("X-K\rey-3", "xyz-xyz"); Truth.assertThat(headers.getAll("X-Valid-K1")).containsExactly("abc-xyz"); Truth.assertThat(headers.getAll("X-K\r\ney-1")).isEmpty(); Truth.assertThat(headers.getAll("X-K\ney-2")).isEmpty(); Truth.assertThat(headers.getAll("X-K\rey-3")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setIfValidIgnoresInvalidKey_headerName() { Headers headers = new Headers(); headers.add("X-Valid-K1", "abc-xyz"); headers.setIfValid(new HeaderName("X-K\r\ney-1"), "abc-def"); headers.setIfValid(new HeaderName("X-K\ney-2"), "def-xyz"); headers.setIfValid(new HeaderName("X-K\rey-3"), "xyz-xyz"); Truth.assertThat(headers.getAll("X-Valid-K1")).containsExactly("abc-xyz"); Truth.assertThat(headers.getAll("X-K\r\ney-1")).isEmpty(); Truth.assertThat(headers.getAll("X-K\ney-2")).isEmpty(); Truth.assertThat(headers.getAll("X-K\rey-3")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void setIfAbsentKeepsExisting() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfAbsent("cookIe", "dilly=dally"); Truth.assertThat(headers.getAll("CookiE")) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void setIfAbsentKeepsExisting_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfAbsent(new HeaderName("cookIe"), "dilly=dally"); Truth.assertThat(headers.getAll("CookiE")) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void setIfAbsentFailsOnNull() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); assertThrows(NullPointerException.class, () -> headers.setIfAbsent("cookIe", null)); } @Test void setIfAbsentFailsOnNull_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); assertThrows(NullPointerException.class, () -> headers.setIfAbsent(new HeaderName("cookIe"), null)); } @Test void setIfAbsent() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfAbsent("X-Netflix-Awesome", "true"); Truth.assertThat(headers.getAll("X-netflix-Awesome")).containsExactly("true"); } @Test void setIfAbsent_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfAbsent(new HeaderName("X-Netflix-Awesome"), "true"); Truth.assertThat(headers.getAll("X-netflix-Awesome")).containsExactly("true"); } @Test void setIfAbsentAndValid() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.setIfAbsentAndValid("X-Netflix-Awesome", "true"); headers.setIfAbsentAndValid("X-Netflix-Awesome", "True"); Truth.assertThat(headers.getAll("X-netflix-Awesome")).containsExactly("true"); Truth.assertThat(headers.size()).isEqualTo(4); } @Test void setIfAbsentAndValidIgnoresInvalidValues() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.setIfAbsentAndValid("X-Invalid-K1", "abc\r\nxy\r\nz"); headers.setIfAbsentAndValid("X-Invalid-K2", "abc\rxy\rz"); headers.setIfAbsentAndValid("X-Invalid-K3", "abc\nxy\nz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); Truth.assertThat(headers.getAll("X-Invalid-K1")).isEmpty(); Truth.assertThat(headers.getAll("X-Invalid-K2")).isEmpty(); Truth.assertThat(headers.getAll("X-Invalid-K3")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void add() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add("via", "con Dios"); Truth.assertThat(headers.getAll("Via")) .containsExactly("duct", "con Dios") .inOrder(); } @Test void add_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add(new HeaderName("via"), "con Dios"); Truth.assertThat(headers.getAll("Via")) .containsExactly("duct", "con Dios") .inOrder(); } @Test void addIfValid() { Headers headers = new Headers(); headers.addIfValid("Via", "duct"); headers.addIfValid("Cookie", "abc=def"); headers.addIfValid("cookie", "uvw=xyz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); Truth.assertThat(headers.getAll("Cookie")) .containsExactly("abc=def", "uvw=xyz") .inOrder(); Truth.assertThat(headers.size()).isEqualTo(3); } @Test void addIfValid_headerName() { Headers headers = new Headers(); headers.addIfValid("Via", "duct"); headers.addIfValid("Cookie", "abc=def"); headers.addIfValid(new HeaderName("cookie"), "uvw=xyz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); Truth.assertThat(headers.getAll("Cookie")) .containsExactly("abc=def", "uvw=xyz") .inOrder(); Truth.assertThat(headers.size()).isEqualTo(3); } @Test void addIfValidIgnoresInvalidValues() { Headers headers = new Headers(); headers.addIfValid("Via", "duct"); headers.addIfValid("Cookie", "abc=def"); headers.addIfValid("X-Invalid-K1", "abc\r\nxy\r\nz"); headers.addIfValid("X-Invalid-K2", "abc\rxy\rz"); headers.addIfValid("X-Invalid-K3", "abc\nxy\nz"); Truth.assertThat(headers.getAll("Via")).containsExactly("duct"); Truth.assertThat(headers.getAll("Cookie")).containsExactly("abc=def"); Truth.assertThat(headers.getAll("X-Invalid-K1")).isEmpty(); Truth.assertThat(headers.getAll("X-Invalid-K2")).isEmpty(); Truth.assertThat(headers.getAll("X-Invalid-K3")).isEmpty(); Truth.assertThat(headers.size()).isEqualTo(2); } @Test void putAll() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); Headers other = new Headers(); other.add("cookie", "a=b"); other.add("via", "com"); headers.putAll(other); // Only check the order per field, not for the entire set. Truth.assertThat(headers.getAll("Via")).containsExactly("duct", "com").inOrder(); Truth.assertThat(headers.getAll("coOkiE")) .containsExactly("this=that", "frizzle=frazzle", "a=b") .inOrder(); Truth.assertThat(headers.size()).isEqualTo(5); } @Test void remove() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add("Soup", "salad"); List<String> removed = headers.remove("Cookie"); Truth.assertThat(headers.getAll("Cookie")).isEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(2); Truth.assertThat(removed) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void remove_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add("Soup", "salad"); List<String> removed = headers.remove(new HeaderName("Cookie")); Truth.assertThat(headers.getAll("Cookie")).isEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(2); Truth.assertThat(removed) .containsExactly("this=that", "frizzle=frazzle") .inOrder(); } @Test void removeEmpty() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add("Soup", "salad"); List<String> removed = headers.remove("Monkey"); Truth.assertThat(headers.getAll("Cookie")).isNotEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(4); Truth.assertThat(removed).isEmpty(); } @Test void removeEmpty_headerName() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("Cookie", "frizzle=frazzle"); headers.add("Soup", "salad"); List<String> removed = headers.remove(new HeaderName("Monkey")); Truth.assertThat(headers.getAll("Cookie")).isNotEmpty(); Truth.assertThat(headers.getAll("Soup")).containsExactly("salad"); Truth.assertThat(headers.size()).isEqualTo(4); Truth.assertThat(removed).isEmpty(); } @Test void removeIf() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("Cookie", "this=that"); headers.add("COOkie", "frizzle=frazzle"); headers.add("Soup", "salad"); boolean removed = headers.removeIf(entry -> entry.getKey().getName().equals("Cookie")); assertTrue(removed); Truth.assertThat(headers.getAll("cOoKie")).containsExactly("frizzle=frazzle"); Truth.assertThat(headers.size()).isEqualTo(3); } @Test void keySet() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("COOKie", "this=that"); headers.add("cookIE", "frizzle=frazzle"); headers.add("Soup", "salad"); Set<HeaderName> keySet = headers.keySet(); Truth.assertThat(keySet) .containsExactly(new HeaderName("COOKie"), new HeaderName("Soup"), new HeaderName("Via")); for (HeaderName headerName : keySet) { if (headerName.getName().equals("COOKie")) { return; } } throw new AssertionError("didn't find right cookie in keys: " + keySet); } @Test void contains() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("COOKie", "this=that"); headers.add("cookIE", "frizzle=frazzle"); headers.add("Soup", "salad"); assertTrue(headers.contains("CoOkIe")); assertTrue(headers.contains(new HeaderName("CoOkIe"))); assertTrue(headers.contains("cookie")); assertTrue(headers.contains(new HeaderName("cookie"))); assertTrue(headers.contains("Cookie")); assertTrue(headers.contains(new HeaderName("Cookie"))); assertTrue(headers.contains("COOKIE")); assertTrue(headers.contains(new HeaderName("COOKIE"))); assertFalse(headers.contains("Monkey")); assertFalse(headers.contains(new HeaderName("Monkey"))); headers.remove("cookie"); assertFalse(headers.contains("cookie")); assertFalse(headers.contains(new HeaderName("cookie"))); } @Test void containsValue() { Headers headers = new Headers(); headers.add("Via", "duct"); headers.add("COOKie", "this=that"); headers.add("cookIE", "frizzle=frazzle"); headers.add("Soup", "salad"); // note the swapping of the two cookie casings. assertTrue(headers.contains("CoOkIe", "frizzle=frazzle")); assertTrue(headers.contains(new HeaderName("CoOkIe"), "frizzle=frazzle")); assertFalse(headers.contains("Via", "lin")); assertFalse(headers.contains(new HeaderName("Soup"), "of the day")); } @Test void testCaseInsensitiveKeys_Set() { Headers headers = new Headers(); headers.set("Content-Length", "5"); headers.set("content-length", "10"); assertEquals("10", headers.getFirst("Content-Length")); assertEquals("10", headers.getFirst("content-length")); assertEquals(1, headers.getAll("content-length").size()); } @Test void testCaseInsensitiveKeys_Add() { Headers headers = new Headers(); headers.add("Content-Length", "5"); headers.add("content-length", "10"); List<String> values = headers.getAll("content-length"); assertTrue(values.contains("10")); assertTrue(values.contains("5")); assertEquals(2, values.size()); } @Test void testCaseInsensitiveKeys_SetIfAbsent() { Headers headers = new Headers(); headers.set("Content-Length", "5"); headers.setIfAbsent("content-length", "10"); List<String> values = headers.getAll("content-length"); assertEquals(1, values.size()); assertEquals("5", values.get(0)); } @Test void testCaseInsensitiveKeys_PutAll() { Headers headers = new Headers(); headers.add("Content-Length", "5"); headers.add("content-length", "10"); Headers headers2 = new Headers(); headers2.putAll(headers); List<String> values = headers2.getAll("content-length"); assertTrue(values.contains("10")); assertTrue(values.contains("5")); assertEquals(2, values.size()); } @Test void testSanitizeValues_CRLF() { Headers headers = new Headers(); assertThrows(ZuulException.class, () -> headers.addAndValidate("x-test-break1", "a\r\nb\r\nc")); assertThrows(ZuulException.class, () -> headers.setAndValidate("x-test-break1", "a\r\nb\r\nc")); } @Test void testSanitizeValues_LF() { Headers headers = new Headers(); assertThrows(ZuulException.class, () -> headers.addAndValidate("x-test-break1", "a\nb\nc")); assertThrows(ZuulException.class, () -> headers.setAndValidate("x-test-break1", "a\nb\nc")); } @Test void testSanitizeValues_ISO88591Value() { Headers headers = new Headers(); headers.addAndValidate("x-test-ISO-8859-1", "P Venkmän"); Truth.assertThat(headers.getAll("x-test-ISO-8859-1")).containsExactly("P Venkmän"); Truth.assertThat(headers.size()).isEqualTo(1); headers.setAndValidate("x-test-ISO-8859-1", "Venkmän"); Truth.assertThat(headers.getAll("x-test-ISO-8859-1")).containsExactly("Venkmän"); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void testSanitizeValues_UTF8Value() { // Ideally Unicode characters should not appear in the Header values. Headers headers = new Headers(); String rawHeaderValue = "\u017d" + "\u0172" + "\u016e" + "\u013F"; // ŽŲŮĽ byte[] bytes = rawHeaderValue.getBytes(StandardCharsets.UTF_8); String utf8HeaderValue = new String(bytes, StandardCharsets.UTF_8); headers.addAndValidate("x-test-UTF8", utf8HeaderValue); Truth.assertThat(headers.getAll("x-test-UTF8")).containsExactly(utf8HeaderValue); Truth.assertThat(headers.size()).isEqualTo(1); rawHeaderValue = "\u017d" + "\u0172" + "uuu" + "\u016e" + "\u013F"; // ŽŲuuuŮĽ bytes = rawHeaderValue.getBytes(StandardCharsets.UTF_8); utf8HeaderValue = new String(bytes, StandardCharsets.UTF_8); headers.setAndValidate("x-test-UTF8", utf8HeaderValue); Truth.assertThat(headers.getAll("x-test-UTF8")).containsExactly(utf8HeaderValue); Truth.assertThat(headers.size()).isEqualTo(1); } @Test void testSanitizeValues_addSetHeaderName() { Headers headers = new Headers(); assertThrows(ZuulException.class, () -> headers.setAndValidate(new HeaderName("x-test-break1"), "a\nb\nc")); assertThrows(ZuulException.class, () -> headers.addAndValidate(new HeaderName("x-test-break2"), "a\r\nb\r\nc")); } @Test void testSanitizeValues_nameCRLF() { Headers headers = new Headers(); assertThrows(ZuulException.class, () -> headers.addAndValidate("x-test-br\r\neak1", "a\r\nb\r\nc")); assertThrows(ZuulException.class, () -> headers.setAndValidate("x-test-br\r\neak2", "a\r\nb\r\nc")); } }
6,170
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpQueryParamsTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message.http; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.util.Locale; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; @ExtendWith(MockitoExtension.class) class HttpQueryParamsTest { @Test void testMultiples() { HttpQueryParams qp = new HttpQueryParams(); qp.add("k1", "v1"); qp.add("k1", "v2"); qp.add("k2", "v3"); assertEquals("k1=v1&k1=v2&k2=v3", qp.toEncodedString()); } @Test 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()); } @Test 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()); } @Test 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); } @Test void parseKeysWithoutValues() { HttpQueryParams expected = new HttpQueryParams(); expected.add("k1", ""); expected.add("k2", "v2"); expected.add("k3", ""); HttpQueryParams actual = HttpQueryParams.parse("k1=&k2=v2&k3="); assertEquals(expected, actual); assertEquals("k1=&k2=v2&k3=", actual.toEncodedString()); } @Test void parseKeyWithoutValueEquals() { HttpQueryParams expected = new HttpQueryParams(); expected.add("k1", ""); HttpQueryParams actual = HttpQueryParams.parse("k1="); assertEquals(expected, actual); assertEquals("k1=", actual.toEncodedString()); } @Test void parseKeyWithoutValue() { HttpQueryParams expected = new HttpQueryParams(); expected.add("k1", ""); HttpQueryParams actual = HttpQueryParams.parse("k1"); assertEquals(expected, actual); assertEquals("k1", actual.toEncodedString()); } @Test void parseKeyWithoutValueShort() { HttpQueryParams expected = new HttpQueryParams(); expected.add("=", ""); HttpQueryParams actual = HttpQueryParams.parse("="); assertEquals(expected, actual); assertEquals("%3D", actual.toEncodedString()); } @Test void parseKeysWithoutValuesMixedTrailers() { HttpQueryParams expected = new HttpQueryParams(); expected.add("k1", ""); expected.add("k2", "v2"); expected.add("k3", ""); expected.add("k4", "v4"); HttpQueryParams actual = HttpQueryParams.parse("k1=&k2=v2&k3&k4=v4"); assertEquals(expected, actual); assertEquals("k1=&k2=v2&k3&k4=v4", actual.toEncodedString()); } @Test void parseKeysIgnoreCase() { String camelCaseKey = "keyName"; HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("foo", "bar"); queryParams.add(camelCaseKey.toLowerCase(Locale.ROOT), "value"); assertTrue(queryParams.containsIgnoreCase(camelCaseKey)); } }
6,171
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpRequestMessageImplTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message.http; import com.google.common.net.InetAddresses; import com.netflix.config.ConfigurationManager; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import io.netty.channel.local.LocalAddress; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URISyntaxException; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class HttpRequestMessageImplTest { HttpRequestMessageImpl request; private final AbstractConfiguration config = ConfigurationManager.getConfigInstance(); @AfterEach void resetConfig() { config.clearProperty("zuul.HttpRequestMessage.host.header.strict.validation"); } @Test void testOriginalRequestInfo() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost", new LocalAddress("777"), false); request.storeInboundRequest(); HttpRequestInfo originalRequest = request.getInboundRequest(); assertEquals(request.getPort(), originalRequest.getPort()); assertEquals(request.getPath(), originalRequest.getPath()); assertEquals( request.getQueryParams().getFirst("flag"), originalRequest.getQueryParams().getFirst("flag")); assertEquals( request.getHeaders().getFirst("Host"), originalRequest.getHeaders().getFirst("Host")); request.setPort(8080); request.setPath("/another/place"); request.getQueryParams().set("flag", "20"); request.getHeaders().set("Host", "wah.netflix.com"); assertEquals(7002, originalRequest.getPort()); assertEquals("/some/where", originalRequest.getPath()); assertEquals("5", originalRequest.getQueryParams().getFirst("flag")); assertEquals("blah.netflix.com", originalRequest.getHeaders().getFirst("Host")); } @Test void testReconstructURI() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("X-Forwarded-Host", "place.netflix.com"); headers.add("X-Forwarded-Port", "80"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "http", 7002, "localhost"); assertEquals("http://place.netflix.com/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("X-Forwarded-Host", "place.netflix.com"); headers.add("X-Forwarded-Proto", "https"); headers.add("X-Forwarded-Port", "443"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "http", 7002, "localhost"); assertEquals("https://place.netflix.com/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); headers = new Headers(); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "http", 7002, "localhost"); assertEquals("http://localhost:7002/some/where", request.reconstructURI()); queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); queryParams.add("flag B", "9"); headers = new Headers(); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some%20where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("https://localhost:7002/some%20where?flag=5&flag+B=9", request.reconstructURI()); } @Test void testReconstructURI_immutable() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost", new SocketAddress() {}, true); // Check it's the same value 2nd time. assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); assertEquals("https://blah.netflix.com:7002/some/where?flag=5", request.reconstructURI()); // Check that cached on 1st usage. request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost", new SocketAddress() {}, true); request = spy(request); when(request._reconstructURI()).thenReturn("http://testhost/blah"); verify(request, times(1))._reconstructURI(); assertEquals("http://testhost/blah", request.reconstructURI()); assertEquals("http://testhost/blah", request.reconstructURI()); // Check that throws exception if we try to mutate it. try { request.setPath("/new-path"); fail(); } catch (IllegalStateException e) { assertTrue(true); } } @Test void testPathAndQuery() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, new Headers(), "192.168.0.2", "https", 7002, "localhost"); // Check that value changes. assertEquals("/some/where?flag=5", request.getPathAndQuery()); request.getQueryParams().add("k", "v"); assertEquals("/some/where?flag=5&k=v", request.getPathAndQuery()); request.setPath("/other"); assertEquals("/other?flag=5&k=v", request.getPathAndQuery()); } @Test void testPathAndQuery_immutable() { HttpQueryParams queryParams = new HttpQueryParams(); queryParams.add("flag", "5"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, new Headers(), "192.168.0.2", "https", 7002, "localhost", new SocketAddress() {}, true); // Check it's the same value 2nd time. assertEquals("/some/where?flag=5", request.getPathAndQuery()); assertEquals("/some/where?flag=5", request.getPathAndQuery()); // Check that cached on 1st usage. request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, new Headers(), "192.168.0.2", "https", 7002, "localhost", new SocketAddress() {}, true); request = spy(request); when(request.generatePathAndQuery()).thenReturn("/blah"); verify(request, times(1)).generatePathAndQuery(); assertEquals("/blah", request.getPathAndQuery()); assertEquals("/blah", request.getPathAndQuery()); } @Test void testGetOriginalHost() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "blah.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("blah.netflix.com", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "0.0.0.1"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("0.0.0.1", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "0.0.0.1:2"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("0.0.0.1", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "[::2]"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("[::2]", request.getOriginalHost()); queryParams = new HttpQueryParams(); headers = new Headers(); headers.add("Host", "[::2]:3"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("[::2]", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "blah.netflix.com"); headers.add("X-Forwarded-Host", "foo.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("foo.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("X-Forwarded-Host", "foo.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("foo.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "blah.netflix.com:8080"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("blah.netflix.com", request.getOriginalHost()); } @Test void testGetOriginalHost_handlesNonRFC2396Hostnames() { config.setProperty("zuul.HttpRequestMessage.host.header.strict.validation", false); HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "my_underscore_endpoint.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("my_underscore_endpoint.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "my_underscore_endpoint.netflix.com:8080"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("my_underscore_endpoint.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "my_underscore_endpoint^including~more-chars.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("my_underscore_endpoint^including~more-chars.netflix.com", request.getOriginalHost()); headers = new Headers(); headers.add("Host", "hostname%5Ewith-url-encoded.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals("hostname%5Ewith-url-encoded.netflix.com", request.getOriginalHost()); } @Test void getOriginalHost_failsOnUnbracketedIpv6Address() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "ba::dd"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertThrows(URISyntaxException.class, () -> HttpRequestMessageImpl.getOriginalHost(headers, "server")); } @Test void getOriginalHost_fallsBackOnUnbracketedIpv6Address_WithNonStrictValidation() { config.setProperty("zuul.HttpRequestMessage.host.header.strict.validation", false); HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "ba::dd"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "server"); assertEquals("server", request.getOriginalHost()); } @Test void testGetOriginalPort() { HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com"); headers.add("X-Forwarded-Port", "443"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com:443"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "127.0.0.2:443"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "127.0.0.2"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "[::2]:443"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(443, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "[::2]"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7002, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "blah.netflix.com:443"); headers.add("X-Forwarded-Port", "7005"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7005, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host_with_underscores.netflix.com:8080"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7002, request.getOriginalPort(), "should fallback to server port"); } @Test void testGetOriginalPort_NonStrictValidation() { config.setProperty("zuul.HttpRequestMessage.host.header.strict.validation", false); HttpQueryParams queryParams = new HttpQueryParams(); Headers headers = new Headers(); headers.add("Host", "host_with_underscores.netflix.com:8080"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(8080, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host-with-carrots^1.0.0.netflix.com:8080"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(8080, request.getOriginalPort()); headers = new Headers(); headers.add("Host", "host-with-carrots-no-port^1.0.0.netflix.com"); request = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", queryParams, headers, "192.168.0.2", "https", 7002, "localhost"); assertEquals(7002, request.getOriginalPort()); } @Test void getOriginalPort_fallsBackOnUnbracketedIpv6Address() throws URISyntaxException { Headers headers = new Headers(); headers.add("Host", "ba::33"); assertEquals(9999, HttpRequestMessageImpl.getOriginalPort(new SessionContext(), headers, 9999)); } @Test void getOriginalPort_EmptyXFFPort() throws URISyntaxException { Headers headers = new Headers(); headers.add(HttpHeaderNames.X_FORWARDED_PORT, ""); // Default to using server port assertEquals(9999, HttpRequestMessageImpl.getOriginalPort(new SessionContext(), headers, 9999)); } @Test void getOriginalPort_respectsProxyProtocol() throws URISyntaxException { SessionContext context = new SessionContext(); context.set( CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS, new InetSocketAddress(InetAddresses.forString("1.1.1.1"), 443)); Headers headers = new Headers(); headers.add("X-Forwarded-Port", "6000"); assertEquals(443, HttpRequestMessageImpl.getOriginalPort(context, headers, 9999)); } @Test void testCleanCookieHeaders() { assertEquals( "BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader("BlahId=12345; Secure, something=67890;")); assertEquals( "BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader("BlahId=12345; something=67890;")); assertEquals( " BlahId=12345; something=67890;", HttpRequestMessageImpl.cleanCookieHeader(" Secure, BlahId=12345; Secure, something=67890;")); assertEquals("", HttpRequestMessageImpl.cleanCookieHeader("")); } @Test void shouldPreferClientDestPortWhenInitialized() { HttpRequestMessageImpl message = new HttpRequestMessageImpl( new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443), true); assertEquals(message.getClientDestinationPort(), Optional.of(443)); } }
6,172
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/message/http/HttpResponseMessageImplTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.message.http; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.nio.charset.StandardCharsets; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link HttpResponseMessageImpl}. */ @ExtendWith(MockitoExtension.class) class HttpResponseMessageImplTest { private static final String TEXT1 = "Hello World!"; private static final String TEXT2 = "Goodbye World!"; @Mock private HttpRequestMessage request; private HttpResponseMessageImpl response; @BeforeEach void setup() { response = new HttpResponseMessageImpl(new SessionContext(), new Headers(), request, 200); } @Test void testHasSetCookieWithName() { response.getHeaders() .add( "Set-Cookie", "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); response.getHeaders() .add( "Set-Cookie", "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); assertTrue(response.hasSetCookieWithName("c1")); assertTrue(response.hasSetCookieWithName("c2")); assertFalse(response.hasSetCookieWithName("XX")); } @Test void testRemoveExistingSetCookie() { response.getHeaders() .add( "Set-Cookie", "c1=1234; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); response.getHeaders() .add( "Set-Cookie", "c2=4567; Max-Age=-1; Expires=Tue, 01 Sep 2015 22:49:57 GMT; Path=/; Domain=.netflix.com"); response.removeExistingSetCookie("c1"); assertEquals(1, response.getHeaders().size()); assertFalse(response.hasSetCookieWithName("c1")); assertTrue(response.hasSetCookieWithName("c2")); } @Test void testContentLengthHeaderHasCorrectValue() { assertEquals(0, response.getHeaders().getAll("Content-Length").size()); response.setBodyAsText(TEXT1); assertEquals(String.valueOf(TEXT1.length()), response.getHeaders().getFirst("Content-Length")); response.setBody(TEXT2.getBytes(StandardCharsets.UTF_8)); assertEquals(String.valueOf(TEXT2.length()), response.getHeaders().getFirst("Content-Length")); } }
6,173
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/insights/ServerStateHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.insights; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Id; import com.netflix.spectator.api.Registry; import com.netflix.zuul.netty.insights.ServerStateHandler.InboundHandler; import com.netflix.zuul.netty.server.http2.DummyChannelHandler; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class ServerStateHandlerTest { private Registry registry; private Id currentConnsId; private Id connectsId; private Id errorsId; private Id closesId; final String listener = "test-conn-throttled"; @BeforeEach void init() { registry = new DefaultRegistry(); currentConnsId = registry.createId("server.connections.current").withTags("id", listener); connectsId = registry.createId("server.connections.connect").withTags("id", listener); closesId = registry.createId("server.connections.close").withTags("id", listener); errorsId = registry.createId("server.connections.errors").withTags("id", listener); } @Test void verifyConnMetrics() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(new DummyChannelHandler()); channel.pipeline().addLast(new InboundHandler(registry, listener)); final Counter connects = (Counter) registry.get(connectsId); final Counter closes = (Counter) registry.get(closesId); final Counter errors = (Counter) registry.get(errorsId); // Connects X 3 channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); assertEquals(3, connects.count()); // Closes X 1 channel.pipeline().context(DummyChannelHandler.class).fireChannelInactive(); assertEquals(3, connects.count()); assertEquals(1, closes.count()); assertEquals(0, errors.count()); } @Test void setPassportStateOnConnect() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(new DummyChannelHandler()); channel.pipeline().addLast(new InboundHandler(registry, listener)); channel.pipeline().context(DummyChannelHandler.class).fireChannelActive(); assertEquals( PassportState.SERVER_CH_ACTIVE, CurrentPassport.fromChannel(channel).getState()); } @Test void setPassportStateOnDisconnect() { final EmbeddedChannel channel = new EmbeddedChannel(); channel.pipeline().addLast(new DummyChannelHandler()); channel.pipeline().addLast(new InboundHandler(registry, listener)); channel.pipeline().context(DummyChannelHandler.class).fireChannelInactive(); assertEquals( PassportState.SERVER_CH_INACTIVE, CurrentPassport.fromChannel(channel).getState()); } }
6,174
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/OpenSslTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.ssl; import io.netty.handler.ssl.OpenSsl; import io.netty.handler.ssl.SslProvider; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertTrue; class OpenSslTest { @BeforeEach void beforeEach() { OpenSsl.ensureAvailability(); assertTrue(OpenSsl.isAvailable()); } @Test void testBoringSsl() { assertThat(OpenSsl.versionString()).isEqualTo("BoringSSL"); assertTrue(SslProvider.isAlpnSupported(SslProvider.OPENSSL)); assertTrue(SslProvider.isTlsv13Supported(SslProvider.OPENSSL)); } }
6,175
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/ClientSslContextFactoryTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.ssl; import com.netflix.spectator.api.DefaultRegistry; import io.netty.handler.ssl.OpenSslClientContext; import io.netty.handler.ssl.SslContext; import org.junit.jupiter.api.Test; import javax.net.ssl.SSLSessionContext; import java.util.Arrays; import java.util.List; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link ClientSslContextFactory}. */ class ClientSslContextFactoryTest { @Test void enableTls13() { String[] protos = ClientSslContextFactory.maybeAddTls13(true, "TLSv1.2"); assertEquals(Arrays.asList("TLSv1.3", "TLSv1.2"), Arrays.asList(protos)); } @Test void disableTls13() { String[] protos = ClientSslContextFactory.maybeAddTls13(false, "TLSv1.2"); assertEquals(Arrays.asList("TLSv1.2"), Arrays.asList(protos)); } @Test void testGetSslContext() { ClientSslContextFactory factory = new ClientSslContextFactory(new DefaultRegistry()); SslContext sslContext = factory.getClientSslContext(); assertThat(sslContext).isInstanceOf(OpenSslClientContext.class); assertThat(sslContext.isClient()).isTrue(); assertThat(sslContext.isServer()).isFalse(); SSLSessionContext sessionContext = sslContext.sessionContext(); assertThat(sessionContext.getSessionCacheSize()).isEqualTo(20480); assertThat(sessionContext.getSessionTimeout()).isEqualTo(300); } @Test void testGetProtocols() { ClientSslContextFactory factory = new ClientSslContextFactory(new DefaultRegistry()); assertThat(factory.getProtocols()).isEqualTo(new String[] {"TLSv1.2"}); } @Test void testGetCiphers() throws Exception { ClientSslContextFactory factory = new ClientSslContextFactory(new DefaultRegistry()); List<String> ciphers = factory.getCiphers(); assertThat(ciphers).isNotEmpty(); assertThat(ciphers).containsNoDuplicates(); } }
6,176
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/ssl/BaseSslContextFactoryTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.ssl; import io.netty.handler.ssl.SslProvider; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Tests for {@link BaseSslContextFactory}. */ class BaseSslContextFactoryTest { @Test void testDefaultSslProviderIsOpenSsl() { assertEquals(SslProvider.OPENSSL, BaseSslContextFactory.chooseSslProvider()); } }
6,177
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/timeouts/OriginTimeoutManagerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.timeouts; import com.netflix.client.config.CommonClientConfigKey; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.origins.NettyOrigin; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import java.time.Duration; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; /** * Origin Timeout Manager Test * * @author Arthur Gonigberg * @since March 23, 2021 */ @ExtendWith(MockitoExtension.class) class OriginTimeoutManagerTest { @Mock private NettyOrigin origin; @Mock private HttpRequestMessage request; private SessionContext context; private IClientConfig requestConfig; private IClientConfig originConfig; private OriginTimeoutManager originTimeoutManager; @BeforeEach void before() { originTimeoutManager = new OriginTimeoutManager(origin); context = new SessionContext(); when(request.getContext()).thenReturn(context); requestConfig = new DefaultClientConfigImpl(); originConfig = new DefaultClientConfigImpl(); context.put(CommonContextKeys.REST_CLIENT_CONFIG, requestConfig); when(origin.getClientConfig()).thenReturn(originConfig); } @Test void computeReadTimeout_default() { Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS.get(), timeout.toMillis()); } @Test void computeReadTimeout_requestOnly() { requestConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(1000, timeout.toMillis()); } @Test void computeReadTimeout_originOnly() { originConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(1000, timeout.toMillis()); } @Test void computeReadTimeout_bolth_equal() { requestConfig.set(CommonClientConfigKey.ReadTimeout, 1000); originConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(1000, timeout.toMillis()); } @Test void computeReadTimeout_bolth_originLower() { requestConfig.set(CommonClientConfigKey.ReadTimeout, 1000); originConfig.set(CommonClientConfigKey.ReadTimeout, 100); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(100, timeout.toMillis()); } @Test void computeReadTimeout_bolth_requestLower() { requestConfig.set(CommonClientConfigKey.ReadTimeout, 100); originConfig.set(CommonClientConfigKey.ReadTimeout, 1000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(100, timeout.toMillis()); } @Test void computeReadTimeout_bolth_enforceMax() { requestConfig.set( CommonClientConfigKey.ReadTimeout, (int) OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 1000); originConfig.set( CommonClientConfigKey.ReadTimeout, (int) OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS.get() + 10000); Duration timeout = originTimeoutManager.computeReadTimeout(request, 1); assertEquals(OriginTimeoutManager.MAX_OUTBOUND_READ_TIMEOUT_MS.get(), timeout.toMillis()); } }
6,178
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientResponseWriterTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.zuul.BasicRequestCompleteHandler; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.util.HttpRequestBuilder; import com.netflix.zuul.stats.status.StatusCategory; import com.netflix.zuul.stats.status.StatusCategoryUtils; import com.netflix.zuul.stats.status.ZuulStatusCategory; import io.netty.channel.Channel; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import static com.google.common.truth.Truth.assertThat; @ExtendWith(MockitoExtension.class) class ClientResponseWriterTest { @Test void exemptClientTimeoutResponseBeforeRequestRead() { final ClientResponseWriter responseWriter = new ClientResponseWriter(new BasicRequestCompleteHandler()); final EmbeddedChannel channel = new EmbeddedChannel(); final SessionContext context = new SessionContext(); StatusCategoryUtils.setStatusCategory(context, ZuulStatusCategory.FAILURE_CLIENT_TIMEOUT); final HttpRequestMessage request = new HttpRequestBuilder(context).withDefaults(); channel.attr(ClientRequestReceiver.ATTR_ZUUL_REQ).set(request); assertThat(responseWriter.shouldAllowPreemptiveResponse(channel)).isTrue(); } @Test void flagResponseBeforeRequestRead() { final ClientResponseWriter responseWriter = new ClientResponseWriter(new BasicRequestCompleteHandler()); final EmbeddedChannel channel = new EmbeddedChannel(); final SessionContext context = new SessionContext(); StatusCategoryUtils.setStatusCategory(context, ZuulStatusCategory.FAILURE_LOCAL); final HttpRequestMessage request = new HttpRequestBuilder(context).withDefaults(); channel.attr(ClientRequestReceiver.ATTR_ZUUL_REQ).set(request); assertThat(responseWriter.shouldAllowPreemptiveResponse(channel)).isFalse(); } @Test void allowExtensionForPremptingResponse() { final ZuulStatusCategory customStatus = ZuulStatusCategory.SUCCESS_LOCAL_NO_ROUTE; final ClientResponseWriter responseWriter = new ClientResponseWriter(new BasicRequestCompleteHandler()) { @Override protected boolean shouldAllowPreemptiveResponse(Channel channel) { StatusCategory status = StatusCategoryUtils.getStatusCategory(ClientRequestReceiver.getRequestFromChannel(channel)); return status == customStatus; } }; final EmbeddedChannel channel = new EmbeddedChannel(); final SessionContext context = new SessionContext(); StatusCategoryUtils.setStatusCategory(context, customStatus); final HttpRequestMessage request = new HttpRequestBuilder(context).withDefaults(); channel.attr(ClientRequestReceiver.ATTR_ZUUL_REQ).set(request); assertThat(responseWriter.shouldAllowPreemptiveResponse(channel)).isTrue(); } }
6,179
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientConnectionsShutdownTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.appinfo.InstanceInfo.InstanceStatus; import com.netflix.config.ConfigurationManager; import com.netflix.discovery.EurekaClient; import com.netflix.discovery.EurekaEventListener; import com.netflix.discovery.StatusChangeEvent; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.DefaultEventLoop; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.Promise; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import java.util.UUID; import java.util.concurrent.Callable; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * @author Justin Guerra * @since 2/28/23 */ class ClientConnectionsShutdownTest { // using LocalChannels instead of EmbeddedChannels to re-create threading behavior in an actual deployment private static LocalAddress LOCAL_ADDRESS; private static DefaultEventLoopGroup SERVER_EVENT_LOOP; private static DefaultEventLoopGroup CLIENT_EVENT_LOOP; private static DefaultEventLoop EVENT_LOOP; @BeforeAll static void staticSetup() throws InterruptedException { LOCAL_ADDRESS = new LocalAddress(UUID.randomUUID().toString()); CLIENT_EVENT_LOOP = new DefaultEventLoopGroup(4); SERVER_EVENT_LOOP = new DefaultEventLoopGroup(4); ServerBootstrap serverBootstrap = new ServerBootstrap() .group(SERVER_EVENT_LOOP) .localAddress(LOCAL_ADDRESS) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) {} }); serverBootstrap.bind().sync(); EVENT_LOOP = new DefaultEventLoop(Executors.newSingleThreadExecutor()); } @AfterAll static void staticCleanup() { CLIENT_EVENT_LOOP.shutdownGracefully(); SERVER_EVENT_LOOP.shutdownGracefully(); EVENT_LOOP.shutdownGracefully(); } private ChannelGroup channels; private ClientConnectionsShutdown shutdown; @BeforeEach void setup() { channels = new DefaultChannelGroup(EVENT_LOOP); shutdown = new ClientConnectionsShutdown(channels, EVENT_LOOP, null); } @Test @SuppressWarnings("unchecked") void discoveryShutdown() { String configName = "server.outofservice.connections.shutdown"; AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); try { configuration.setProperty(configName, "true"); EurekaClient eureka = Mockito.mock(EurekaClient.class); EventExecutor executor = Mockito.mock(EventExecutor.class); ArgumentCaptor<EurekaEventListener> captor = ArgumentCaptor.forClass(EurekaEventListener.class); shutdown = spy(new ClientConnectionsShutdown(channels, executor, eureka)); verify(eureka).registerEventListener(captor.capture()); doReturn(executor.newPromise()).when(shutdown).gracefullyShutdownClientChannels(); EurekaEventListener listener = captor.getValue(); listener.onEvent(new StatusChangeEvent(InstanceStatus.UP, InstanceStatus.DOWN)); verify(executor).schedule(ArgumentMatchers.isA(Callable.class), anyLong(), eq(TimeUnit.MILLISECONDS)); Mockito.reset(executor); listener.onEvent(new StatusChangeEvent(InstanceStatus.UP, InstanceStatus.OUT_OF_SERVICE)); verify(executor).schedule(ArgumentMatchers.isA(Callable.class), anyLong(), eq(TimeUnit.MILLISECONDS)); Mockito.reset(executor); listener.onEvent(new StatusChangeEvent(InstanceStatus.STARTING, InstanceStatus.OUT_OF_SERVICE)); verify(executor, never()) .schedule(ArgumentMatchers.isA(Callable.class), anyLong(), eq(TimeUnit.MILLISECONDS)); } finally { configuration.setProperty(configName, "false"); } } @Test void allConnectionsGracefullyClosed() throws Exception { createChannels(100); Promise<Void> promise = shutdown.gracefullyShutdownClientChannels(); Promise<Object> testPromise = EVENT_LOOP.newPromise(); promise.addListener(future -> { if (future.isSuccess()) { testPromise.setSuccess(null); } else { testPromise.setFailure(future.cause()); } }); channels.forEach(Channel::close); testPromise.await(10, TimeUnit.SECONDS); assertTrue(channels.isEmpty()); } @Test void connectionNeedsToBeForceClosed() throws Exception { String configName = "server.outofservice.close.timeout"; AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); try { configuration.setProperty(configName, "0"); createChannels(10); shutdown.gracefullyShutdownClientChannels().await(10, TimeUnit.SECONDS); assertTrue( channels.isEmpty(), "All channels in group should have been force closed after the timeout was triggered"); } finally { configuration.setProperty(configName, "30"); } } @Test void connectionsNotForceClosed() throws Exception { String configName = "server.outofservice.close.timeout"; AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); DefaultEventLoop eventLoop = spy(EVENT_LOOP); shutdown = new ClientConnectionsShutdown(channels, eventLoop, null); try { configuration.setProperty(configName, "0"); createChannels(10); Promise<Void> promise = shutdown.gracefullyShutdownClientChannels(false); verify(eventLoop, never()).schedule(isA(Runnable.class), anyLong(), isA(TimeUnit.class)); channels.forEach(Channel::close); promise.await(10, TimeUnit.SECONDS); assertTrue(channels.isEmpty(), "All channels in group should have been closed"); } finally { configuration.setProperty(configName, "30"); } } private void createChannels(int numChannels) throws InterruptedException { ChannelInitializer<LocalChannel> initializer = new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) {} }; for (int i = 0; i < numChannels; ++i) { ChannelFuture connect = new Bootstrap() .group(CLIENT_EVENT_LOOP) .channel(LocalChannel.class) .handler(initializer) .remoteAddress(LOCAL_ADDRESS) .connect() .sync(); channels.add(connect.channel()); } } }
6,180
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/ClientRequestReceiverTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.google.common.net.InetAddresses; import com.netflix.netty.common.HttpLifecycleChannelHandler; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteEvent; import com.netflix.netty.common.HttpLifecycleChannelHandler.CompleteReason; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.netty.insights.PassportLoggingHandler; import com.netflix.zuul.stats.status.StatusCategoryUtils; import com.netflix.zuul.stats.status.ZuulStatusCategory; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.DefaultFullHttpResponse; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpRequestEncoder; import io.netty.handler.codec.http.HttpResponseStatus; import io.netty.handler.codec.http.HttpServerCodec; import io.netty.handler.codec.http.HttpVersion; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.junit.jupiter.MockitoExtension; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Unit tests for {@link ClientRequestReceiver}. */ @ExtendWith(MockitoExtension.class) class ClientRequestReceiverTest { @Test void proxyProtocol_portSetInSessionContextAndInHttpRequestMessageImpl() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); InetSocketAddress hapmDestinationAddress = new InetSocketAddress(InetAddresses.forString("2.2.2.2"), 444); channel.attr(SourceAddressChannelHandler.ATTR_PROXY_PROTOCOL_DESTINATION_ADDRESS) .set(hapmDestinationAddress); channel.attr(SourceAddressChannelHandler.ATTR_LOCAL_ADDR).set(hapmDestinationAddress); HttpRequestMessageImpl result; { channel.writeInbound( new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } assertEquals((int) result.getClientDestinationPort().get(), hapmDestinationAddress.getPort()); int destinationPort = ((InetSocketAddress) result.getContext().get(CommonContextKeys.PROXY_PROTOCOL_DESTINATION_ADDRESS)) .getPort(); assertEquals(444, destinationPort); assertEquals(444, result.getOriginalPort()); channel.close(); } @Test void parseUriFromNetty_relative() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { channel.writeInbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/foo/bar/somePath/%5E1.0.0?param1=foo&param2=bar&param3=baz", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } assertEquals("/foo/bar/somePath/%5E1.0.0", result.getPath()); channel.close(); } @Test void parseUriFromNetty_absolute() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { channel.writeInbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "https://www.netflix.com/foo/bar/somePath/%5E1.0.0?param1=foo&param2=bar&param3=baz", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } assertEquals("/foo/bar/somePath/%5E1.0.0", result.getPath()); channel.close(); } @Test void parseUriFromNetty_unknown() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { channel.writeInbound( new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "asdf", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } assertEquals("asdf", result.getPath()); channel.close(); } @Test void parseQueryParamsWithEncodedCharsInURI() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); HttpRequestMessageImpl result; { channel.writeInbound(new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "/foo/bar/somePath/%5E1.0.0?param1=foo&param2=bar&param3=baz", Unpooled.buffer())); result = channel.readInbound(); result.disposeBufferedBody(); } assertEquals("foo", result.getQueryParams().getFirst("param1")); assertEquals("bar", result.getQueryParams().getFirst("param2")); assertEquals("baz", result.getQueryParams().getFirst("param3")); channel.close(); } @Test void largeResponse_atLimit() { ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(receiver); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); int maxSize; // Figure out the max size, since it isn't public. { ByteBuf buf = Unpooled.buffer(1).writeByte('a'); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf)); HttpRequestMessageImpl res = channel.readInbound(); maxSize = res.getMaxBodySize(); res.disposeBufferedBody(); } HttpRequestMessageImpl result; { ByteBuf buf = Unpooled.buffer(maxSize); buf.writerIndex(maxSize); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf)); result = channel.readInbound(); result.disposeBufferedBody(); } assertNull(result.getContext().getError()); assertFalse(result.getContext().shouldSendErrorResponse()); channel.close(); } @Test void largeResponse_aboveLimit() { ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(receiver); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); int maxSize; // Figure out the max size, since it isn't public. { ByteBuf buf = Unpooled.buffer(1).writeByte('a'); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf)); HttpRequestMessageImpl res = channel.readInbound(); maxSize = res.getMaxBodySize(); res.disposeBufferedBody(); } HttpRequestMessageImpl result; { ByteBuf buf = Unpooled.buffer(maxSize + 1); buf.writerIndex(maxSize + 1); channel.writeInbound(new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf)); result = channel.readInbound(); result.disposeBufferedBody(); } assertNotNull(result.getContext().getError()); assertTrue(result.getContext().getError().getMessage().contains("too large")); assertTrue(result.getContext().shouldSendErrorResponse()); assertEquals(ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(result)); assertTrue(StatusCategoryUtils.getStatusCategoryReason(result.getContext()) .startsWith("Invalid request provided: Request body size ")); channel.close(); } @Test void maxHeaderSizeExceeded_setBadRequestStatus() { int maxInitialLineLength = BaseZuulChannelInitializer.MAX_INITIAL_LINE_LENGTH.get(); int maxHeaderSize = 10; int maxChunkSize = BaseZuulChannelInitializer.MAX_CHUNK_SIZE.get(); ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder()); PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry()); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); channel.pipeline().addLast(new HttpServerCodec(maxInitialLineLength, maxHeaderSize, maxChunkSize, false)); channel.pipeline().addLast(receiver); channel.pipeline().addLast(loggingHandler); String str = "test-header-value"; ByteBuf buf = Unpooled.buffer(1); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post", buf); for (int i = 0; i < 100; i++) { httpRequest.headers().add("test-header" + i, str); } channel.writeOutbound(httpRequest); ByteBuf byteBuf = channel.readOutbound(); channel.writeInbound(byteBuf); channel.readInbound(); channel.close(); HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); assertEquals( ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(request.getContext())); assertEquals( "Invalid request provided: Decode failure", StatusCategoryUtils.getStatusCategoryReason(request.getContext())); } @Test void multipleHostHeaders_setBadRequestStatus() { ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder()); PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry()); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); channel.pipeline().addLast(new HttpServerCodec()); channel.pipeline().addLast(receiver); channel.pipeline().addLast(loggingHandler); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post"); httpRequest.headers().add("Host", "foo.bar.com"); httpRequest.headers().add("Host", "bar.foo.com"); channel.writeOutbound(httpRequest); ByteBuf byteBuf = channel.readOutbound(); channel.writeInbound(byteBuf); channel.readInbound(); channel.close(); HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); SessionContext context = request.getContext(); assertEquals(ZuulStatusCategory.FAILURE_CLIENT_BAD_REQUEST, StatusCategoryUtils.getStatusCategory(context)); assertEquals("Multiple Host headers", context.getError().getMessage()); assertEquals( "Invalid request provided: Multiple Host headers", StatusCategoryUtils.getStatusCategoryReason(context)); } @Test void setStatusCategoryForHttpPipelining() { EmbeddedChannel channel = new EmbeddedChannel(new ClientRequestReceiver(null)); channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); final DefaultFullHttpRequest request = new DefaultFullHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.POST, "?ELhAWDLM1hwm8bhU0UT4", Unpooled.buffer()); // Write the message and save a copy channel.writeInbound(request); final HttpRequestMessage inboundRequest = ClientRequestReceiver.getRequestFromChannel(channel); // Set the attr to emulate pipelining rejection channel.attr(HttpLifecycleChannelHandler.ATTR_HTTP_PIPELINE_REJECT).set(Boolean.TRUE); // Fire completion event channel.pipeline() .fireUserEventTriggered(new CompleteEvent( CompleteReason.PIPELINE_REJECT, request, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST))); channel.close(); assertEquals( ZuulStatusCategory.FAILURE_CLIENT_PIPELINE_REJECT, StatusCategoryUtils.getStatusCategory(inboundRequest.getContext())); } @Test void headersAllCopied() { ClientRequestReceiver receiver = new ClientRequestReceiver(null); EmbeddedChannel channel = new EmbeddedChannel(new HttpRequestEncoder()); PassportLoggingHandler loggingHandler = new PassportLoggingHandler(new DefaultRegistry()); // Required for messages channel.attr(SourceAddressChannelHandler.ATTR_SERVER_LOCAL_PORT).set(1234); channel.pipeline().addLast(new HttpServerCodec()); channel.pipeline().addLast(receiver); channel.pipeline().addLast(loggingHandler); HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/post"); httpRequest.headers().add("Header1", "Value1"); httpRequest.headers().add("Header2", "Value2"); httpRequest.headers().add("Duplicate", "Duplicate1"); httpRequest.headers().add("Duplicate", "Duplicate2"); channel.writeOutbound(httpRequest); ByteBuf byteBuf = channel.readOutbound(); channel.writeInbound(byteBuf); channel.readInbound(); channel.close(); HttpRequestMessage request = ClientRequestReceiver.getRequestFromChannel(channel); Headers headers = request.getHeaders(); assertEquals(4, headers.size()); assertEquals("Value1", headers.getFirst("Header1")); assertEquals("Value2", headers.getFirst("Header2")); List<String> duplicates = headers.getAll("Duplicate"); assertEquals(Arrays.asList("Duplicate1", "Duplicate2"), duplicates); } }
6,181
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/BaseZuulChannelInitializerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.netty.common.SourceAddressChannelHandler; import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; import com.netflix.netty.common.metrics.PerEventLoopMetricsChannelHandler; import com.netflix.netty.common.proxyprotocol.ElbProxyProtocolChannelHandler; import com.netflix.netty.common.throttle.MaxInboundConnectionsHandler; import com.netflix.spectator.api.NoopRegistry; import com.netflix.zuul.netty.insights.ServerStateHandler; import com.netflix.zuul.netty.ratelimiting.NullChannelHandlerProvider; import io.netty.channel.Channel; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.DefaultChannelGroup; import io.netty.util.concurrent.GlobalEventExecutor; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Unit tests for {@link BaseZuulChannelInitializer}. */ class BaseZuulChannelInitializerTest { @Test void tcpHandlersAdded() { ChannelConfig channelConfig = new ChannelConfig(); ChannelConfig channelDependencies = new ChannelConfig(); channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry()); channelDependencies.set( ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider()); channelDependencies.set( ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider()); ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); BaseZuulChannelInitializer init = new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); init.addTcpRelatedHandlers(channel.pipeline()); assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class)); assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class)); assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class)); } @Test void tcpHandlersAdded_withProxyProtocol() { ChannelConfig channelConfig = new ChannelConfig(); channelConfig.set(CommonChannelConfigKeys.withProxyProtocol, true); ChannelConfig channelDependencies = new ChannelConfig(); channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry()); channelDependencies.set( ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider()); channelDependencies.set( ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider()); ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); BaseZuulChannelInitializer init = new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); init.addTcpRelatedHandlers(channel.pipeline()); assertNotNull(channel.pipeline().context(SourceAddressChannelHandler.class)); assertNotNull(channel.pipeline().context(PerEventLoopMetricsChannelHandler.Connections.class)); assertNotNull(channel.pipeline().context(ElbProxyProtocolChannelHandler.NAME)); assertNotNull(channel.pipeline().context(MaxInboundConnectionsHandler.class)); } @Test void serverStateHandlerAdded() { ChannelConfig channelConfig = new ChannelConfig(); ChannelConfig channelDependencies = new ChannelConfig(); channelDependencies.set(ZuulDependencyKeys.registry, new NoopRegistry()); channelDependencies.set( ZuulDependencyKeys.rateLimitingChannelHandlerProvider, new NullChannelHandlerProvider()); channelDependencies.set( ZuulDependencyKeys.sslClientCertCheckChannelHandlerProvider, new NullChannelHandlerProvider()); ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); BaseZuulChannelInitializer init = new BaseZuulChannelInitializer("1234", channelConfig, channelDependencies, channelGroup) { @Override protected void initChannel(Channel ch) {} }; EmbeddedChannel channel = new EmbeddedChannel(); init.addPassportHandler(channel.pipeline()); assertNotNull(channel.pipeline().context(ServerStateHandler.InboundHandler.class)); assertNotNull(channel.pipeline().context(ServerStateHandler.OutboundHandler.class)); } }
6,182
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/ServerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.config.ConfigurationManager; import com.netflix.netty.common.metrics.EventLoopGroupMetrics; import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Spectator; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.GlobalEventExecutor; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; /** * Tests for {@link Server}. */ class ServerTest { private static final Logger LOGGER = LoggerFactory.getLogger(ServerTest.class); @BeforeEach void beforeTest() { final AbstractConfiguration config = ConfigurationManager.getConfigInstance(); config.setProperty("zuul.server.netty.socket.force_nio", "true"); config.setProperty("zuul.server.netty.socket.force_io_uring", "false"); } @Test void getListeningSockets() throws Exception { ServerStatusManager ssm = mock(ServerStatusManager.class); Map<NamedSocketAddress, ChannelInitializer<?>> initializers = new HashMap<>(); final List<NioSocketChannel> nioChannels = Collections.synchronizedList(new ArrayList<NioSocketChannel>()); ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() { @Override protected void initChannel(final Channel ch) { LOGGER.info("Channel: {}, isActive={}, isOpen={}", ch.getClass().getName(), ch.isActive(), ch.isOpen()); if (ch instanceof NioSocketChannel) { nioChannels.add((NioSocketChannel) ch); } } }; initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init); // The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init); ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, /* discoveryClient= */ null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override public int eventLoopCount() { return 1; } @Override public int acceptorCount() { return 1; } }; Server s = new Server(new NoopRegistry(), ssm, initializers, ccs, elgm, elc); s.start(); List<NamedSocketAddress> addrs = s.getListeningAddresses(); assertEquals(2, addrs.size()); for (NamedSocketAddress address : addrs) { assertTrue(address.unwrap() instanceof InetSocketAddress); final int port = ((InetSocketAddress) address.unwrap()).getPort(); assertNotEquals(0, port); checkConnection(port); } await().atMost(1, TimeUnit.SECONDS).until(() -> nioChannels.size() == 2); s.stop(); assertEquals(2, nioChannels.size()); for (NioSocketChannel ch : nioChannels) { assertTrue(ch.isShutdown(), "isShutdown"); } } private static void checkConnection(final int port) { Socket sock = null; try { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", port); sock = new Socket(); sock.setSoTimeout(100); sock.connect(socketAddress, 100); OutputStream out = sock.getOutputStream(); out.write("Hello".getBytes(StandardCharsets.UTF_8)); out.flush(); out.close(); } catch (Exception exception) { fail("checkConnection failed. port=" + port + " " + exception); } finally { try { sock.close(); } catch (Exception ignored) { } } } }
6,183
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/SocketAddressPropertyTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.zuul.netty.server.SocketAddressProperty.BindType; import io.netty.channel.unix.DomainSocketAddress; import org.junit.jupiter.api.Test; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Arrays; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; class SocketAddressPropertyTest { @Test void defaultValueWorks() { SocketAddressProperty prop = new SocketAddressProperty("com.netflix.zuul.netty.server.testprop", "=7001"); SocketAddress address = prop.getValue(); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); } @Test void bindTypeWorks_any() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("ANY=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); } @Test void bindTypeWorks_blank() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); } @Test void bindTypeWorks_ipv4Any() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("IPV4_ANY=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); assertTrue(inetSocketAddress.getAddress() instanceof Inet4Address); assertTrue(inetSocketAddress.getAddress().isAnyLocalAddress()); } @Test void bindTypeWorks_ipv6Any() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("IPV6_ANY=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); assertTrue(inetSocketAddress.getAddress() instanceof Inet6Address); assertTrue(inetSocketAddress.getAddress().isAnyLocalAddress()); } @Test void bindTypeWorks_anyLocal() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("ANY_LOCAL=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); assertTrue(inetSocketAddress.getAddress().isLoopbackAddress()); } @Test void bindTypeWorks_ipv4Local() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("IPV4_LOCAL=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); assertTrue(inetSocketAddress.getAddress() instanceof Inet4Address); assertTrue(inetSocketAddress.getAddress().isLoopbackAddress()); } @Test void bindTypeWorks_ipv6Local() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("IPV6_LOCAL=7001"); assertEquals(InetSocketAddress.class, address.getClass()); InetSocketAddress inetSocketAddress = (InetSocketAddress) address; assertEquals(7001, inetSocketAddress.getPort()); assertFalse(inetSocketAddress.isUnresolved()); assertTrue(inetSocketAddress.getAddress() instanceof Inet6Address); assertTrue(inetSocketAddress.getAddress().isLoopbackAddress()); } @Test void bindTypeWorks_uds() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("UDS=/var/run/zuul.sock"); assertEquals(DomainSocketAddress.class, address.getClass()); DomainSocketAddress domainSocketAddress = (DomainSocketAddress) address; assertEquals("/var/run/zuul.sock", domainSocketAddress.path()); } @Test void bindTypeWorks_udsWithEquals() { SocketAddress address = SocketAddressProperty.Decoder.INSTANCE.apply("UDS=/var/run/zuul=.sock"); assertEquals(DomainSocketAddress.class, address.getClass()); DomainSocketAddress domainSocketAddress = (DomainSocketAddress) address; assertEquals("/var/run/zuul=.sock", domainSocketAddress.path()); } @Test void failsOnMissingEqual() { assertThrows(IllegalArgumentException.class, () -> { SocketAddressProperty.Decoder.INSTANCE.apply("ANY"); }); } @Test void failsOnBadPort() { for (BindType type : Arrays.asList( BindType.ANY, BindType.IPV4_ANY, BindType.IPV6_ANY, BindType.ANY_LOCAL, BindType.IPV4_LOCAL, BindType.IPV6_LOCAL)) { IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> { SocketAddressProperty.Decoder.INSTANCE.apply(type.name() + "=bogus"); }); assertTrue(exception.getMessage().contains("Port")); } } }
6,184
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/IoUringTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server; import com.netflix.config.ConfigurationManager; import com.netflix.netty.common.metrics.EventLoopGroupMetrics; import com.netflix.netty.common.status.ServerStatusManager; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Spectator; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.group.DefaultChannelGroup; import io.netty.incubator.channel.uring.IOUring; import io.netty.incubator.channel.uring.IOUringSocketChannel; import io.netty.util.concurrent.GlobalEventExecutor; import io.netty.util.internal.PlatformDependent; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.Mockito.mock; /* Goals of this test: 1) verify that the server starts 2) verify that the server is listening on 2 ports 3) verify that the correct number of IOUringSocketChannel's are initialized 4) verify that the server stops */ @Disabled class IoUringTest { private static final Logger LOGGER = LoggerFactory.getLogger(IoUringTest.class); private static final boolean IS_OS_LINUX = "linux".equals(PlatformDependent.normalizedOs()); @BeforeEach void beforeTest() { final AbstractConfiguration config = ConfigurationManager.getConfigInstance(); config.setProperty("zuul.server.netty.socket.force_io_uring", "true"); config.setProperty("zuul.server.netty.socket.force_nio", "false"); } @Test void testIoUringServer() throws Exception { LOGGER.info("IOUring.isAvailable: {}", IOUring.isAvailable()); LOGGER.info("IS_OS_LINUX: {}", IS_OS_LINUX); if (IS_OS_LINUX) { exerciseIoUringServer(); } } private void exerciseIoUringServer() throws Exception { IOUring.ensureAvailability(); ServerStatusManager ssm = mock(ServerStatusManager.class); Map<NamedSocketAddress, ChannelInitializer<?>> initializers = new HashMap<>(); final List<IOUringSocketChannel> ioUringChannels = Collections.synchronizedList(new ArrayList<IOUringSocketChannel>()); ChannelInitializer<Channel> init = new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) { LOGGER.info("Channel: {}, isActive={}, isOpen={}", ch.getClass().getName(), ch.isActive(), ch.isOpen()); if (ch instanceof IOUringSocketChannel) { ioUringChannels.add((IOUringSocketChannel) ch); } } }; initializers.put(new NamedSocketAddress("test", new InetSocketAddress(0)), init); // The port to channel map keys on the port, post bind. This should be unique even if InetAddress is same initializers.put(new NamedSocketAddress("test2", new InetSocketAddress(0)), init); ClientConnectionsShutdown ccs = new ClientConnectionsShutdown( new DefaultChannelGroup(GlobalEventExecutor.INSTANCE), GlobalEventExecutor.INSTANCE, /* discoveryClient= */ null); EventLoopGroupMetrics elgm = new EventLoopGroupMetrics(Spectator.globalRegistry()); EventLoopConfig elc = new EventLoopConfig() { @Override public int eventLoopCount() { return 1; } @Override public int acceptorCount() { return 1; } }; Server s = new Server(new NoopRegistry(), ssm, initializers, ccs, elgm, elc); s.start(); List<NamedSocketAddress> addresses = s.getListeningAddresses(); assertEquals(2, addresses.size()); addresses.forEach(address -> { assertTrue(address.unwrap() instanceof InetSocketAddress); InetSocketAddress inetAddress = ((InetSocketAddress) address.unwrap()); assertNotEquals(0, inetAddress.getPort()); checkConnection(inetAddress.getPort()); }); await().atMost(1, TimeUnit.SECONDS).until(() -> ioUringChannels.size() == 2); s.stop(); assertEquals(2, ioUringChannels.size()); for (IOUringSocketChannel ch : ioUringChannels) { assertTrue(ch.isShutdown(), "isShutdown"); } } private static void checkConnection(final int port) { LOGGER.info("checkConnection port {}", port); Socket sock = null; try { InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", port); sock = new Socket(); sock.setSoTimeout(100); sock.connect(socketAddress, 100); OutputStream out = sock.getOutputStream(); out.write("Hello".getBytes(StandardCharsets.UTF_8)); out.flush(); out.close(); } catch (Exception exception) { fail("checkConnection failed. port=" + port + " " + exception); } finally { try { sock.close(); } catch (Exception ignored) { } } } }
6,185
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/ssl/SslHandshakeInfoHandlerTest.java
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.ssl; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelOutboundHandlerAdapter; import io.netty.channel.ChannelPromise; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.SslHandler; import io.netty.handler.ssl.util.SelfSignedCertificate; import io.netty.util.ReferenceCountUtil; import org.junit.jupiter.api.Test; import javax.net.ssl.SSLEngine; import java.nio.channels.ClosedChannelException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; /** * Unit tests for {@link SslHandshakeInfoHandler}. */ class SslHandshakeInfoHandlerTest { @Test void sslEarlyHandshakeFailure() throws Exception { EmbeddedChannel clientChannel = new EmbeddedChannel(); SSLEngine clientEngine = SslContextBuilder.forClient().build().newEngine(clientChannel.alloc()); clientChannel.pipeline().addLast(new SslHandler(clientEngine)); EmbeddedChannel serverChannel = new EmbeddedChannel(); SelfSignedCertificate cert = new SelfSignedCertificate("localhorse"); SSLEngine serverEngine = SslContextBuilder.forServer(cert.key(), cert.cert()).build().newEngine(serverChannel.alloc()); serverChannel.pipeline().addLast(new ChannelOutboundHandlerAdapter() { @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { // Simulate an early closure form the client. ReferenceCountUtil.safeRelease(msg); promise.setFailure(new ClosedChannelException()); } }); serverChannel.pipeline().addLast(new SslHandler(serverEngine)); serverChannel.pipeline().addLast(new SslHandshakeInfoHandler()); Object clientHello = clientChannel.readOutbound(); assertNotNull(clientHello); ReferenceCountUtil.retain(clientHello); serverChannel.writeInbound(clientHello); // Assert that the handler removes itself from the pipeline, since it was torn down. assertNull(serverChannel.pipeline().context(SslHandshakeInfoHandler.class)); } @Test void getFailureCauses() { SslHandshakeInfoHandler handler = new SslHandshakeInfoHandler(); RuntimeException noMessage = new RuntimeException(); assertEquals(noMessage.toString(), handler.getFailureCause(noMessage)); RuntimeException withMessage = new RuntimeException("some unexpected message"); assertEquals("some unexpected message", handler.getFailureCause(withMessage)); RuntimeException openSslMessage = new RuntimeException( "javax.net.ssl.SSLHandshakeException: error:1000008e:SSL routines:OPENSSL_internal:DIGEST_CHECK_FAILED"); assertEquals("DIGEST_CHECK_FAILED", handler.getFailureCause(openSslMessage)); } }
6,186
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2ContentLengthEnforcingHandlerTest.java
/* * Copyright 2021 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.http2; import io.netty.buffer.ByteBufUtil; import io.netty.buffer.UnpooledByteBufAllocator; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.DefaultHttpContent; import io.netty.handler.codec.http.DefaultHttpRequest; import io.netty.handler.codec.http.DefaultLastHttpContent; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpRequest; import io.netty.handler.codec.http.HttpVersion; import io.netty.handler.codec.http2.Http2ResetFrame; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; class Http2ContentLengthEnforcingHandlerTest { @Test void failsOnMultipleContentLength() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 2); chan.writeInbound(req); Object out = chan.readOutbound(); assertThat(out).isInstanceOf(Http2ResetFrame.class); } @Test void failsOnMixedContentLengthAndChunked() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, "identity, chunked"); req.headers().add(HttpHeaderNames.TRANSFER_ENCODING, "fzip"); chan.writeInbound(req); Object out = chan.readOutbound(); assertThat(out).isInstanceOf(Http2ResetFrame.class); } @Test void failsOnShortContentLength() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 1); chan.writeInbound(req); Object out = chan.readOutbound(); assertThat(out).isNull(); DefaultHttpContent content = new DefaultHttpContent(ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "a")); chan.writeInbound(content); out = chan.readOutbound(); assertThat(out).isNull(); DefaultHttpContent content2 = new DefaultHttpContent(ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "a")); chan.writeInbound(content2); out = chan.readOutbound(); assertThat(out).isInstanceOf(Http2ResetFrame.class); } @Test void failsOnShortContent() { EmbeddedChannel chan = new EmbeddedChannel(); chan.pipeline().addLast(new Http2ContentLengthEnforcingHandler()); DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, ""); req.headers().add(HttpHeaderNames.CONTENT_LENGTH, 2); chan.writeInbound(req); Object out = chan.readOutbound(); assertThat(out).isNull(); DefaultHttpContent content = new DefaultHttpContent(ByteBufUtil.writeUtf8(UnpooledByteBufAllocator.DEFAULT, "a")); chan.writeInbound(content); out = chan.readOutbound(); assertThat(out).isNull(); DefaultHttpContent content2 = new DefaultLastHttpContent(); chan.writeInbound(content2); out = chan.readOutbound(); assertThat(out).isInstanceOf(Http2ResetFrame.class); } }
6,187
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/http2/Http2OrHttpHandlerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.http2; import com.netflix.netty.common.Http2ConnectionCloseHandler; import com.netflix.netty.common.Http2ConnectionExpiryHandler; import com.netflix.netty.common.channel.config.ChannelConfig; import com.netflix.netty.common.channel.config.ChannelConfigValue; import com.netflix.netty.common.channel.config.CommonChannelConfigKeys; import com.netflix.netty.common.metrics.Http2MetricsChannelHandlers; import com.netflix.spectator.api.NoopRegistry; import com.netflix.zuul.netty.server.BaseZuulChannelInitializer; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http2.Http2FrameCodec; import io.netty.handler.codec.http2.Http2MultiplexHandler; import io.netty.handler.ssl.ApplicationProtocolNames; import org.junit.jupiter.api.Test; import static com.google.common.truth.Truth.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Argha C * @since November 18, 2020 */ class Http2OrHttpHandlerTest { @Test void swapInHttp2HandlerBasedOnALPN() throws Exception { EmbeddedChannel channel = new EmbeddedChannel(); final NoopRegistry registry = new NoopRegistry(); final ChannelConfig channelConfig = new ChannelConfig(); channelConfig.add(new ChannelConfigValue<>(CommonChannelConfigKeys.maxHttp2HeaderListSize, 32768)); Http2ConnectionCloseHandler connectionCloseHandler = new Http2ConnectionCloseHandler(registry); Http2ConnectionExpiryHandler connectionExpiryHandler = new Http2ConnectionExpiryHandler(100, 100, 20 * 60 * 1000); Http2MetricsChannelHandlers http2MetricsChannelHandlers = new Http2MetricsChannelHandlers(registry, "server", "http2-443"); final Http2OrHttpHandler http2OrHttpHandler = new Http2OrHttpHandler( new Http2StreamInitializer( channel, (x) -> {}, http2MetricsChannelHandlers, connectionCloseHandler, connectionExpiryHandler), channelConfig, cp -> {}); channel.pipeline().addLast("codec_placeholder", new DummyChannelHandler()); channel.pipeline().addLast(Http2OrHttpHandler.class.getSimpleName(), http2OrHttpHandler); http2OrHttpHandler.configurePipeline(channel.pipeline().lastContext(), ApplicationProtocolNames.HTTP_2); assertThat(channel.pipeline().get(Http2FrameCodec.class.getSimpleName() + "#0")) .isInstanceOf(Http2FrameCodec.class); assertThat(channel.pipeline().get(BaseZuulChannelInitializer.HTTP_CODEC_HANDLER_NAME)) .isInstanceOf(Http2MultiplexHandler.class); assertEquals("HTTP/2", channel.attr(Http2OrHttpHandler.PROTOCOL_NAME).get()); } }
6,188
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushMessageSenderInitializerTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.push; import io.netty.channel.Channel; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelPipeline; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpServerCodec; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.mockito.Mockito.mock; /** * Unit tests for {@link PushMessageSenderInitializer}. */ class PushMessageSenderInitializerTest { private PushMessageSenderInitializer initializer; private Channel channel; private ChannelHandler handler; @BeforeEach void setUp() { handler = mock(ChannelHandler.class); // Initialize mock handler initializer = new PushMessageSenderInitializer() { @Override protected void addPushMessageHandlers(ChannelPipeline pipeline) { pipeline.addLast("mockHandler", handler); } }; channel = new EmbeddedChannel(); } @Test void testInitChannel() throws Exception { initializer.initChannel(channel); assertNotNull(channel.pipeline().context(HttpServerCodec.class)); assertNotNull(channel.pipeline().context(HttpObjectAggregator.class)); assertNotNull(channel.pipeline().get("mockHandler")); } }
6,189
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushRegistrationHandlerTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.push; import com.google.common.util.concurrent.MoreExecutors; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelPipeline; import io.netty.channel.DefaultEventLoop; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.util.concurrent.ScheduledFuture; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; /** * @author Justin Guerra * @since 8/31/22 */ class PushRegistrationHandlerTest { private static ExecutorService EXECUTOR; @Captor private ArgumentCaptor<Runnable> scheduledCaptor; @Captor private ArgumentCaptor<Object> writeCaptor; @Mock private ChannelHandlerContext context; @Mock private ChannelFuture channelFuture; @Mock private ChannelPipeline pipelineMock; @Mock private Channel channel; private PushConnectionRegistry registry; private PushRegistrationHandler handler; private DefaultEventLoop eventLoopSpy; private TestAuth successfulAuth; @BeforeAll static void classSetup() { EXECUTOR = Executors.newSingleThreadExecutor(); } @AfterAll static void classCleanup() { MoreExecutors.shutdownAndAwaitTermination(EXECUTOR, 5, TimeUnit.SECONDS); } @BeforeEach void setup() { MockitoAnnotations.openMocks(this); registry = new PushConnectionRegistry(); handler = new PushRegistrationHandler(registry, PushProtocol.WEBSOCKET); successfulAuth = new TestAuth(true); eventLoopSpy = spy(new DefaultEventLoop(EXECUTOR)); doReturn(eventLoopSpy).when(context).executor(); doReturn(channelFuture).when(context).writeAndFlush(writeCaptor.capture()); doReturn(pipelineMock).when(context).pipeline(); doReturn(channel).when(context).channel(); } @Test void closeIfNotAuthenticated() throws Exception { doHandshakeComplete(); Runnable scheduledTask = scheduledCaptor.getValue(); scheduledTask.run(); validateConnectionClosed(1000, "Server closed connection"); } @Test void authFailed() throws Exception { doHandshakeComplete(); handler.userEventTriggered(context, new TestAuth(false)); validateConnectionClosed(1008, "Auth failed"); } @Test void authSuccess() throws Exception { doHandshakeComplete(); authenticateChannel(); } @Test void requestClientToCloseInactiveConnection() throws Exception { doHandshakeComplete(); Mockito.reset(eventLoopSpy); authenticateChannel(); verify(eventLoopSpy).schedule(scheduledCaptor.capture(), anyLong(), eq(TimeUnit.SECONDS)); Runnable requestClientToClose = scheduledCaptor.getValue(); requestClientToClose.run(); validateConnectionClosed(1000, "Server closed connection"); } @Test void requestClientToClose() throws Exception { doHandshakeComplete(); Mockito.reset(eventLoopSpy); authenticateChannel(); verify(eventLoopSpy).schedule(scheduledCaptor.capture(), anyLong(), eq(TimeUnit.SECONDS)); Runnable requestClientToClose = scheduledCaptor.getValue(); int taskListSize = handler.getScheduledFutures().size(); doReturn(true).when(channel).isActive(); requestClientToClose.run(); assertEquals(taskListSize + 1, handler.getScheduledFutures().size()); Object capture = writeCaptor.getValue(); assertTrue(capture instanceof TextWebSocketFrame); TextWebSocketFrame frame = (TextWebSocketFrame) capture; assertEquals("_CLOSE_", frame.text()); } @Test void channelInactiveCancelsTasks() throws Exception { doHandshakeComplete(); TestAuth testAuth = new TestAuth(true); authenticateChannel(); List<ScheduledFuture<?>> copyOfFutures = new ArrayList<>(handler.getScheduledFutures()); handler.channelInactive(context); assertNull(registry.get(testAuth.getClientIdentity())); assertTrue(handler.getScheduledFutures().isEmpty()); copyOfFutures.forEach(f -> assertTrue(f.isCancelled())); verify(context).close(); } private void doHandshakeComplete() throws Exception { handler.userEventTriggered(context, PushProtocol.WEBSOCKET.getHandshakeCompleteEvent()); assertNotNull(handler.getPushConnection()); verify(eventLoopSpy).schedule(scheduledCaptor.capture(), anyLong(), eq(TimeUnit.SECONDS)); } private void authenticateChannel() throws Exception { handler.userEventTriggered(context, successfulAuth); assertNotNull(registry.get(successfulAuth.getClientIdentity())); assertEquals(2, handler.getScheduledFutures().size()); verify(pipelineMock).remove(PushAuthHandler.NAME); } private void validateConnectionClosed(int expected, String messaged) { Object capture = writeCaptor.getValue(); assertTrue(capture instanceof CloseWebSocketFrame); CloseWebSocketFrame closeFrame = (CloseWebSocketFrame) capture; assertEquals(expected, closeFrame.statusCode()); assertEquals(messaged, closeFrame.reasonText()); verify(channelFuture).addListener(ChannelFutureListener.CLOSE); } private static class TestAuth implements PushUserAuth { private final boolean success; public TestAuth(boolean success) { this.success = success; } @Override public boolean isSuccess() { return success; } @Override public int statusCode() { return 0; } @Override public String getClientIdentity() { return "whatever"; } } }
6,190
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushAuthHandlerTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.push; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.http.DefaultFullHttpRequest; import io.netty.handler.codec.http.FullHttpRequest; import io.netty.handler.codec.http.HttpHeaderNames; import io.netty.handler.codec.http.HttpMethod; import io.netty.handler.codec.http.HttpVersion; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; class PushAuthHandlerTest { @Test void testIsInvalidOrigin() { ZuulPushAuthHandlerTest authHandler = new ZuulPushAuthHandlerTest(); final DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/ws", Unpooled.buffer()); // Invalid input assertTrue(authHandler.isInvalidOrigin(request)); request.headers().add(HttpHeaderNames.ORIGIN, "zuul-push.foo.com"); assertTrue(authHandler.isInvalidOrigin(request)); // Valid input request.headers().remove(HttpHeaderNames.ORIGIN); request.headers().add(HttpHeaderNames.ORIGIN, "zuul-push.netflix.com"); assertFalse(authHandler.isInvalidOrigin(request)); } class ZuulPushAuthHandlerTest extends PushAuthHandler { public ZuulPushAuthHandlerTest() { super("/ws", ".netflix.com"); } @Override protected boolean isDelayedAuth(FullHttpRequest req, ChannelHandlerContext ctx) { return false; } @Override protected PushUserAuth doAuth(FullHttpRequest req) { return null; } } }
6,191
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/server/push/PushConnectionRegistryTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.server.push; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; class PushConnectionRegistryTest { private PushConnectionRegistry pushConnectionRegistry; private PushConnection pushConnection; @BeforeEach void setUp() { pushConnectionRegistry = new PushConnectionRegistry(); pushConnection = mock(PushConnection.class); } @Test void testPutAndGet() { assertNull(pushConnectionRegistry.get("clientId1")); pushConnectionRegistry.put("clientId1", pushConnection); assertEquals(pushConnection, pushConnectionRegistry.get("clientId1")); } @Test void testGetAll() { pushConnectionRegistry.put("clientId1", pushConnection); pushConnectionRegistry.put("clientId2", pushConnection); List<PushConnection> connections = pushConnectionRegistry.getAll(); assertEquals(2, connections.size()); } @Test void testMintNewSecureToken() { String token = pushConnectionRegistry.mintNewSecureToken(); assertNotNull(token); assertEquals(20, token.length()); // 15 bytes become 20 characters when Base64-encoded } @Test void testPutAssignsTokenToConnection() { pushConnectionRegistry.put("clientId1", pushConnection); verify(pushConnection).setSecureToken(anyString()); } @Test void testRemove() { pushConnectionRegistry.put("clientId1", pushConnection); assertEquals(pushConnection, pushConnectionRegistry.remove("clientId1")); assertNull(pushConnectionRegistry.get("clientId1")); } @Test void testSize() { assertEquals(0, pushConnectionRegistry.size()); pushConnectionRegistry.put("clientId1", pushConnection); assertEquals(1, pushConnectionRegistry.size()); } }
6,192
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/DefaultClientChannelManagerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.connectionpool; import com.google.common.net.InetAddresses; import com.google.common.truth.Truth; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.discovery.DynamicServerResolver; import com.netflix.zuul.discovery.NonDiscoveryServer; import com.netflix.zuul.netty.server.Server; import com.netflix.zuul.origins.OriginName; import com.netflix.zuul.passport.CurrentPassport; import io.netty.channel.DefaultEventLoop; import io.netty.channel.EventLoop; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.util.concurrent.Promise; import org.junit.jupiter.api.Test; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.SocketAddress; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Tests for {@link DefaultClientChannelManager}. These tests don't use IPv6 addresses because {@link InstanceInfo} is * not capable of expressing them. */ class DefaultClientChannelManagerTest { @Test void pickAddressInternal_discovery() { InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("app") .setHostName("192.168.0.1") .setPort(443) .build(); DiscoveryResult s = DiscoveryResult.from(instanceInfo, true); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class); InetSocketAddress socketAddress = (InetSocketAddress) addr; assertEquals(InetAddresses.forString("192.168.0.1"), socketAddress.getAddress()); assertEquals(443, socketAddress.getPort()); } @Test void pickAddressInternal_discovery_unresolved() { InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("app") .setHostName("localhost") .setPort(443) .build(); DiscoveryResult s = DiscoveryResult.from(instanceInfo, true); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class); InetSocketAddress socketAddress = (InetSocketAddress) addr; assertTrue(socketAddress.getAddress().isLoopbackAddress(), socketAddress.toString()); assertEquals(443, socketAddress.getPort()); } @Test void pickAddressInternal_nonDiscovery() { NonDiscoveryServer s = new NonDiscoveryServer("192.168.0.1", 443); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class); InetSocketAddress socketAddress = (InetSocketAddress) addr; assertEquals(InetAddresses.forString("192.168.0.1"), socketAddress.getAddress()); assertEquals(443, socketAddress.getPort()); } @Test void pickAddressInternal_nonDiscovery_unresolved() { NonDiscoveryServer s = new NonDiscoveryServer("localhost", 443); SocketAddress addr = DefaultClientChannelManager.pickAddressInternal(s, OriginName.fromVip("vip")); Truth.assertThat(addr).isInstanceOf(InetSocketAddress.class); InetSocketAddress socketAddress = (InetSocketAddress) addr; assertTrue(socketAddress.getAddress().isLoopbackAddress(), socketAddress.toString()); assertEquals(443, socketAddress.getPort()); } @Test void updateServerRefOnEmptyDiscoveryResult() { OriginName originName = OriginName.fromVip("vip", "test"); final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); final DynamicServerResolver resolver = mock(DynamicServerResolver.class); when(resolver.resolve(any())).thenReturn(DiscoveryResult.EMPTY); final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, clientConfig, resolver, new DefaultRegistry()); final AtomicReference<DiscoveryResult> serverRef = new AtomicReference<>(); final Promise<PooledConnection> promise = clientChannelManager.acquire( new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); Truth.assertThat(promise.isSuccess()).isFalse(); Truth.assertThat(serverRef.get()).isSameInstanceAs(DiscoveryResult.EMPTY); } @Test void updateServerRefOnValidDiscoveryResult() { OriginName originName = OriginName.fromVip("vip", "test"); final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); final DynamicServerResolver resolver = mock(DynamicServerResolver.class); final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName("server-equality") .setHostName("server-equality") .setPort(7777) .build(); final DiscoveryResult discoveryResult = DiscoveryResult.from(instanceInfo, false); when(resolver.resolve(any())).thenReturn(discoveryResult); final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, clientConfig, resolver, new DefaultRegistry()); final AtomicReference<DiscoveryResult> serverRef = new AtomicReference<>(); // TODO(argha-c) capture and assert on the promise once we have a dummy with ServerStats initialized clientChannelManager.acquire( new DefaultEventLoop(), null, CurrentPassport.create(), serverRef, new AtomicReference<>()); Truth.assertThat(serverRef.get()).isSameInstanceAs(discoveryResult); } @Test void initializeAndShutdown() throws Exception { final String appName = "app-" + UUID.randomUUID(); final ServerSocket serverSocket = new ServerSocket(0); final InetSocketAddress serverSocketAddress = (InetSocketAddress) serverSocket.getLocalSocketAddress(); final String serverHostname = serverSocketAddress.getHostName(); final int serverPort = serverSocketAddress.getPort(); final OriginName originName = OriginName.fromVipAndApp("vip", appName); final DefaultClientConfigImpl clientConfig = new DefaultClientConfigImpl(); Server.defaultOutboundChannelType.set(NioSocketChannel.class); final InstanceInfo instanceInfo = Builder.newBuilder() .setAppName(appName) .setHostName(serverHostname) .setPort(serverPort) .build(); DiscoveryResult discoveryResult = DiscoveryResult.from(instanceInfo, true); final DynamicServerResolver resolver = mock(DynamicServerResolver.class); when(resolver.resolve(any())).thenReturn(discoveryResult); when(resolver.hasServers()).thenReturn(true); final Registry registry = new DefaultRegistry(); final DefaultClientChannelManager clientChannelManager = new DefaultClientChannelManager(originName, clientConfig, resolver, registry); final NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(10); final EventLoop eventLoop = eventLoopGroup.next(); clientChannelManager.init(); Truth.assertThat(clientChannelManager.getConnsInUse()).isEqualTo(0); final Promise<PooledConnection> promiseConn = clientChannelManager.acquire(eventLoop); promiseConn.await(200, TimeUnit.MILLISECONDS); assertTrue(promiseConn.isDone()); assertTrue(promiseConn.isSuccess()); final PooledConnection connection = promiseConn.get(); assertTrue(connection.isActive()); assertFalse(connection.isInPool()); Truth.assertThat(clientChannelManager.getConnsInUse()).isEqualTo(1); final boolean releaseResult = clientChannelManager.release(connection); assertTrue(releaseResult); assertTrue(connection.isInPool()); Truth.assertThat(clientChannelManager.getConnsInUse()).isEqualTo(0); clientChannelManager.shutdown(); serverSocket.close(); } }
6,193
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/connectionpool/PerServerConnectionPoolTest.java
/* * Copyright 2023 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.connectionpool; import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.Builder; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfigKey.Keys; import com.netflix.config.ConfigurationManager; import com.netflix.spectator.api.Counter; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.Timer; import com.netflix.zuul.discovery.DiscoveryResult; import com.netflix.zuul.netty.connectionpool.PooledConnection.ConnectionState; import com.netflix.zuul.netty.server.Server; import com.netflix.zuul.origins.OriginName; import com.netflix.zuul.passport.CurrentPassport; import com.netflix.zuul.passport.PassportState; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelInitializer; import io.netty.channel.DefaultEventLoopGroup; import io.netty.channel.EventLoop; import io.netty.channel.embedded.EmbeddedChannel; import io.netty.channel.local.LocalAddress; import io.netty.channel.local.LocalChannel; import io.netty.channel.local.LocalServerChannel; import io.netty.util.concurrent.Promise; import org.apache.commons.configuration.AbstractConfiguration; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.Deque; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.spy; /** * @author Justin Guerra * @since 2/24/23 */ class PerServerConnectionPoolTest { private static LocalAddress LOCAL_ADDRESS; private static DefaultEventLoopGroup ORIGIN_EVENT_LOOP_GROUP; private static DefaultEventLoopGroup CLIENT_EVENT_LOOP_GROUP; private static EventLoop CLIENT_EVENT_LOOP; private static Class<? extends Channel> PREVIOUS_CHANNEL_TYPE; @Mock private ClientChannelManager channelManager; private Registry registry; private DiscoveryResult discoveryResult; private DefaultClientConfigImpl clientConfig; private ConnectionPoolConfig connectionPoolConfig; private PerServerConnectionPool pool; private Counter createNewConnCounter; private Counter createConnSucceededCounter; private Counter createConnFailedCounter; private Counter requestConnCounter; private Counter reuseConnCounter; private Counter connTakenFromPoolIsNotOpen; private Counter closeAboveHighWaterMarkCounter; private Counter maxConnsPerHostExceededCounter; private Timer connEstablishTimer; private AtomicInteger connsInPool; private AtomicInteger connsInUse; @BeforeAll @SuppressWarnings("deprecation") static void staticSetup() throws InterruptedException { LOCAL_ADDRESS = new LocalAddress(UUID.randomUUID().toString()); CLIENT_EVENT_LOOP_GROUP = new DefaultEventLoopGroup(1); CLIENT_EVENT_LOOP = CLIENT_EVENT_LOOP_GROUP.next(); ORIGIN_EVENT_LOOP_GROUP = new DefaultEventLoopGroup(1); ServerBootstrap bootstrap = new ServerBootstrap() .group(ORIGIN_EVENT_LOOP_GROUP) .localAddress(LOCAL_ADDRESS) .channel(LocalServerChannel.class) .childHandler(new ChannelInitializer<LocalChannel>() { @Override protected void initChannel(LocalChannel ch) {} }); bootstrap.bind().sync(); PREVIOUS_CHANNEL_TYPE = Server.defaultOutboundChannelType.getAndSet(LocalChannel.class); } @AfterAll @SuppressWarnings("deprecation") static void staticCleanup() { ORIGIN_EVENT_LOOP_GROUP.shutdownGracefully(); CLIENT_EVENT_LOOP_GROUP.shutdownGracefully(); if (PREVIOUS_CHANNEL_TYPE != null) { Server.defaultOutboundChannelType.set(PREVIOUS_CHANNEL_TYPE); } } @BeforeEach void setup() { MockitoAnnotations.openMocks(this); registry = new DefaultRegistry(); int index = 0; createNewConnCounter = registry.counter("fake_counter" + index++); createConnSucceededCounter = registry.counter("fake_counter" + index++); createConnFailedCounter = registry.counter("fake_counter" + index++); requestConnCounter = registry.counter("fake_counter" + index++); reuseConnCounter = registry.counter("fake_counter" + index++); connTakenFromPoolIsNotOpen = registry.counter("fake_counter" + index++); closeAboveHighWaterMarkCounter = registry.counter("fake_counter" + index++); maxConnsPerHostExceededCounter = registry.counter("fake_counter" + index++); connEstablishTimer = registry.timer("fake_timer"); connsInPool = new AtomicInteger(); connsInUse = new AtomicInteger(); OriginName originName = OriginName.fromVipAndApp("whatever", "whatever-secure"); InstanceInfo instanceInfo = Builder.newBuilder() .setIPAddr("175.45.176.0") .setPort(7001) .setAppName("whatever") .build(); discoveryResult = DiscoveryResult.from(instanceInfo, true); clientConfig = new DefaultClientConfigImpl(); connectionPoolConfig = spy(new ConnectionPoolConfigImpl(originName, clientConfig)); NettyClientConnectionFactory nettyConnectionFactory = new NettyClientConnectionFactory(connectionPoolConfig, new ChannelInitializer<Channel>() { @Override protected void initChannel(Channel ch) {} }); PooledConnectionFactory pooledConnectionFactory = this::newPooledConnection; pool = new PerServerConnectionPool( discoveryResult, LOCAL_ADDRESS, nettyConnectionFactory, pooledConnectionFactory, connectionPoolConfig, clientConfig, createNewConnCounter, createConnSucceededCounter, createConnFailedCounter, requestConnCounter, reuseConnCounter, connTakenFromPoolIsNotOpen, closeAboveHighWaterMarkCounter, maxConnsPerHostExceededCounter, connEstablishTimer, connsInPool, connsInUse); } @Test void acquireNewConnectionHitsMaxConnections() { CurrentPassport currentPassport = CurrentPassport.create(); clientConfig.set(Keys.MaxConnectionsPerHost, 1); discoveryResult.incrementOpenConnectionsCount(); Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, currentPassport, new AtomicReference<>()); assertFalse(promise.isSuccess()); assertTrue(promise.cause() instanceof OriginConnectException); assertEquals(1, maxConnsPerHostExceededCounter.count()); } @Test void acquireNewConnection() throws InterruptedException, ExecutionException { CurrentPassport currentPassport = CurrentPassport.create(); Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, currentPassport, new AtomicReference<>()); PooledConnection connection = promise.sync().get(); assertEquals(1, requestConnCounter.count()); assertEquals(1, createNewConnCounter.count()); assertNotNull(currentPassport.findState(PassportState.ORIGIN_CH_CONNECTING)); assertNotNull(currentPassport.findState(PassportState.ORIGIN_CH_CONNECTED)); assertEquals(1, createConnSucceededCounter.count()); assertEquals(1, connsInUse.get()); // check state on PooledConnection - not all thread safe CLIENT_EVENT_LOOP .submit(() -> { checkChannelState(connection, currentPassport, 1); }) .sync(); } @Test void acquireConnectionFromPoolAndRelease() throws InterruptedException, ExecutionException { CurrentPassport currentPassport = CurrentPassport.create(); Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, currentPassport, new AtomicReference<>()); PooledConnection connection = promise.sync().get(); CLIENT_EVENT_LOOP .submit(() -> { pool.release(connection); }) .sync(); assertEquals(1, connsInPool.get()); CurrentPassport newPassport = CurrentPassport.create(); Promise<PooledConnection> secondPromise = pool.acquire(CLIENT_EVENT_LOOP, newPassport, new AtomicReference<>()); PooledConnection connection2 = secondPromise.sync().get(); assertEquals(connection, connection2); assertEquals(2, requestConnCounter.count()); assertEquals(0, connsInPool.get()); CLIENT_EVENT_LOOP .submit(() -> { checkChannelState(connection, newPassport, 2); }) .sync(); } @Test void releaseFromPoolButAlreadyClosed() throws InterruptedException, ExecutionException { CurrentPassport currentPassport = CurrentPassport.create(); Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, currentPassport, new AtomicReference<>()); PooledConnection connection = promise.sync().get(); CLIENT_EVENT_LOOP .submit(() -> { pool.release(connection); }) .sync(); // make the connection invalid connection.getChannel().deregister().sync(); CurrentPassport newPassport = CurrentPassport.create(); Promise<PooledConnection> secondPromise = pool.acquire(CLIENT_EVENT_LOOP, newPassport, new AtomicReference<>()); PooledConnection connection2 = secondPromise.sync().get(); assertNotEquals(connection, connection2); assertEquals(1, connTakenFromPoolIsNotOpen.count()); assertEquals(0, connsInPool.get()); assertTrue( connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "Channel should have been closed by pool"); } @Test void releaseFromPoolAboveHighWaterMark() throws InterruptedException, ExecutionException { CurrentPassport currentPassport = CurrentPassport.create(); AbstractConfiguration configuration = ConfigurationManager.getConfigInstance(); String propertyName = "whatever.netty.client.perServerWaterline"; Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, currentPassport, new AtomicReference<>()); PooledConnection connection = promise.sync().get(); try { configuration.setProperty(propertyName, 0); CLIENT_EVENT_LOOP .submit(() -> { assertFalse(pool.release(connection)); assertEquals(1, closeAboveHighWaterMarkCounter.count()); assertFalse(connection.isInPool()); }) .sync(); assertTrue( connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "connection should have been closed"); } finally { configuration.setProperty(propertyName, 4); } } @Test void releaseFromPoolWhileDraining() throws InterruptedException, ExecutionException { Promise<PooledConnection> promise = pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>()); PooledConnection connection = promise.sync().get(); pool.drain(); CLIENT_EVENT_LOOP .submit(() -> { assertFalse(connection.isInPool()); assertTrue( connection.getChannel().isActive(), "connection was incorrectly closed during the drain"); pool.release(connection); }) .sync(); assertTrue( connection.getChannel().closeFuture().await(5, TimeUnit.SECONDS), "connection should have been closed after release"); } @Test void acquireWhileDraining() { pool.drain(); assertFalse(pool.isAvailable()); assertThrows( IllegalStateException.class, () -> pool.acquire(CLIENT_EVENT_LOOP, CurrentPassport.create(), new AtomicReference<>())); } @Test void gracefulDrain() { EmbeddedChannel channel1 = new EmbeddedChannel(); EmbeddedChannel channel2 = new EmbeddedChannel(); PooledConnection connection1 = newPooledConnection(channel1); PooledConnection connection2 = newPooledConnection(channel2); Deque<PooledConnection> connections = pool.getPoolForEventLoop(channel1.eventLoop()); connections.add(connection1); connections.add(connection2); connsInPool.set(2); assertEquals(2, connsInPool.get()); pool.drainIdleConnectionsOnEventLoop(channel1.eventLoop()); channel1.runPendingTasks(); assertEquals(0, connsInPool.get()); assertTrue(connection1.getChannel().closeFuture().isSuccess()); assertTrue(connection2.getChannel().closeFuture().isSuccess()); } private void checkChannelState(PooledConnection connection, CurrentPassport passport, int expectedUsage) { Channel channel = connection.getChannel(); assertEquals(expectedUsage, connection.getUsageCount()); assertEquals(passport, CurrentPassport.fromChannelOrNull(channel)); assertFalse(connection.isReleased()); assertEquals(ConnectionState.WRITE_BUSY, connection.getConnectionState()); assertNull(channel.pipeline().get(DefaultClientChannelManager.IDLE_STATE_HANDLER_NAME)); } private PooledConnection newPooledConnection(Channel ch) { return new PooledConnection( ch, discoveryResult, channelManager, registry.counter("fake_close_counter"), registry.counter("fake_close_wrt_counter")); } }
6,194
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulFilterChainRunnerTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.filter; import com.netflix.spectator.api.Registry; import com.netflix.zuul.ExecutionStatus; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.filters.http.HttpInboundFilter; import com.netflix.zuul.filters.http.HttpOutboundFilter; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import rx.Observable; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; class ZuulFilterChainRunnerTest { private HttpRequestMessage request; private HttpResponseMessage response; @BeforeEach void before() { SessionContext context = new SessionContext(); Headers headers = new Headers(); ChannelHandlerContext chc = mock(ChannelHandlerContext.class); when(chc.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); context.put(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, chc); request = new HttpRequestMessageImpl( context, "http", "GET", "/foo/bar", new HttpQueryParams(), headers, "127.0.0.1", "http", 8080, "server123"); request.storeInboundRequest(); response = new HttpResponseMessageImpl(context, request, 200); } @Test void testInboundFilterChain() { final SimpleInboundFilter inbound1 = spy(new SimpleInboundFilter(true)); final SimpleInboundFilter inbound2 = spy(new SimpleInboundFilter(false)); final ZuulFilter[] filters = new ZuulFilter[] {inbound1, inbound2}; final FilterUsageNotifier notifier = mock(FilterUsageNotifier.class); final Registry registry = mock(Registry.class); final ZuulFilterChainRunner runner = new ZuulFilterChainRunner(filters, notifier, registry); runner.filter(request); verify(inbound1, times(1)).applyAsync(eq(request)); verify(inbound2, never()).applyAsync(eq(request)); verify(notifier).notify(eq(inbound1), eq(ExecutionStatus.SUCCESS)); verify(notifier).notify(eq(inbound2), eq(ExecutionStatus.SKIPPED)); verifyNoMoreInteractions(notifier); } @Test void testOutboundFilterChain() { final SimpleOutboundFilter outbound1 = spy(new SimpleOutboundFilter(true)); final SimpleOutboundFilter outbound2 = spy(new SimpleOutboundFilter(false)); final ZuulFilter[] filters = new ZuulFilter[] {outbound1, outbound2}; final FilterUsageNotifier notifier = mock(FilterUsageNotifier.class); final Registry registry = mock(Registry.class); final ZuulFilterChainRunner runner = new ZuulFilterChainRunner(filters, notifier, registry); runner.filter(response); verify(outbound1, times(1)).applyAsync(any()); verify(outbound2, never()).applyAsync(any()); verify(notifier).notify(eq(outbound1), eq(ExecutionStatus.SUCCESS)); verify(notifier).notify(eq(outbound2), eq(ExecutionStatus.SKIPPED)); verifyNoMoreInteractions(notifier); } class SimpleInboundFilter extends HttpInboundFilter { private final boolean shouldFilter; public SimpleInboundFilter(final boolean shouldFilter) { this.shouldFilter = shouldFilter; } @Override public int filterOrder() { return 0; } @Override public FilterType filterType() { return FilterType.INBOUND; } @Override public Observable<HttpRequestMessage> applyAsync(HttpRequestMessage input) { return Observable.just(input); } @Override public boolean shouldFilter(HttpRequestMessage msg) { return this.shouldFilter; } } class SimpleOutboundFilter extends HttpOutboundFilter { private final boolean shouldFilter; public SimpleOutboundFilter(final boolean shouldFilter) { this.shouldFilter = shouldFilter; } @Override public int filterOrder() { return 0; } @Override public FilterType filterType() { return FilterType.OUTBOUND; } @Override public Observable<HttpResponseMessage> applyAsync(HttpResponseMessage input) { return Observable.just(input); } @Override public boolean shouldFilter(HttpResponseMessage msg) { return this.shouldFilter; } } }
6,195
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/netty/filter/ZuulEndPointRunnerTest.java
/* * Copyright 2022 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.netty.filter; import com.netflix.spectator.api.NoopRegistry; import com.netflix.spectator.api.Registry; import com.netflix.zuul.Filter; import com.netflix.zuul.FilterCategory; import com.netflix.zuul.FilterLoader; import com.netflix.zuul.FilterUsageNotifier; import com.netflix.zuul.context.CommonContextKeys; import com.netflix.zuul.context.SessionContext; import com.netflix.zuul.filters.Endpoint; import com.netflix.zuul.filters.FilterType; import com.netflix.zuul.filters.ZuulFilter; import com.netflix.zuul.message.Headers; import com.netflix.zuul.message.ZuulMessage; import com.netflix.zuul.message.http.HttpQueryParams; import com.netflix.zuul.message.http.HttpRequestMessage; import com.netflix.zuul.message.http.HttpRequestMessageImpl; import com.netflix.zuul.message.http.HttpResponseMessage; import com.netflix.zuul.message.http.HttpResponseMessageImpl; import io.netty.channel.ChannelHandlerContext; import io.netty.util.concurrent.ImmediateEventExecutor; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import rx.Observable; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; class ZuulEndPointRunnerTest { private static final String BASIC_ENDPOINT = "basicEndpoint"; private ZuulEndPointRunner endpointRunner; private FilterUsageNotifier usageNotifier; private FilterLoader filterLoader; private FilterRunner filterRunner; private Registry registry; private HttpRequestMessageImpl request; @BeforeEach void beforeEachTest() { usageNotifier = mock(FilterUsageNotifier.class); filterLoader = mock(FilterLoader.class); when(filterLoader.getFilterByNameAndType(ZuulEndPointRunner.DEFAULT_ERROR_ENDPOINT.get(), FilterType.ENDPOINT)) .thenReturn(new ErrorEndpoint()); when(filterLoader.getFilterByNameAndType(BASIC_ENDPOINT, FilterType.ENDPOINT)) .thenReturn(new BasicEndpoint()); filterRunner = mock(FilterRunner.class); registry = new NoopRegistry(); endpointRunner = new ZuulEndPointRunner(usageNotifier, filterLoader, filterRunner, registry); SessionContext context = new SessionContext(); Headers headers = new Headers(); ChannelHandlerContext chc = mock(ChannelHandlerContext.class); when(chc.executor()).thenReturn(ImmediateEventExecutor.INSTANCE); context.put(CommonContextKeys.NETTY_SERVER_CHANNEL_HANDLER_CONTEXT, chc); request = new HttpRequestMessageImpl( context, "http", "GET", "/foo/bar", new HttpQueryParams(), headers, "127.0.0.1", "http", 8080, "server123"); request.storeInboundRequest(); } @Test void nonErrorEndpoint() { request.getContext().setShouldSendErrorResponse(false); request.getContext().setEndpoint(BASIC_ENDPOINT); assertNull(request.getContext().get(CommonContextKeys.ZUUL_ENDPOINT)); endpointRunner.filter(request); final ZuulFilter<HttpRequestMessage, HttpResponseMessage> filter = request.getContext().get(CommonContextKeys.ZUUL_ENDPOINT); assertTrue(filter instanceof BasicEndpoint); ArgumentCaptor<HttpResponseMessage> captor = ArgumentCaptor.forClass(HttpResponseMessage.class); verify(filterRunner, times(1)).filter(captor.capture()); final HttpResponseMessage capturedResponseMessage = captor.getValue(); assertEquals(capturedResponseMessage.getInboundRequest(), request.getInboundRequest()); assertEquals("basicEndpoint", capturedResponseMessage.getContext().getEndpoint()); assertFalse(capturedResponseMessage.getContext().errorResponseSent()); } @Test void errorEndpoint() { request.getContext().setShouldSendErrorResponse(true); assertNull(request.getContext().get(CommonContextKeys.ZUUL_ENDPOINT)); endpointRunner.filter(request); final ZuulFilter filter = request.getContext().get(CommonContextKeys.ZUUL_ENDPOINT); assertTrue(filter instanceof ErrorEndpoint); ArgumentCaptor<HttpResponseMessage> captor = ArgumentCaptor.forClass(HttpResponseMessage.class); verify(filterRunner, times(1)).filter(captor.capture()); final HttpResponseMessage capturedResponseMessage = captor.getValue(); assertEquals(capturedResponseMessage.getInboundRequest(), request.getInboundRequest()); assertNull(capturedResponseMessage.getContext().getEndpoint()); assertTrue(capturedResponseMessage.getContext().errorResponseSent()); } @Filter(order = 10, type = FilterType.ENDPOINT) static class ErrorEndpoint extends Endpoint { @Override public FilterCategory category() { return super.category(); } @Override public Observable applyAsync(ZuulMessage input) { return Observable.just(buildHttpResponseMessage(input)); } } @Filter(order = 20, type = FilterType.ENDPOINT) static class BasicEndpoint extends Endpoint { @Override public FilterCategory category() { return super.category(); } @Override public Observable applyAsync(ZuulMessage input) { return Observable.just(buildHttpResponseMessage(input)); } } private static HttpResponseMessage buildHttpResponseMessage(ZuulMessage request) { return new HttpResponseMessageImpl(request.getContext(), (HttpRequestMessage) request, 200); } }
6,196
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/passport/CurrentPassportTest.java
/* * Copyright 2018 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.passport; import org.junit.jupiter.api.Test; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; class CurrentPassportTest { @Test void test_findEachPairOf_1pair() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=IN_REQ_HEADERS_RECEIVED, +5=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=MISC_IO_STOP, +350=FILTERS_INBOUND_END, +1117794707=NOW]}"); List<StartAndEnd> pairs = passport.findEachPairOf( PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(1, pairs.size()); assertEquals(0, pairs.get(0).startTime); assertEquals(50, pairs.get(0).endTime); } @Test void test_findEachPairOf_2pairs() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=IN_REQ_HEADERS_RECEIVED, +5=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=MISC_IO_STOP, +300=MISC_IO_START, +350=FILTERS_INBOUND_END, +400=MISC_IO_STOP, +1117794707=NOW]}"); List<StartAndEnd> pairs = passport.findEachPairOf(PassportState.MISC_IO_START, PassportState.MISC_IO_STOP); assertEquals(2, pairs.size()); assertEquals(200, pairs.get(0).startTime); assertEquals(250, pairs.get(0).endTime); assertEquals(300, pairs.get(1).startTime); assertEquals(400, pairs.get(1).endTime); } @Test void test_findEachPairOf_noneFound() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +200=MISC_IO_START, +1117794707=NOW]}"); List<StartAndEnd> pairs = passport.findEachPairOf( PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test void test_findEachPairOf_endButNoStart() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +1117794707=NOW]}"); List<StartAndEnd> pairs = passport.findEachPairOf( PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test void test_findEachPairOf_wrongOrder() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=IN_REQ_HEADERS_RECEIVED, +1117794707=NOW]}"); List<StartAndEnd> pairs = passport.findEachPairOf( PassportState.IN_REQ_HEADERS_RECEIVED, PassportState.IN_REQ_LAST_CONTENT_RECEIVED); assertEquals(0, pairs.size()); } @Test void testFindBackwards() { CurrentPassport passport = CurrentPassport.parseFromToString( "CurrentPassport {start_ms=0, [+0=FILTERS_INBOUND_START, +50=IN_REQ_LAST_CONTENT_RECEIVED, +200=MISC_IO_START, +250=IN_REQ_HEADERS_RECEIVED, +1117794707=NOW]}"); assertEquals( 200, passport.findStateBackwards(PassportState.MISC_IO_START).getTime()); } @Test void testGetStateWithNoHistory() { assertNull(CurrentPassport.create().getState()); } }
6,197
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnCounterTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.monitoring; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Gauge; import com.netflix.spectator.api.Registry; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class ConnCounterTest { @Test void record() { EmbeddedChannel chan = new EmbeddedChannel(); Attrs attrs = Attrs.newInstance(); chan.attr(Server.CONN_DIMENSIONS).set(attrs); Registry registry = new DefaultRegistry(); ConnCounter counter = ConnCounter.install(chan, registry, registry.createId("foo")); counter.increment("start"); counter.increment("middle"); Attrs.newKey("bar").put(attrs, "baz"); counter.increment("end"); Gauge meter1 = registry.gauge(registry.createId("foo.start", "from", "nascent")); assertNotNull(meter1); assertEquals(1, meter1.value(), 0); Gauge meter2 = registry.gauge(registry.createId("foo.middle", "from", "start")); assertNotNull(meter2); assertEquals(1, meter2.value(), 0); Gauge meter3 = registry.gauge(registry.createId("foo.end", "from", "middle", "bar", "baz")); assertNotNull(meter3); assertEquals(1, meter3.value(), 0); } @Test void activeConnsCount() { EmbeddedChannel channel = new EmbeddedChannel(); Attrs attrs = Attrs.newInstance(); channel.attr(Server.CONN_DIMENSIONS).set(attrs); Registry registry = new DefaultRegistry(); ConnCounter.install(channel, registry, registry.createId("foo")); // Dedup increments ConnCounter.from(channel).increment("active"); ConnCounter.from(channel).increment("active"); assertEquals(1, ConnCounter.from(channel).getCurrentActiveConns(), 0); } }
6,198
0
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul
Create_ds/zuul/zuul-core/src/test/java/com/netflix/zuul/monitoring/ConnTimerTest.java
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.zuul.monitoring; import com.netflix.spectator.api.DefaultRegistry; import com.netflix.spectator.api.Registry; import com.netflix.spectator.api.histogram.PercentileTimer; import com.netflix.zuul.Attrs; import com.netflix.zuul.netty.server.Server; import io.netty.channel.embedded.EmbeddedChannel; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; class ConnTimerTest { @Test void record() { EmbeddedChannel chan = new EmbeddedChannel(); Attrs attrs = Attrs.newInstance(); chan.attr(Server.CONN_DIMENSIONS).set(attrs); Registry registry = new DefaultRegistry(); ConnTimer timer = ConnTimer.install(chan, registry, registry.createId("foo")); timer.record(1000L, "start"); timer.record(2000L, "middle"); Attrs.newKey("bar").put(attrs, "baz"); timer.record(4000L, "end"); PercentileTimer meter1 = PercentileTimer.get(registry, registry.createId("foo.start-middle")); assertNotNull(meter1); assertEquals(1000L, meter1.totalTime()); PercentileTimer meter2 = PercentileTimer.get(registry, registry.createId("foo.middle-end", "bar", "baz")); assertNotNull(meter2); assertEquals(2000L, meter2.totalTime()); PercentileTimer meter3 = PercentileTimer.get(registry, registry.createId("foo.start-end", "bar", "baz")); assertNotNull(meter3); assertEquals(3000L, meter3.totalTime()); } }
6,199