Java Code Examples for okhttp3.mockwebserver.MockWebServer#setDispatcher()

The following examples show how to use okhttp3.mockwebserver.MockWebServer#setDispatcher() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: IsochroneTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(ISOCHRONE_WITH_POLYGONS_VALID);
                if (request.getPath().contains("polygons=false")) {
                    response = loadJsonFixture(ISOCHRONE_NO_POLYGONS_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example 2
Source File: MapboxDirectionsRefreshTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

      String resource = DIRECTIONS_REFRESH_V1_FIXTURE;

      try {
        String body = loadJsonFixture(resource);
        return new MockResponse().setBody(body);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example 3
Source File: MapMatchingTracepointTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  server = new MockWebServer();
  server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      try {
        String response = loadJsonFixture(MAP_MATCHING_FIXTURE);
        return new MockResponse().setBody(response);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");

  coordinates = new ArrayList<>();
  coordinates.add(Point.fromLngLat(13.418946862220764, 52.50055852688439));
  coordinates.add(Point.fromLngLat(13.419011235237122, 52.50113000479732));
  coordinates.add(Point.fromLngLat(13.419756889343262, 52.50171780290061));
  coordinates.add(Point.fromLngLat(13.419885635375975, 52.50237416816131));
  coordinates.add(Point.fromLngLat(13.420631289482117, 52.50294888790448));
}
 
Example 4
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMemoRequiredAccountNotFound() throws IOException, AccountRequiresMemoException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(buildTestCheckMemoRequiredMockDispatcher());
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    KeyPair source = KeyPair.fromSecretSeed("SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY");
    Account account = new Account(source.getAccountId(), 1L);
    Transaction transaction = new Transaction.Builder(account, Network.PUBLIC)
            .addOperation(new PaymentOperation.Builder(DESTINATION_ACCOUNT_NO_FOUND, new AssetTypeNative(), "10").build())
            .addOperation(new PathPaymentStrictReceiveOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_NO_FOUND, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new PathPaymentStrictSendOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_NO_FOUND, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new AccountMergeOperation.Builder(DESTINATION_ACCOUNT_NO_FOUND).build())
            .setTimeout(Transaction.Builder.TIMEOUT_INFINITE)
            .setBaseFee(100)
            .build();
    transaction.sign(source);
    server.submitTransaction(transaction);
    server.submitTransaction(feeBump(transaction));
}
 
Example 5
Source File: OAuthApiConnectionTest.java    From Wikidata-Toolkit with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void init() throws IOException {
    Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            switch (request.getBody().readUtf8()) {
                case "languages=fr&assert=user&format=json&action=wbgetentities&ids=Q8&sitefilter=enwiki&props=info%7Cdatatype%7Clabels%7Caliases%7Cdescriptions%7Csitelinks":
                    return new MockResponse()
                            .addHeader("Content-Type", "application/json; charset=utf-8")
                            .setBody("{\"entities\":{\"Q8\":{\"pageid\":134,\"ns\":0,\"title\":\"Q8\",\"lastrevid\":1174289176,\"modified\":\"2020-05-05T12:39:07Z\",\"type\":\"item\",\"id\":\"Q8\",\"labels\":{\"fr\":{\"language\":\"fr\",\"value\":\"bonheur\"}},\"descriptions\":{\"fr\":{\"language\":\"fr\",\"value\":\"état émotionnel\"}},\"aliases\":{\"fr\":[{\"language\":\"fr\",\"value\":\":)\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE04\"},{\"language\":\"fr\",\"value\":\"\uD83D\uDE03\"}]},\"sitelinks\":{\"enwiki\":{\"site\":\"enwiki\",\"title\":\"Happiness\",\"badges\":[]}}}},\"success\":1}");
                case "meta=userinfo&assert=user&format=json&action=query":
                    return new MockResponse()
                            .addHeader("Content-Type", "application/json; charset=utf-8")
                            .setBody("{\"batchcomplete\":\"\",\"query\":{\"userinfo\":{\"id\":2333,\"name\":\"foo\"}}}");
                default:
                    return new MockResponse().setResponseCode(404);
            }
        }
    };

    server = new MockWebServer();
    server.setDispatcher(dispatcher);
    server.start();
}
 
