Advertisement
pflammertsma

Translator (MainActivity.java)

Sep 3rd, 2012
277
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.95 KB | None | 0 0
  1. package com.pixplicity.translator;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.UnsupportedEncodingException;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.net.URLEncoder;
  12. import java.util.List;
  13. import java.util.Map.Entry;
  14.  
  15. import org.json.JSONObject;
  16.  
  17. import android.app.Activity;
  18. import android.os.AsyncTask;
  19. import android.os.Bundle;
  20. import android.os.Environment;
  21. import android.util.Log;
  22.  
  23. public class MainActivity extends Activity {
  24.  
  25.     private static final String CLIENT_ID = "your-client-id";
  26.     private static final String CLIENT_SECRET = "your-client-secret";
  27.  
  28.     private static final String PREFERRED_CHARSET = "UTF-8";
  29.  
  30.     private static final boolean TRANSLATE = false;
  31.     private static final String PATH = "/";
  32.  
  33.     private static final String TAG = "Translator";
  34.  
  35.     /**
  36.      * Tailor-made HTTP request for Microsoft Azure, downloading a file to a
  37.      * specified location.
  38.      */
  39.     private class HttpDownloadFile extends HttpRequest {
  40.  
  41.         private String mDir;
  42.  
  43.         @Override
  44.         protected String doInBackground(String... params) {
  45.             if (params.length < 3) {
  46.                 throw new IllegalArgumentException(
  47.                         "Four arguments required for "
  48.                                 + getClass().getSimpleName());
  49.             }
  50.             mDir = params[3];
  51.             return super.doInBackground(params);
  52.         }
  53.  
  54.         @Override
  55.         protected boolean isPost() {
  56.             return false;
  57.         }
  58.  
  59.         @Override
  60.         protected OutputStream getOutput() throws IOException {
  61.             return new FileOutputStream(mDir);
  62.         }
  63.  
  64.         @Override
  65.         protected String getResponse(OutputStream output, String charset)
  66.                 throws UnsupportedEncodingException {
  67.             return mDir;
  68.         }
  69.     }
  70.  
  71.     /**
  72.      * Tailor-made HTTP request for Microsoft Azure. Toggles between POST and GET
  73.      * based on {@link isPost()}.
  74.      */
  75.     private class HttpRequest extends AsyncTask<String, Integer, String> {
  76.         @Override
  77.         protected String doInBackground(String... params) {
  78.             if (params.length < 2) {
  79.                 throw new IllegalArgumentException(
  80.                         "Two arguments required for "
  81.                                 + getClass().getSimpleName());
  82.             }
  83.             String response = null;
  84.             String uri = params[0];
  85.             String query = params[1];
  86.             try {
  87.                 Log.d(TAG, "Requesting " + uri
  88.                         + (query.length() > 0 ? "?" + query : ""));
  89.                 if (!isPost() && query.length() > 0) {
  90.                     uri += "?" + query;
  91.                 }
  92.                 URL url = new URL(uri);
  93.                 HttpURLConnection connection = (HttpURLConnection) url
  94.                         .openConnection();
  95.                 if (isPost()) {
  96.                     connection.setDoOutput(true);
  97.                 }
  98.                 connection.setRequestProperty("Content-Type",
  99.                         "application/x-www-form-urlencoded");
  100.                 if (params.length > 2) {
  101.                     String auth = "Bearer " + params[2];
  102.                     Log.v(TAG, "Authorization: " + auth);
  103.                     connection.setRequestProperty("Authorization", auth);
  104.                 }
  105.                 if (isPost()) {
  106.                     OutputStream output = null;
  107.                     try {
  108.                         output = connection.getOutputStream();
  109.                         output.write(query.getBytes(PREFERRED_CHARSET));
  110.                     } finally {
  111.                         if (output != null) {
  112.                             try {
  113.                                 output.close();
  114.                             } catch (IOException logOrIgnore) {
  115.                             }
  116.                         }
  117.                     }
  118.                 } else {
  119.                     connection.connect();
  120.                 }
  121.                 int fileLength = connection.getContentLength();
  122.                 String charset = PREFERRED_CHARSET;
  123.                 if (connection.getContentEncoding() != null) {
  124.                     charset = connection.getContentEncoding();
  125.                 }
  126.                 int responseCode = connection.getResponseCode();
  127.  
  128.                 for (Entry<String, List<String>> header : connection
  129.                         .getHeaderFields().entrySet()) {
  130.                     Log.v(TAG,
  131.                             "Header: "
  132.                                     + (header.getKey() == null ? "" :
  133.                                             "[" + header.getKey() + "]=")
  134.                                     + header.getValue());
  135.                 }
  136.  
  137.                 Log.v(TAG, "Response code " + responseCode);
  138.                 Log.v(TAG, "Content encoding " + charset);
  139.  
  140.                 InputStream input;
  141.                 OutputStream output;
  142.                 boolean isError = false;
  143.                 try {
  144.                     input = connection.getInputStream();
  145.                     output = getOutput();
  146.                 } catch (IOException e) {
  147.                     input = connection.getErrorStream();
  148.                     output = getErrorOutput();
  149.                     isError = true;
  150.                 }
  151.  
  152.                 byte data[] = new byte[1024];
  153.                 long total = 0;
  154.                 int count;
  155.                 while ((count = input.read(data)) != -1) {
  156.                     total += count;
  157.                     // publishing the progress....
  158.                     publishProgress((int) (total * 100 / fileLength));
  159.                     output.write(data, 0, count);
  160.                 }
  161.  
  162.                 output.flush();
  163.                 if (!isError) {
  164.                     response = getResponse(output, charset);
  165.                 } else {
  166.                     response = getErrorResponse(output, charset);
  167.                     Log.e(TAG, response);
  168.                     response = null;
  169.                 }
  170.                 output.close();
  171.                 input.close();
  172.             } catch (Exception e) {
  173.                 Log.e(TAG, "Failed requesting " + uri, e);
  174.             }
  175.             return response;
  176.         }
  177.  
  178.         @Override
  179.         protected void onProgressUpdate(Integer... values) {
  180.             Log.d(TAG, "progress: " + values[0] + "%");
  181.         }
  182.  
  183.         protected boolean isPost() {
  184.             return true;
  185.         }
  186.  
  187.         protected OutputStream getOutput() throws IOException {
  188.             return new ByteArrayOutputStream();
  189.         }
  190.  
  191.         protected OutputStream getErrorOutput() throws IOException {
  192.             return new ByteArrayOutputStream();
  193.         }
  194.  
  195.         protected String getResponse(OutputStream output, String charset)
  196.                 throws UnsupportedEncodingException {
  197.             return ((ByteArrayOutputStream) output).toString(charset);
  198.         }
  199.  
  200.         protected String getErrorResponse(OutputStream output, String charset)
  201.                 throws UnsupportedEncodingException {
  202.             return ((ByteArrayOutputStream) output).toString(charset);
  203.         }
  204.  
  205.     }
  206.  
  207.     @Override
  208.     public void onCreate(Bundle savedInstanceState) {
  209.         super.onCreate(savedInstanceState);
  210.         setContentView(R.layout.ac_main);
  211.  
  212.         try {
  213.             String clientId = encode(CLIENT_ID);
  214.             String clientSecret = encode(CLIENT_SECRET);
  215.             String text = encode("Met PowerPivot kunnen gebruikers interessante selfservice BI-oplossingen maken, eenvoudig gegevens delen en samenwerken met door gebruikers gegenereerde BI-oplossingen in een omgeving met Microsoft SharePoint Server 2010 en kunnen IT-organisaties efficiënter werken met behulp van op Microsoft SQL Server 2008 R2 gebaseerde beheerprogramma's.");
  216.             String fromLanguage = encode("nl");
  217.             String toLanguage = encode("en");
  218.             String accessToken = null;
  219.             String file = "test.wav";
  220.  
  221.             if (true) {
  222.                 HttpRequest task = new HttpRequest();
  223.                 task.execute(
  224.                         getString(R.string.url_oauth),
  225.                         getString(R.string.url_oauth_query, clientId,
  226.                                 clientSecret));
  227.                 String response = task.get();
  228.                 if (response != null) {
  229.                     Log.d(TAG, response);
  230.                     JSONObject json = new JSONObject(response);
  231.                     accessToken = json.getString("access_token");
  232.                 } else {
  233.                     Log.w(TAG, "response was null");
  234.                 }
  235.             }
  236.  
  237.             if (accessToken != null) {
  238.                 String translated = null;
  239.                 if (TRANSLATE) {
  240.                     HttpRequest task = new HttpRequest();
  241.                     task.execute(
  242.                             getString(R.string.url_translate),
  243.                             getString(R.string.url_translate_query,
  244.                                     text, fromLanguage, toLanguage),
  245.                             accessToken);
  246.                     String response = task.get();
  247.                     if (response != null) {
  248.                         Log.d(TAG, response);
  249.                         // Do something with the response
  250.                     } else {
  251.                         Log.w(TAG, "response was null");
  252.                     }
  253.                 } else {
  254.                     translated = text;
  255.                     toLanguage = fromLanguage;
  256.                 }
  257.                 if (translated != null) {
  258.                     HttpDownloadFile task = new HttpDownloadFile();
  259.                     task.execute(
  260.                             getString(R.string.url_speak),
  261.                             getString(R.string.url_speak_query,
  262.                                     text, toLanguage, file),
  263.                             accessToken,
  264.                             Environment.getExternalStorageDirectory().getPath()
  265.                                     + PATH + file);
  266.                     String response = task.get();
  267.                     if (response == null) {
  268.                         Log.w(TAG, "response was null");
  269.                     } else {
  270.                         Log.i(TAG, response);
  271.                     }
  272.                 }
  273.             }
  274.         } catch (Exception e) {
  275.             throw new RuntimeException(e);
  276.         }
  277.  
  278.     }
  279.  
  280.     private String encode(String str) throws UnsupportedEncodingException {
  281.         return URLEncoder.encode(
  282.                 str,
  283.                 PREFERRED_CHARSET);
  284.     }
  285.  
  286. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement