com.squareup.okhttp.HttpUrl Java Examples

The following examples show how to use com.squareup.okhttp.HttpUrl. 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: Auth0.java    From Auth0.Android with MIT License 6 votes vote down vote up
private HttpUrl resolveConfiguration(@Nullable String configurationDomain, @NonNull HttpUrl domainUrl) {
    HttpUrl url = ensureValidUrl(configurationDomain);
    if (url == null) {
        final String host = domainUrl.host();
        if (host.endsWith(DOT_AUTH0_DOT_COM)) {
            String[] parts = host.split("\\.");
            if (parts.length > 3) {
                url = HttpUrl.parse("https://cdn." + parts[parts.length - 3] + DOT_AUTH0_DOT_COM);
            } else {
                url = HttpUrl.parse(AUTH0_US_CDN_URL);
            }
        } else {
            url = domainUrl;
        }
    }
    return url;
}
 
Example #2
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 6 votes vote down vote up
/**
 * Requests new Credentials using a valid Refresh Token. The received token will have the same audience and scope as first requested. How the new Credentials are requested depends on the {@link Auth0#isOIDCConformant()} flag.
 * - If the instance is OIDC Conformant the endpoint will be /oauth/token with 'refresh_token' grant, and the response will include an id_token and an access_token if 'openid' scope was requested when the refresh_token was obtained.
 * In addition, if the application has Refresh Token Rotation configured, a new one-time use refresh token will also be included in the response.
 * - If the instance is not OIDC Conformant the endpoint will be /delegation with 'urn:ietf:params:oauth:grant-type:jwt-bearer' grant, and the response will include an id_token.
 * Example usage:
 * <pre>
 * {@code
 * client.renewAuth("{refresh_token}")
 *      .addParameter("scope", "openid profile email")
 *      .start(new BaseCallback<Credentials>() {
 *          {@literal}Override
 *          public void onSuccess(Credentials payload) { }
 *
 *          {@literal}@Override
 *          public void onFailure(AuthenticationException error) { }
 *      });
 * }
 * </pre>
 *
 * @param refreshToken used to fetch the new Credentials.
 * @return a request to start
 */
@SuppressWarnings("WeakerAccess")
public ParameterizableRequest<Credentials, AuthenticationException> renewAuth(@NonNull String refreshToken) {
    final Map<String, Object> parameters = ParameterBuilder.newBuilder()
            .setClientId(getClientId())
            .setRefreshToken(refreshToken)
            .setGrantType(auth0.isOIDCConformant() ? ParameterBuilder.GRANT_TYPE_REFRESH_TOKEN : ParameterBuilder.GRANT_TYPE_JWT)
            .asDictionary();

    HttpUrl url;
    if (auth0.isOIDCConformant()) {
        url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
                .addPathSegment(OAUTH_PATH)
                .addPathSegment(TOKEN_PATH)
                .build();
    } else {
        url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
                .addPathSegment(DELEGATION_PATH)
                .build();
    }

    return factory.POST(url, client, gson, Credentials.class, authErrorBuilder)
            .addParameters(parameters);
}
 
Example #3
Source File: LastUpdatedManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Session get() {
    String serverUrlString = getString(SERVER_URI);
    String userNameString = getString(USERNAME);
    String passwordString = getString(PASSWORD);

    HttpUrl serverUrl = null;
    if (serverUrlString != null) {
        serverUrl = HttpUrl.parse(serverUrlString);
    }

    Credentials credentials = null;
    if (userNameString != null && passwordString != null) {
        credentials = new Credentials(
                userNameString, passwordString
        );
    }
    return new Session(serverUrl, credentials);
}
 