Example 6
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMemoRequiredWithSkipCheck() throws IOException, AccountRequiresMemoException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(buildTestCheckMemoRequiredMockDispatcher());
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    KeyPair source = KeyPair.fromSecretSeed("SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY");
    Account account = new Account(source.getAccountId(), 1L);
    Transaction transaction = new Transaction.Builder(account, Network.PUBLIC)
            .addOperation(new PaymentOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_A, new AssetTypeNative(), "10").build())
            .addOperation(new PathPaymentStrictReceiveOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_NO_MEMO_REQUIRED, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new PathPaymentStrictSendOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_NO_MEMO_REQUIRED, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new AccountMergeOperation.Builder(DESTINATION_ACCOUNT_NO_MEMO_REQUIRED).build())
            .setTimeout(Transaction.Builder.TIMEOUT_INFINITE)
            .setBaseFee(100)
            .build();
    transaction.sign(source);
    server.submitTransaction(transaction, true);
    server.submitTransaction(feeBump(transaction), true);
}
 
Example 7
Source File: MapboxSpeechTest.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws IOException {
  mockWebServer = new MockWebServer();

  mockWebServer.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      okio.Buffer buffer = new okio.Buffer();
      try {
        buffer.writeAll(Okio.source(new File("src/test/resources/test_response.mp3")));
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
      return new MockResponse().setBody(buffer);
    }
  });

  mockWebServer.start();
  mockUrl = mockWebServer.url("");

}
 
Example 8
Source File: ServerTest.java    From java-stellar-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckMemoRequiredWithMemo() throws IOException, AccountRequiresMemoException {
    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(buildTestCheckMemoRequiredMockDispatcher());
    mockWebServer.start();
    HttpUrl baseUrl = mockWebServer.url("");
    Server server = new Server(baseUrl.toString());

    KeyPair source = KeyPair.fromSecretSeed("SDQXFKA32UVQHUTLYJ42N56ZUEM5PNVVI4XE7EA5QFMLA2DHDCQX3GPY");
    Account account = new Account(source.getAccountId(), 1L);
    Transaction transaction = new Transaction.Builder(account, Network.PUBLIC)
            .addOperation(new PaymentOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_A, new AssetTypeNative(), "10").build())
            .addOperation(new PathPaymentStrictReceiveOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_B, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new PathPaymentStrictSendOperation.Builder(new AssetTypeNative(), "10", DESTINATION_ACCOUNT_MEMO_REQUIRED_C, new AssetTypeCreditAlphaNum4("BTC", "GA7GYB3QGLTZNHNGXN3BMANS6TC7KJT3TCGTR763J4JOU4QHKL37RVV2"), "5").build())
            .addOperation(new AccountMergeOperation.Builder(DESTINATION_ACCOUNT_MEMO_REQUIRED_D).build())
            .setTimeout(Transaction.Builder.TIMEOUT_INFINITE)
            .addMemo(new MemoText("Hello, Stellar."))
            .setBaseFee(100)
            .build();
    transaction.sign(source);
    server.submitTransaction(transaction);
    server.submitTransaction(feeBump(transaction));
}
 
Example 9
Source File: TilequeryTestUtils.java    From mapbox-java with MIT License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            try {
                String response = loadJsonFixture(TILEQUERY_VALID);
                if (request.getPath().contains("limit")) {
                    response = loadJsonFixture(TILEQUERY_ALL_PARAM_VALID);
                }
                return new MockResponse().setBody(response);
            } catch (IOException ioException) {
                throw new RuntimeException(ioException);
            }
        }
    });
    server.start();
    mockUrl = server.url("");
}
 
Example 10
Source File: ExternalRecommenderIntegrationTest.java    From inception with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception
{
    casStorageSession = CasStorageSession.open();
    recommender = buildRecommender();
    context = new RecommenderContext();

    traits = new ExternalRecommenderTraits();
    sut = new ExternalRecommender(recommender, traits);

    remoteRecommender = new RemoteStringMatchingNerRecommender(recommender);

    server = new MockWebServer();
    server.setDispatcher(buildDispatcher());
    server.start();

    requestBodies = new ArrayList<>();

    String url = server.url("/").toString();
    traits.setRemoteUrl(url);
}
 
