无服务器的微服务 2

来源:开源中国社区 作者:oschina
  

下面是完整的代码文件:

MainActivity.java

package com.amazon.lambda.androidimageprocessor;
 
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.amazon.lambda.androidimageprocessor.lambda.ILambdaInvoker;
import com.amazon.lambda.androidimageprocessor.lambda.ImageConvertRequest;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.lambdainvoker.LambdaFunctionException;
import com.amazonaws.mobileconnectors.lambdainvoker.LambdaInvokerFactory;
import com.amazonaws.regions.Regions;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
 
public class MainActivity extends Activity {
    private ILambdaInvoker lambda;
    private ImageView selectedImage;
    private String selectedImageBase64;
    private ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Create an instance of CognitoCachingCredentialsProvider
        CognitoCachingCredentialsProvider cognitoProvider = new CognitoCachingCredentialsProvider(
                this.getApplicationContext(), "us-east-1:2a40105a-b330-43cf-8d4e-b647d492e76e", Regions.US_EAST_1);
        // Create LambdaInvokerFactory, to be used to instantiate the Lambda proxy.
        LambdaInvokerFactory factory = new LambdaInvokerFactory(this.getApplicationContext(),
                Regions.US_EAST_1, cognitoProvider);
        // Create the Lambda proxy object with a default Json data binder.
        lambda = factory.build(ILambdaInvoker.class);
        // ping lambda function to make sure everything is working
        pingLambda();
    }
    // ping the lambda function
    @SuppressWarnings("unchecked")
    private void pingLambda() {
        Map event = new HashMap();
        event.put("operation""ping");
        // The Lambda function invocation results in a network call.
        // Make sure it is not called from the main thread.
        new AsyncTask<Map, Void, String>() {
            @Override
            protected String doInBackground(Map... params) {
                // invoke "ping" method. In case it fails, it will throw a
                // LambdaFunctionException.
                try {
                    return lambda.ping(params[0]);
                catch (LambdaFunctionException lfe) {
                    Log.e("Tag""Failed to invoke ping", lfe);
                    return null;
                }
            }
            @Override
            protected void onPostExecute(String result) {
                if (result == null) {
                    return;
                }
                // Display a quick message
                Toast.makeText(MainActivity.this"Made contact with AWS lambda", Toast.LENGTH_LONG).show();
            }
        }.execute(event);
    }
    // event handler for "process image" button
    public void processImage(View view) {
        // no image has been selected yet
        if (selectedImageBase64 == null) {
            Toast.makeText(this"Please tap one of the images above", Toast.LENGTH_LONG).show();
            return;
        }
        // get selected filter
        String filter = ((Spinner) findViewById(R.id.filter_picker)).getSelectedItem().toString();
        // assemble new request
        ImageConvertRequest request = new ImageConvertRequest();
        request.setBase64Image(selectedImageBase64);
        request.setInputExtension("png");
        request.setOutputExtension("png");
        // custom arguments per filter
        List customArgs = new ArrayList();
        request.setCustomArgs(customArgs);
        switch (filter) {
            case "Sepia":
                customArgs.add("-sepia-tone");
                customArgs.add("65%");
                break;
            case "Black/White":
                customArgs.add("-colorspace");
                customArgs.add("Gray");
                break;
            case "Negate":
                customArgs.add("-negate");
                break;
            case "Darken":
                customArgs.add("-fill");
                customArgs.add("black");
                customArgs.add("-colorize");
                customArgs.add("50%");
                break;
            case "Lighten":
                customArgs.add("-fill");
                customArgs.add("white");
                customArgs.add("-colorize");
                customArgs.add("50%");
                break;
            default:
                return;
        }
        // async request to lambda function
        new AsyncTask() {
            @Override
            protected String doInBackground(ImageConvertRequest... params) {
                try {
                    return lambda.convert(params[0]);
                catch (LambdaFunctionException e) {
                    Log.e("Tag""Failed to convert image");
                    return null;
                }
            }
            @Override
            protected void onPostExecute(String result) {
                // if no data was returned, there was a failure
                if (result == null || Objects.equals(result, "")) {
                    hideLoadingDialog();
                    Toast.makeText(MainActivity.this"Processing failed", Toast.LENGTH_LONG).show();
                    return;
                }
                // otherwise decode the base64 data and put it in the selected image view
                byte[] imageData = Base64.decode(result, Base64.DEFAULT);
                selectedImage.setImageBitmap(BitmapFactory.decodeByteArray(imageData, 0, imageData.length));
                hideLoadingDialog();
            }
        }.execute(request);
        showLoadingDialog();
    }
    /*
    Select methods for each image
     */
    public void selectLambdaImage(View view) {
        selectImage(R.drawable.lambda);
        selectedImage = (ImageView) findViewById(R.id.static_lambda);
        Toast.makeText(this"Selected image 'lambda'", Toast.LENGTH_LONG).show();
    }
    public void selectSeattleImage(View view) {
        selectImage(R.drawable.seattle);
        selectedImage = (ImageView) findViewById(R.id.static_seattle);
        Toast.makeText(this"Selected image 'seattle'", Toast.LENGTH_LONG).show();
    }
    public void selectSquirrelImage(View view) {
        selectImage(R.drawable.squirrel);
        selectedImage = (ImageView) findViewById(R.id.static_squirrel);
        Toast.makeText(this"Selected image 'squirrel'", Toast.LENGTH_LONG).show();
    }
    public void selectLinuxImage(View view) {
        selectImage(R.drawable.linux);
        selectedImage = (ImageView) findViewById(R.id.static_linux);
        Toast.makeText(this"Selected image 'linux'", Toast.LENGTH_LONG).show();
    }
    // extract the base64 encoded data of the drawable resource `id`
    private void selectImage(int id) {
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), id);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        selectedImageBase64 = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);
    }
    // reset images to their original state
    public void reset(View view) {
        ((ImageView) findViewById(R.id.static_lambda)).setImageDrawable(getResources().getDrawable(R.drawable.lambda, getTheme()));
        ((ImageView) findViewById(R.id.static_seattle)).setImageDrawable(getResources().getDrawable(R.drawable.seattle, getTheme()));
        ((ImageView) findViewById(R.id.static_squirrel)).setImageDrawable(getResources().getDrawable(R.drawable.squirrel, getTheme()));
        ((ImageView) findViewById(R.id.static_linux)).setImageDrawable(getResources().getDrawable(R.drawable.linux, getTheme()));
        Toast.makeText(this"Please choose from one of these images", Toast.LENGTH_LONG).show();
    }
    private void showLoadingDialog() {
        progressDialog = ProgressDialog.show(this"Please wait...""Processing image"truefalse);
    }
    private void hideLoadingDialog() {
        progressDialog.dismiss();
    }
}

这就是这个移动应用所需要的了:一个数据模型(又叫做 Java 类),一个控制模型(又叫做成对的方法),三个用来对一些东西进行初始化的语句,而后就是一个被 try/catch 块包围起来的远程调用了 … 够简单。

本文转自:开源中国社区 [http://www.oschina.net]
本文标题:无服务器的微服务
本文地址:http://www.oschina.net/translate/microservices-without-the-servers
参与翻译:Iam魔方, leoxu, HAILINCAI, 武汉加油, 无若, 木兰宿莽

英文原文:Microservices without the Servers


时间:2015-10-29 09:18 来源:开源中国社区 作者:oschina 原文链接

好文,顶一下
(0)
0%
文章真差,踩一下
(0)
0%
------分隔线----------------------------


把开源带在你的身边-精美linux小纪念品
无觅相关文章插件,快速提升流量