下面列出了com.squareup.okhttp.Cache#retrofit.RestAdapter.LogLevel 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
SDKProvider(Context context,
@Nullable OauthBasicAuthCredentialsProvider oAuthCredentialsProvider,
HttpUrl uri) {
this.ctx = context.getApplicationContext();
if (oAuthCredentialsProvider == null) {
oAuthCredentialsProvider = new ResourceValueBasicAuthCredentialsProvider(
ctx, R.string.oauth_client_id, R.string.oauth_client_secret);
}
tokenGetter = new TokenGetterDelegateImpl();
LogLevel httpLogLevel = LogLevel.valueOf(ctx.getString(R.string.http_log_level));
ApiFactory apiFactory = new ApiFactory(uri, httpLogLevel, tokenGetter, oAuthCredentialsProvider);
cloudApi = apiFactory.buildNewCloudApi();
identityApi = apiFactory.buildNewIdentityApi();
particleCloud = buildCloud(apiFactory);
}
/**
* This test creates a Video and attempts to add it to the video service
* without logging in. The test checks to make sure that the request is
* denied and the client redirected to the login page.
*
* @throws Exception
*/
@Test
public void testRedirectToLoginWithoutAuth() throws Exception {
ErrorRecorder error = new ErrorRecorder();
VideoSvcApi videoService = new RestAdapter.Builder()
.setClient(
new ApacheClient(UnsafeHttpsClient.createUnsafeClient()))
.setEndpoint(TEST_URL).setLogLevel(LogLevel.FULL)
.setErrorHandler(error).build().create(VideoSvcApi.class);
try {
// This should fail because we haven't logged in!
videoService.addVideo(video);
fail("Yikes, the security setup is horribly broken and didn't require the user to login!!");
} catch (Exception e) {
// Ok, our security may have worked, ensure that
// we got redirected to the login page
assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, error.getError()
.getResponse().getStatus());
}
}
@Bean
public IgorService igorService(
Endpoint igorEndpoint,
OkHttpClientProvider clientProvider,
LogLevel retrofitLogLevel,
SpinnakerRequestInterceptor spinnakerRequestInterceptor) {
log.info("igor service loaded");
return new Builder()
.setEndpoint(igorEndpoint)
.setConverter(new JacksonConverter())
.setClient(
new Ok3Client(
clientProvider.getClient(
new DefaultServiceEndpoint("igor", igorEndpoint.getUrl()))))
.setRequestInterceptor(spinnakerRequestInterceptor)
.setLogLevel(retrofitLogLevel)
.setLog(new Slf4jRetrofitLogger(IgorService.class))
.build()
.create(IgorService.class);
}
@Bean
public Front50Service front50Service(
Endpoint front50Endpoint,
OkHttpClientProvider clientProvider,
LogLevel retrofitLogLevel,
SpinnakerRequestInterceptor spinnakerRequestInterceptor) {
log.info("front50 service loaded");
return new Builder()
.setEndpoint(front50Endpoint)
.setConverter(new JacksonConverter())
.setClient(
new Ok3Client(
clientProvider.getClient(
new DefaultServiceEndpoint("front50", front50Endpoint.getUrl()))))
.setRequestInterceptor(spinnakerRequestInterceptor)
.setLogLevel(retrofitLogLevel)
.setLog(new Slf4jRetrofitLogger(Front50Service.class))
.build()
.create(Front50Service.class);
}
@Before
public void setup() {
mCountDownLatch = new CountDownLatch(1);
mApiClient = new RestAdapter.Builder()
.setEndpoint(Settings.getSandboxUrl())
.setRequestInterceptor(new ApiClientRequestInterceptor())
.setLogLevel(LogLevel.FULL)
.build()
.create(ApiClient.class);
}
ApiFactory(
HttpUrl uri,
LogLevel httpLogLevel,
TokenGetterDelegate tokenGetterDelegate,
OauthBasicAuthCredentialsProvider basicAuthProvider
) {
this.tokenDelegate = tokenGetterDelegate;
this.basicAuthCredentialsProvider = basicAuthProvider;
this.gson = new Gson();
this.apiBaseUri = uri;
this.httpLogLevel = httpLogLevel;
normalTimeoutClient = buildClientWithTimeout(REGULAR_TIMEOUT);
}
/**
* This test creates a Video and attempts to add it to the video service
* without logging in. The test checks to make sure that the request is
* denied and the client redirected to the login page.
*
* @throws Exception
*/
@Test
public void testDenyVideoAddWithoutLogin() throws Exception {
ErrorRecorder error = new ErrorRecorder();
VideoSvcApi videoService = new RestAdapter.Builder()
.setClient(
new ApacheClient(UnsafeHttpsClient.createUnsafeClient()))
.setEndpoint(TEST_URL).setLogLevel(LogLevel.FULL)
.setErrorHandler(error).build().create(VideoSvcApi.class);
try {
// This should fail because we haven't logged in!
videoService.addVideo(video);
fail("Yikes, the security setup is horribly broken and didn't require the user to login!!");
} catch (Exception e) {
// Ok, our security may have worked, ensure that
// we got redirected to the login page
assertEquals(HttpStatus.SC_MOVED_TEMPORARILY, error.getError()
.getResponse().getStatus());
}
// Now, let's login and ensure that the Video wasn't added
videoService.login("coursera", "changeit");
// We should NOT get back the video that we added above!
Collection<Video> videos = videoService.getVideoList();
assertFalse(videos.contains(video));
}
public static synchronized VideoSvcApi init(String server, String user,
String pass) {
videoSvc_ = new SecuredRestBuilder()
.setLoginEndpoint(server + VideoSvcApi.TOKEN_PATH)
.setUsername(user)
.setPassword(pass)
.setClientId(CLIENT_ID)
.setClient(
new ApacheClient(new EasyHttpClient()))
.setEndpoint(server).setLogLevel(LogLevel.FULL).build()
.create(VideoSvcApi.class);
return videoSvc_;
}
/**
* Hook method dispatched by the GenericActivity framework to
* initialize the AcronymOps object after it's been created.
*
* @param view The currently active AcronymOps.View.
* @param firstTimeIn Set to "true" if this is the first time the
* Ops class is initialized, else set to
* "false" if called after a runtime
* configuration change.
*/
public void onConfiguration(AcronymOps.View view,
boolean firstTimeIn) {
Log.d(TAG,
"onConfiguration() called");
// Reset the mAcronymView WeakReference.
mAcronymView =
new WeakReference<>(view);
if (firstTimeIn) {
// Store the Application context to avoid problems with
// the Activity context disappearing during a rotation.
mContext = view.getApplicationContext();
// Set up the HttpResponse cache that will be used by
// Retrofit.
mCache = new Cache(new File(mContext.getCacheDir(),
CACHE_FILENAME),
// Cache stores up to 1 MB.
1024 * 1024);
// Set up the client that will use this cache. Retrofit
// will use okhttp client to make network calls.
mOkHttpClient = new OkHttpClient();
if (mCache != null)
mOkHttpClient.setCache(mCache);
// Create a proxy to access the Acronym Service web
// service.
mAcronymWebServiceProxy =
new RestAdapter.Builder()
.setEndpoint(AcronymWebServiceProxy.ENDPOINT)
.setClient(new OkClient(mOkHttpClient))
// .setLogLevel(LogLevel.FULL)
.setLogLevel(LogLevel.NONE)
.build()
.create(AcronymWebServiceProxy.class);
}
}
private RestAdapter.Builder buildCommonRestAdapterBuilder(Gson gson, OkHttpClient client) {
return new RestAdapter.Builder()
.setClient(new OkClient(client))
.setConverter(new GsonConverter(gson))
.setEndpoint(getApiUri().toString())
.setLogLevel(LogLevel.valueOf(ctx.getString(R.string.http_log_level)));
}
@Bean
public KeelService keelService(
Endpoint keelEndpoint, OkHttpClientProvider clientProvider, LogLevel retrofitLogLevel) {
return new RestAdapter.Builder()
.setEndpoint(keelEndpoint)
.setConverter(new JacksonConverter())
.setClient(
new Ok3Client(
clientProvider.getClient(
new DefaultServiceEndpoint("keel", keelEndpoint.getUrl()))))
.setLogLevel(retrofitLogLevel)
.setLog(new Slf4jRetrofitLogger(KeelService.class))
.build()
.create(KeelService.class);
}
private <T> T bindRetrofitService(final Class<T> type, final String endpoint) {
log.info("Connecting {} to {}", type.getSimpleName(), endpoint);
return new RestAdapter.Builder()
.setClient(
new Ok3Client(clientProvider.getClient(new DefaultServiceEndpoint("orca", endpoint))))
.setRequestInterceptor(requestInterceptor)
.setConverter(new JacksonConverter(EchoObjectMapper.getInstance()))
.setEndpoint(endpoint)
.setLogLevel(LogLevel.BASIC)
.setLog(new Slf4jRetrofitLogger(type))
.build()
.create(type);
}
@Before
public void setup() {
mCountDownLatch = new CountDownLatch(1);
mApiClient = new RestAdapter.Builder()
.setEndpoint(Settings.getSandboxUrl())
.setRequestInterceptor(new ApiClientRequestInterceptor())
.setLogLevel(LogLevel.FULL)
.build()
.create(ApiClient.class);
}
@Override
public SecuredRestBuilder setLogLevel(LogLevel logLevel) {
return (SecuredRestBuilder) super.setLogLevel(logLevel);
}
@Override
public SecuredRestBuilder setLogLevel(LogLevel logLevel) {
return (SecuredRestBuilder) super.setLogLevel(logLevel);
}
@Override
public SecuredRestBuilder setLogLevel(LogLevel logLevel) {
return (SecuredRestBuilder) super.setLogLevel(logLevel);
}
/**
* Constructor that initializes the VideoDataMediator.
*
* @param context
*/
public VideoDataMediator(Context context) {
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
String serverProtocol = prefs
.getString(SettingsActivity.KEY_PREFERENCE_PROTOCOL,
"");
String serverIp = prefs
.getString(SettingsActivity.KEY_PREFERENCE_IP_ADDRESS,
"");
String serverPort = prefs
.getString(SettingsActivity.KEY_PREFERENCE_PORT,
"");
String userName = prefs
.getString(SettingsActivity.KEY_PREFERENCE_USER_NAME,
"");
String password = prefs
.getString(SettingsActivity.KEY_PREFERENCE_PASSWORD,
"");
String serverUrl = serverProtocol
+ "://"
+ serverIp
+ ":"
+ serverPort ;
// Initialize the VideoServiceProxy.
mVideoServiceProxy =
new SecuredRestBuilder()
.setLoginEndpoint(serverUrl + VideoSvcApi.TOKEN_PATH)
.setEndpoint(serverUrl)
.setUsername(userName)
.setPassword(password)
.setClientId(Constants.CLIENT_ID)
.setClient(new OkClient(UnsafeHttpsClient.getUnsafeOkHttpClient()))
.setLogLevel(LogLevel.FULL)
.build()
.create(VideoSvcApi.class);
}
@Bean
public LogLevel retrofitLogLevel() {
return LogLevel.BASIC;
}
@Override
public void run() {
Map<String, Cluster> clusters = this.schedulerState.getClusters();
if (MapUtils.isEmpty(clusters)) {
LOGGER.info("Nothing to rebalance, as there are no clusters registered");
return;
}
clusters.values()
.stream()
.forEach(
cluster -> {
String clusterId = cluster.getClusterId();
boolean acquireLock = this.schedulerState
.acquireLock(clusterId);
if (!acquireLock) {
LOGGER.info(
"Rebalancer was unable to acquire lock for cluster {}",
clusterId);
return;
}
LOGGER.info("Analyzing cluster: {}", clusterId);
String host = cluster.getResourceManagerHost();
String port = cluster.getResourceManagerPort();
double minQuota = cluster.getMinQuota();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://" + host + ":" + port)
.setLogLevel(LogLevel.FULL).build();
YARNResourceManagerService service = restAdapter
.create(YARNResourceManagerService.class);
ClusterMetrics metrics = service.metrics()
.getClusterMetrics();
AppsResponse appsResponse = service
.apps("ACCEPTED");
int acceptedApps = 0;
if (appsResponse == null
|| appsResponse.getApps() == null
|| appsResponse.getApps().getApps() == null) {
acceptedApps = 0;
} else {
acceptedApps = appsResponse.getApps().getApps()
.size();
}
LOGGER.info("Metrics: {}", metrics);
LOGGER.info("Apps: {}", appsResponse);
long availableMB = metrics.getAvailableMB();
long allocatedMB = metrics.getAllocatedMB();
long reservedMB = metrics.getReservedMB();
int activeNodes = metrics.getActiveNodes();
int unhealthyNodes = metrics.getUnhealthyNodes();
int appsPending = metrics.getAppsPending();
int appsRunning = metrics.getAppsRunning();
if (activeNodes == 0 && appsPending > 0) {
LOGGER.info(
"Flexing up for condition: activeNodes ({}) == 0 && appsPending ({}) > 0",
activeNodes, appsPending);
this.myriadOperations.flexUpCluster(clusterId,
1, "small");
} else if (appsPending == 0 && appsRunning == 0
&& activeNodes > 0) {
LOGGER.info(
"Flexing down for condition: appsPending ({}) == 0 && appsRunning ({}) == 0 && activeNodes ({}) > 0",
appsPending, appsRunning, activeNodes);
this.myriadOperations.flexDownCluster(cluster,
1);
} else if (acceptedApps > 0) {
LOGGER.info(
"Flexing up for condition: acceptedApps ({}) > 0",
acceptedApps);
this.myriadOperations.flexUpCluster(clusterId,
1, "small");
} else {
LOGGER.info("Nothing to rebalance");
this.schedulerState.releaseLock(clusterId);
}
});
}