Example 11
Source File: SessionAuthenticationServiceTest.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    mAuthStateManager = AuthStateManager.getInstance(RuntimeEnvironment.application);

    MockWebServer server = new MockWebServer();
    dispatcher = new CustomDispatcher();
    server.setDispatcher(dispatcher);

    SSLSocketFactory sslSocketFactory = TestUtils.getSSL(this);
    HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });
    server.useHttps(sslSocketFactory, false);
    server.start();
    String baseUrl = server.url("/").toString();
    authorizationRequest = TestUtils.getMinimalAuthRequestBuilder(baseUrl, ResponseTypeValues.CODE);

    mAuthService = new AuthorizationService(RuntimeEnvironment.application.getApplicationContext(), new AppAuthConfiguration.Builder().setConnectionBuilder(ConnectionBuilderForTest.INSTANCE).build());

    sessionAuthenticationService = new SessionAuthenticationService(mAuthStateManager, mAuthService, new ConnectionBuilder() {
        @NonNull
        @Override
        public HttpURLConnection openConnection(@NonNull Uri uri) throws IOException {
            return DefaultOktaConnectionBuilder.INSTANCE.openConnection(uri);
        }
    });

    request = authorizationRequest.build();
    dispatcher.nonce = request.nonce;
}
 
Example 12
Source File: MapboxMatrixTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
  server = new MockWebServer();

  server.setDispatcher(new Dispatcher() {

    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      try {
        String resource;
        if (request.getPath().contains("walking")) {
          resource = DIRECTIONS_MATRIX_WALKING_1X3_FIXTURE;

        } else if (request.getPath().contains("cycling")) {
          resource = DIRECTIONS_MATRIX_CYCLING_2X3_FIXTURE;

        } else { // driving
          resource = DIRECTIONS_MATRIX_DRIVING_3X3_FIXTURE;
        }
        String response = loadJsonFixture(resource);
        return new MockResponse().setBody(response);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });
  server.start();
  mockUrl = server.url("");

  positions = new ArrayList<>();
  positions.add(Point.fromLngLat(-122.42, 37.78));
  positions.add(Point.fromLngLat(-122.45, 37.91));
  positions.add(Point.fromLngLat(-122.48, 37.73));
}
 
Example 13
Source File: OptimizationResponseTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final String json = loadJsonFixture(OPTIMIZATION_FIXTURE);
  object = new JsonParser().parse(json).getAsJsonObject();

  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return new MockResponse().setBody(json);
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example 14
Source File: OptimizationWaypointTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  final String json = loadJsonFixture(OPTIMIZATION_FIXTURE);
  object = new JsonParser().parse(json).getAsJsonObject();

  server = new MockWebServer();
  server.setDispatcher(new Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
      return new MockResponse().setBody(json);
    }
  });
  server.start();
  mockUrl = server.url("");
}
 
Example 15
Source File: MapboxMapMatchingTest.java    From mapbox-java with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  server = new MockWebServer();
  server.setDispatcher(new okhttp3.mockwebserver.Dispatcher() {
    @Override
    public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
        String resource = MAP_MATCHING_FIXTURE;
        if (request.getPath().contains("approaches")) {
          resource = MAP_MATCHING_APPROACHES;
        } else if (request.getPath().contains("waypoint_names")) {
          resource = MAP_MATCHING_WAYPOINT_NAMES_FIXTURE;
        } else if (request.getPath().contains("0,-40;0,-20")) { // no matching segment
          resource = MAP_MATCHING_ERROR_FIXTURE;
        }
          try {
        String response = loadJsonFixture(resource);
        return new MockResponse().setBody(response);
      } catch (IOException ioException) {
        throw new RuntimeException(ioException);
      }
    }
  });

  coordinates = new ArrayList<>();
  coordinates.add(Point.fromLngLat(13.418946862220764, 52.50055852688439));
  coordinates.add(Point.fromLngLat(13.419011235237122, 52.50113000479732));
  coordinates.add(Point.fromLngLat(13.419756889343262, 52.50171780290061));
  coordinates.add(Point.fromLngLat(13.419885635375975, 52.50237416816131));
  coordinates.add(Point.fromLngLat(13.420631289482117, 52.50294888790448));

  server.start();
  mockUrl = server.url("");
}
 
Example 16
Source File: OkHttpBaseTestCase.java    From edx-app-android with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    server = new MockWebServer();
    server.setDispatcher(new MockResponseDispatcher());
    server.start();

    super.setUp();
}
 
Example 17
Source File: WebServerBuilder.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public WebServerBuilder() {
  server = new MockWebServer();
  QueueDispatcher dispatcher = new QueueDispatcher();
  dispatcher.setFailFast(new MockResponse().setResponseCode(400));
  server.setDispatcher(dispatcher);
}
 
