1 /* 2 * Copyright 2015 The gRPC Authors 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package io.grpc.clientcacheexample; 18 19 import android.app.Activity; 20 import android.content.Context; 21 import android.os.AsyncTask; 22 import android.os.Bundle; 23 import android.support.v7.app.AppCompatActivity; 24 import android.text.TextUtils; 25 import android.text.method.ScrollingMovementMethod; 26 import android.util.Log; 27 import android.view.View; 28 import android.view.inputmethod.InputMethodManager; 29 import android.widget.Button; 30 import android.widget.CheckBox; 31 import android.widget.EditText; 32 import android.widget.TextView; 33 import io.grpc.CallOptions; 34 import io.grpc.Channel; 35 import io.grpc.ClientInterceptors; 36 import io.grpc.ManagedChannel; 37 import io.grpc.ManagedChannelBuilder; 38 import io.grpc.MethodDescriptor; 39 import io.grpc.examples.helloworld.GreeterGrpc; 40 import io.grpc.examples.helloworld.HelloReply; 41 import io.grpc.examples.helloworld.HelloRequest; 42 import io.grpc.stub.ClientCalls; 43 import java.io.PrintWriter; 44 import java.io.StringWriter; 45 import java.lang.ref.WeakReference; 46 import java.util.concurrent.TimeUnit; 47 48 public final class ClientCacheExampleActivity extends AppCompatActivity { 49 private static final int CACHE_SIZE_IN_BYTES = 1 * 1024 * 1024; // 1MB 50 private static final String TAG = "grpcCacheExample"; 51 private Button sendButton; 52 private EditText hostEdit; 53 private EditText portEdit; 54 private EditText messageEdit; 55 private TextView resultText; 56 private CheckBox getCheckBox; 57 private CheckBox noCacheCheckBox; 58 private CheckBox onlyIfCachedCheckBox; 59 private SafeMethodCachingInterceptor.Cache cache; 60 61 @Override onCreate(Bundle savedInstanceState)62 protected void onCreate(Bundle savedInstanceState) { 63 super.onCreate(savedInstanceState); 64 setContentView(R.layout.activity_clientcacheexample); 65 sendButton = (Button) findViewById(R.id.send_button); 66 hostEdit = (EditText) findViewById(R.id.host_edit_text); 67 portEdit = (EditText) findViewById(R.id.port_edit_text); 68 messageEdit = (EditText) findViewById(R.id.message_edit_text); 69 getCheckBox = (CheckBox) findViewById(R.id.get_checkbox); 70 noCacheCheckBox = (CheckBox) findViewById(R.id.no_cache_checkbox); 71 onlyIfCachedCheckBox = (CheckBox) findViewById(R.id.only_if_cached_checkbox); 72 resultText = (TextView) findViewById(R.id.grpc_response_text); 73 resultText.setMovementMethod(new ScrollingMovementMethod()); 74 cache = SafeMethodCachingInterceptor.newLruCache(CACHE_SIZE_IN_BYTES); 75 } 76 77 /** Sends RPC. Invoked when app button is pressed. */ sendMessage(View view)78 public void sendMessage(View view) { 79 ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)) 80 .hideSoftInputFromWindow(hostEdit.getWindowToken(), 0); 81 sendButton.setEnabled(false); 82 resultText.setText(""); 83 new GrpcTask(this, cache) 84 .execute( 85 hostEdit.getText().toString(), 86 messageEdit.getText().toString(), 87 portEdit.getText().toString(), 88 getCheckBox.isChecked(), 89 noCacheCheckBox.isChecked(), 90 onlyIfCachedCheckBox.isChecked()); 91 } 92 93 private static class GrpcTask extends AsyncTask<Object, Void, String> { 94 private final WeakReference<Activity> activityReference; 95 private final SafeMethodCachingInterceptor.Cache cache; 96 private ManagedChannel channel; 97 GrpcTask(Activity activity, SafeMethodCachingInterceptor.Cache cache)98 private GrpcTask(Activity activity, SafeMethodCachingInterceptor.Cache cache) { 99 this.activityReference = new WeakReference<Activity>(activity); 100 this.cache = cache; 101 } 102 103 @Override doInBackground(Object... params)104 protected String doInBackground(Object... params) { 105 String host = (String) params[0]; 106 String message = (String) params[1]; 107 String portStr = (String) params[2]; 108 boolean useGet = (boolean) params[3]; 109 boolean noCache = (boolean) params[4]; 110 boolean onlyIfCached = (boolean) params[5]; 111 int port = TextUtils.isEmpty(portStr) ? 0 : Integer.valueOf(portStr); 112 try { 113 channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); 114 Channel channelToUse = 115 ClientInterceptors.intercept( 116 channel, SafeMethodCachingInterceptor.newSafeMethodCachingInterceptor(cache)); 117 HelloRequest request = HelloRequest.newBuilder().setName(message).build(); 118 HelloReply reply; 119 if (useGet) { 120 MethodDescriptor<HelloRequest, HelloReply> safeCacheableUnaryCallMethod = 121 GreeterGrpc.getSayHelloMethod().toBuilder().setSafe(true).build(); 122 CallOptions callOptions = CallOptions.DEFAULT; 123 if (noCache) { 124 callOptions = 125 callOptions.withOption(SafeMethodCachingInterceptor.NO_CACHE_CALL_OPTION, true); 126 } 127 if (onlyIfCached) { 128 callOptions = 129 callOptions.withOption( 130 SafeMethodCachingInterceptor.ONLY_IF_CACHED_CALL_OPTION, true); 131 } 132 reply = 133 ClientCalls.blockingUnaryCall( 134 channelToUse, safeCacheableUnaryCallMethod, callOptions, request); 135 } else { 136 GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channelToUse); 137 reply = stub.sayHello(request); 138 } 139 return reply.getMessage(); 140 } catch (Exception e) { 141 Log.e(TAG, "RPC failed", e); 142 StringWriter sw = new StringWriter(); 143 PrintWriter pw = new PrintWriter(sw); 144 e.printStackTrace(pw); 145 pw.flush(); 146 return String.format("Failed... : %n%s", sw); 147 } 148 } 149 150 @Override onPostExecute(String result)151 protected void onPostExecute(String result) { 152 if (channel != null) { 153 try { 154 channel.shutdown().awaitTermination(1, TimeUnit.SECONDS); 155 } catch (InterruptedException e) { 156 Thread.currentThread().interrupt(); 157 } 158 } 159 Activity activity = activityReference.get(); 160 if (activity == null) { 161 return; 162 } 163 TextView resultText = (TextView) activity.findViewById(R.id.grpc_response_text); 164 Button sendButton = (Button) activity.findViewById(R.id.send_button); 165 resultText.setText(result); 166 sendButton.setEnabled(true); 167 } 168 } 169 } 170