Example #4
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 6 votes vote down vote up
public Optional<Response> saveIntegrationPluginOfType(SaveSCMPluginConfigRequest saveSCMPluginConfigRequest) throws JsonProcessingException {

        HttpUrl httpUrl = getSaveIntegrationPluginConfigURL(saveSCMPluginConfigRequest);
        MediaType mediaType = MediaType.parse("application/json");
        Request httpRequest = buildPutRequest(httpUrl, mediaType, saveSCMPluginConfigRequest.getRequestBody());
        try {
            Response response = client.newCall(httpRequest).execute();
            if(!response.isSuccessful()){
                log.error(String.format("Error when attempting to save %s plugin integration for API %s version %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(),saveSCMPluginConfigRequest.getVersion()));
                log.error("Error response: "+response.body().string());
                response.body().close();
            }
            return Optional.ofNullable(response);
        } catch (IOException e) {
            log.error(String.format("Error when attempting to save %s plugin integration for API %s. Error message %s", saveSCMPluginConfigRequest.getScmProvider(), saveSCMPluginConfigRequest.getApi(), e.getMessage()));
            return Optional.empty();
        }

    }
 
Example #5
Source File: BaseAuthenticationRequestTest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Test
public void shouldWhiteListLegacyParametersOnNonLegacyEndpoints() throws Exception {
    HashMap<String, Object> parameters = new HashMap<>();
    parameters.put("extra", "value");
    parameters.put("connection", "my-connection");
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.addAuthenticationParameters(parameters)
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("extra", "value"));
    assertThat(body, not(hasKey("connection")));
}
 
Example #6
Source File: BaseAuthenticationRequestTest.java    From Auth0.Android with MIT License 6 votes vote down vote up
@Test
public void shouldSetRealm() throws Exception {
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();
    AuthenticationRequest req = createRequest(url);
    mockAPI.willReturnSuccessfulLogin();
    req.setRealm("users")
            .execute();

    final RecordedRequest request = mockAPI.takeRequest();
    Map<String, String> body = bodyFromRequest(request);
    assertThat(body, hasEntry("realm", "users"));
}
 
Example #7
Source File: OkHttpClientTransport.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
private Request createHttpProxyRequest(InetSocketAddress address, String proxyUsername,
    String proxyPassword) {
  HttpUrl tunnelUrl = new HttpUrl.Builder()
      .scheme("https")
      .host(address.getHostName())
      .port(address.getPort())
      .build();
  Request.Builder request = new Request.Builder()
      .url(tunnelUrl)
      .header("Host", tunnelUrl.host() + ":" + tunnelUrl.port())
      .header("User-Agent", userAgent);

  // If we have proxy credentials, set them right away
  if (proxyUsername != null && proxyPassword != null) {
    request.header("Proxy-Authorization", Credentials.basic(proxyUsername, proxyPassword));
  }
  return request.build();
}
 
Example #8
Source File: LastUpdatedManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void put(Session session) {
    isNull(session, "Session object must not be null");
    HttpUrl serverUrl = session.getServerUrl();
    Credentials credentials = session.getCredentials();

    String url = null;
    String username = null;
    String password = null;

    if (serverUrl != null) {
        url = serverUrl.toString();
    }

    if (credentials != null) {
        username = credentials.getUsername();
        password = credentials.getPassword();
    }

    putString(SERVER_URI, url);
    putString(USERNAME, username);
    putString(PASSWORD, password);
}
 
Example #9
Source File: IntegrationApiModule.java    From android-step-by-step with Apache License 2.0 6 votes vote down vote up
public ApiInterface getApiInterface(MockWebServer mockWebServer) throws IOException {
    mockWebServer.start();
    TestUtils testUtils = new TestUtils();
    final Dispatcher dispatcher = new Dispatcher() {

        @Override
        public MockResponse dispatch(RecordedRequest request) throws InterruptedException {

            if (request.getPath().equals("/users/" + TestConst.TEST_OWNER + "/repos")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/repos.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/branches")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/branches.json"));
            } else if (request.getPath().equals("/repos/" + TestConst.TEST_OWNER + "/" + TestConst.TEST_REPO + "/contributors")) {
                return new MockResponse().setResponseCode(200)
                        .setBody(testUtils.readString("json/contributors.json"));
            }
            return new MockResponse().setResponseCode(404);
        }
    };

    mockWebServer.setDispatcher(dispatcher);
    HttpUrl baseUrl = mockWebServer.url("/");
    return ApiModule.getApiInterface(baseUrl.toString());
}
 
Example #10
Source File: BaseRoboTest.java    From mobile-sdk-android with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    SDKSettings.setExternalExecutor(null);
    Robolectric.getBackgroundThreadScheduler().reset();
    Robolectric.getForegroundThreadScheduler().reset();
    ShadowLog.stream = System.out;
    activity = Robolectric.buildActivity(MockMainActivity.class).create().start().resume().visible().get();
    shadowOf(activity).grantPermissions("android.permission.INTERNET");
    server= new MockWebServer();
    try {
        server.start();
        HttpUrl url= server.url("/");
        UTConstants.REQUEST_BASE_URL_UT = url.toString();
        System.out.println(UTConstants.REQUEST_BASE_URL_UT);
        ShadowSettings.setTestURL(url.toString());
        TestResponsesUT.setTestURL(url.toString());
    } catch (IOException e) {
        System.out.print("IOException");
    }
    bgScheduler = Robolectric.getBackgroundThreadScheduler();
    uiScheduler = Robolectric.getForegroundThreadScheduler();
    Robolectric.flushBackgroundThreadScheduler();
    Robolectric.flushForegroundThreadScheduler();
    bgScheduler.pause();
    uiScheduler.pause();
}
 