Example 18
Source File: OktaAppAuthTest.java    From okta-sdk-appauth-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testAllTokenRevocationRefreshTokenFailure() throws JSONException, InterruptedException {
    final String testRefreshToken = "testRefreshToken";
    final String  testClientId = "clientId";
    AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class);
    AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class);

    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            String url = request.getPath();
            if (url.contains(TestUtils.REVOKE_URI)
                    && url.contains(testClientId)
                    && (url.contains(testRefreshToken))
                    ){
                return new MockResponse().setResponseCode(400);
            }
            return new MockResponse().setResponseCode(404);
        }
    });
    String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString();
    sut.mClientId.set(testClientId);

    ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils
            .addField(new JSONObject(),
                    RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl
            ));

    ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc);

    when(mAuthStateManager.getCurrent()).thenReturn(mAuthState);
    when(mAuthState.getAuthorizationServiceConfiguration())
            .thenReturn(configurationMoc);
    when(mAuthState.getRefreshToken()).thenReturn(testRefreshToken);

    when(mAuthState.isAuthorized()).thenReturn(true);

    final AtomicBoolean isPassed = new AtomicBoolean();
    final CountDownLatch latch = new CountDownLatch(1);

    sut.revoke(new OktaAppAuth.OktaRevokeListener() {
        @Override
        public void onSuccess() {
            isPassed.set(false);
            latch.countDown();
        }

        @Override
        public void onError(AuthorizationException ex) {
            if (ex.type == AuthorizationException.TYPE_OAUTH_TOKEN_ERROR) {
                isPassed.set(true);
            }
            latch.countDown();
        }
    });

    latch.await();
    assertTrue("onSuccess has been called",isPassed.get());
}
 
Example 19
Source File: XsuaaMockWebServer.java    From cloud-security-xsuaa-integration with Apache License 2.0 4 votes vote down vote up
private static MockWebServer createMockWebServer(Dispatcher dispatcher) {
	Assert.notNull(dispatcher, "Dispatcher required");
	MockWebServer mockWebServer = new MockWebServer();
	mockWebServer.setDispatcher(dispatcher);
	return mockWebServer;
}
 
Example 20
Source File: OktaAppAuthTest.java    From okta-sdk-appauth-android with Apache License 2.0 4 votes vote down vote up
@Test
public void testAccessTokenRevocationSuccess() throws JSONException, InterruptedException {
    final String testAccessToken = "testAccesToken";
    final String  testClientId = "clientId";
    AuthorizationServiceDiscovery discoveryMoc = mock(AuthorizationServiceDiscovery.class);
    AuthorizationServiceConfiguration configurationMoc = mock(AuthorizationServiceConfiguration.class);

    MockWebServer mockWebServer = new MockWebServer();
    mockWebServer.setDispatcher(new Dispatcher() {
        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
            String url = request.getPath();
            if (url.contains(TestUtils.REVOKE_URI)
                   && url.contains(testAccessToken)
                    && url.contains(testClientId)){
                return new MockResponse().setResponseCode(200);
            }
            return new MockResponse().setResponseCode(404);
        }
    });
    String tokenRevocationUrl = mockWebServer.url(TestUtils.REVOKE_URI).toString();
    sut.mClientId.set(testClientId);

    ReflectionUtils.refectSetValue(discoveryMoc, "docJson", TestUtils
            .addField(new JSONObject(),
                    RevokeTokenRequest.REVOKE_ENDPOINT_KEY, tokenRevocationUrl
            ));

    ReflectionUtils.refectSetValue(configurationMoc, "discoveryDoc", discoveryMoc);

    when(mAuthStateManager.getCurrent()).thenReturn(mAuthState);
    when(mAuthState.getAuthorizationServiceConfiguration())
            .thenReturn(configurationMoc);

    final AtomicBoolean isPassed = new AtomicBoolean();
    final CountDownLatch latch = new CountDownLatch(1);

    sut.revoke(testAccessToken, new OktaAppAuth.OktaRevokeListener() {
        @Override
        public void onSuccess() {
            isPassed.set(true);
            latch.countDown();
        }

        @Override
        public void onError(AuthorizationException ex) {
            isPassed.set(false);
            latch.countDown();
        }
    });

    latch.await();
    assertTrue("onError has been called",isPassed.get());
}