Example #11
Source File: SwaggerHubClient.java    From swaggerhub-gradle-plugin with Apache License 2.0 6 votes vote down vote up
public String getDefinition(SwaggerHubRequest swaggerHubRequest) throws GradleException {
    HttpUrl httpUrl = getDownloadUrl(swaggerHubRequest);
    MediaType mediaType = MediaType.parse("application/" + swaggerHubRequest.getFormat());

    Request requestBuilder = buildGetRequest(httpUrl, mediaType);

    final String jsonResponse;
    try {
        final Response response = client.newCall(requestBuilder).execute();
        if (!response.isSuccessful()) {
            throw new GradleException(String.format("Failed to download API definition: %s", response.body().string()));
        } else {
            jsonResponse = response.body().string();
        }
    } catch (IOException e) {
        throw new GradleException("Failed to download API definition", e);
    }
    return jsonResponse;
}
 
Example #12
Source File: Auth0Test.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldHandleNonAuth0Domain() {
    Auth0 auth0 = new Auth0(CLIENT_ID, "mydomain.com");
    assertThat(auth0.getClientId(), equalTo(CLIENT_ID));
    assertThat(HttpUrl.parse(auth0.getDomainUrl()), equalTo(HttpUrl.parse("https://mydomain.com")));
    assertThat(HttpUrl.parse(auth0.getConfigurationUrl()), equalTo(HttpUrl.parse("https://mydomain.com")));
}
 
Example #13
Source File: MockRequest.java    From Auth0.Android with MIT License 5 votes vote down vote up
public MockRequest(HttpUrl url, OkHttpClient client, Gson gson, String method, ErrorBuilder<U> builder) {
    this.headers = new HashMap<>();
    this.url = url;
    this.client = client;
    this.gson = gson;
    this.method = method;
    this.builder = builder;
}
 
Example #14
Source File: SwaggerHubClient.java    From swaggerhub-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Request buildPostRequest(HttpUrl httpUrl, MediaType mediaType, String content) {
    return new Request.Builder()
            .url(httpUrl)
            .addHeader("Content-Type", mediaType.toString())
            .addHeader("Authorization", token)
            .addHeader("User-Agent", "swaggerhub-maven-plugin")
            .post(RequestBody.create(mediaType, content))
            .build();
}
 
Example #15
Source File: Auth0Test.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldBuildWithConfigurationDomainToo() {
    Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN, CONFIG_DOMAIN_CUSTOM);
    assertThat(auth0.getClientId(), equalTo(CLIENT_ID));
    assertThat(HttpUrl.parse(auth0.getDomainUrl()), equalTo(HttpUrl.parse("https://samples.auth0.com")));
    assertThat(HttpUrl.parse(auth0.getConfigurationUrl()), equalTo(HttpUrl.parse("https://config.mydomain.com")));
}
 
Example #16
Source File: ParticleCloudSDK.java    From particle-android with Apache License 2.0 5 votes vote down vote up
static void initWithInstanceCheck(Context ctx,
                                  @Nullable OauthBasicAuthCredentialsProvider oauthProvider) {
    if (instance != null) {
        log.w("Calling ParticleCloudSDK.init() more than once does not re-initialize the SDK.");
        return;
    }

    String asString = ctx.getString(R.string.api_base_uri);
    doInit(ctx, oauthProvider, HttpUrl.parse(asString));
}
 
Example #17
Source File: RepoManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static DhisApi createService(HttpUrl serverUrl, Credentials credentials,
        final Context context) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(provideServerUrl(serverUrl))
            .setConverter(provideJacksonConverter())
            .setClient(provideOkClient(credentials, context))
            .setErrorHandler(new RetrofitErrorHandler())
            .setLogLevel(RestAdapter.LogLevel.BASIC)
            .setRequestInterceptor(new ConnectionInterceptor(context))
            .build();
    return restAdapter.create(DhisApi.class);
}
 
Example #18
Source File: RequestBuilderBuildMethodInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
String toHost(Object target) {
    if (target instanceof HttpUrlGetter) {
        final HttpUrl url = ((HttpUrlGetter) target)._$PINPOINT$_getHttpUrl();
        return getDestinationId(url);
    }
    return null;
}
 
Example #19
Source File: ParticleCloudSDK.java    From particle-android with Apache License 2.0 5 votes vote down vote up
private static void doInit(Context ctx,
                           @Nullable OauthBasicAuthCredentialsProvider oauthProvider,
                           HttpUrl uri) {
    Context appContext = ctx.getApplicationContext();
    SDKProvider sdkProvider = new SDKProvider(appContext, oauthProvider, uri);
    instance = new ParticleCloudSDK(sdkProvider);
}
 
Example #20
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 5 votes vote down vote up
private <T> ParameterizableRequest<T, AuthenticationException> delegation(Class<T> clazz) {
    HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
            .addPathSegment(DELEGATION_PATH)
            .build();

    final Map<String, Object> parameters = ParameterBuilder.newBuilder()
            .setClientId(getClientId())
            .setGrantType(ParameterBuilder.GRANT_TYPE_JWT)
            .asDictionary();

    return factory.POST(url, client, gson, clazz, authErrorBuilder)
            .addParameters(parameters);
}
 
Example #21
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 5 votes vote down vote up
/**
 * Start a custom passwordless flow
 *
 * @return a request to configure and start
 */
@SuppressWarnings("WeakerAccess")
private ParameterizableRequest<Void, AuthenticationException> passwordless() {
    HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
            .addPathSegment(PASSWORDLESS_PATH)
            .addPathSegment(START_PATH)
            .build();

    final Map<String, Object> parameters = ParameterBuilder.newBuilder()
            .setClientId(getClientId())
            .asDictionary();

    return factory.POST(url, client, gson, authErrorBuilder)
            .addParameters(parameters);
}
 
Example #22
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 5 votes vote down vote up
/**
 * Creates a new Request to obtain the JSON Web Keys associated with the Auth0 account under the given domain.
 * Only supports RSA keys used for signatures (Public Keys).
 *
 * @return a request to obtain the JSON Web Keys associated with this Auth0 account.
 */
public Request<Map<String, PublicKey>, AuthenticationException> fetchJsonWebKeys() {
    HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
            .addPathSegment(WELL_KNOWN_PATH)
            .addPathSegment(JWKS_FILE_PATH)
            .build();
    TypeToken<Map<String, PublicKey>> jwksType = new TypeToken<Map<String, PublicKey>>() {
    };
    return factory.GET(url, client, gson, jwksType, authErrorBuilder);
}
 
Example #23
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 5 votes vote down vote up
private AuthenticationRequest loginWithToken(Map<String, Object> parameters) {
    HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(TOKEN_PATH)
            .build();

    final Map<String, Object> requestParameters = ParameterBuilder.newBuilder()
            .setClientId(getClientId())
            .addAll(parameters)
            .asDictionary();
    return factory.authenticationPOST(url, client, gson)
            .addAuthenticationParameters(requestParameters);
}
 
Example #24
Source File: AuthenticationAPIClient.java    From Auth0.Android with MIT License 5 votes vote down vote up
private ParameterizableRequest<UserProfile, AuthenticationException> profileRequest() {
    HttpUrl url = HttpUrl.parse(auth0.getDomainUrl()).newBuilder()
            .addPathSegment(USER_INFO_PATH)
            .build();

    return factory.GET(url, client, gson, UserProfile.class, authErrorBuilder);
}
 
Example #25
Source File: Auth0Test.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldHandleEUInstance() {
    Auth0 auth0 = new Auth0(CLIENT_ID, EU_DOMAIN);
    assertThat(auth0.getClientId(), equalTo(CLIENT_ID));
    assertThat(HttpUrl.parse(auth0.getDomainUrl()), equalTo(HttpUrl.parse("https://samples.eu.auth0.com")));
    assertThat(HttpUrl.parse(auth0.getConfigurationUrl()), equalTo(HttpUrl.parse("https://cdn.eu.auth0.com")));
}
 
Example #26
Source File: Auth0Test.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Test
public void shouldReturnLogoutUrl() {
    Auth0 auth0 = new Auth0(CLIENT_ID, DOMAIN);

    final HttpUrl url = HttpUrl.parse(auth0.getLogoutUrl());
    assertThat(url, hasScheme("https"));
    assertThat(url, hasHost(DOMAIN));
    assertThat(url, hasPath("v2", "logout"));
}
 
Example #27
Source File: Auth0.java    From Auth0.Android with MIT License 5 votes vote down vote up
private HttpUrl ensureValidUrl(String url) {
    if (url == null) {
        return null;
    }
    String safeUrl = url.startsWith("http") ? url : "https://" + url;
    return HttpUrl.parse(safeUrl);
}
 
Example #28
Source File: MockAuthenticationRequest.java    From Auth0.Android with MIT License 5 votes vote down vote up
public MockAuthenticationRequest(HttpUrl url, OkHttpClient client, Gson gson, String method) {
    this.headers = new HashMap<>();
    this.url = url;
    this.client = client;
    this.gson = gson;
    this.method = method;
}
 
Example #29
Source File: AbstractProxyTest.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
public final void setUp() throws Exception {
    mockWebServer = new MockWebServer();
    HttpUrl serverUrl = mockWebServer.url("/");

    // Override factory endpoint
    getProxy().setHost(serverUrl.host());
    getProxy().setPort(serverUrl.port());
}
 
Example #30
Source File: BaseAuthenticationRequestTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockAPI = new AuthenticationAPI();
    gson = GsonProvider.buildGson();
    HttpUrl url = HttpUrl.parse(mockAPI.getDomain())
            .newBuilder()
            .addPathSegment(OAUTH_PATH)
            .addPathSegment(RESOURCE_OWNER_PATH)
            .build();
    request = createRequest(url);
}