Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.pixplicity.translator;
- import java.io.ByteArrayOutputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.List;
- import java.util.Map.Entry;
- import org.json.JSONObject;
- import android.app.Activity;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.os.Environment;
- import android.util.Log;
- public class MainActivity extends Activity {
- private static final String CLIENT_ID = "your-client-id";
- private static final String CLIENT_SECRET = "your-client-secret";
- private static final String PREFERRED_CHARSET = "UTF-8";
- private static final boolean TRANSLATE = false;
- private static final String PATH = "/";
- private static final String TAG = "Translator";
- /**
- * Tailor-made HTTP request for Microsoft Azure, downloading a file to a
- * specified location.
- */
- private class HttpDownloadFile extends HttpRequest {
- private String mDir;
- @Override
- protected String doInBackground(String... params) {
- if (params.length < 3) {
- throw new IllegalArgumentException(
- "Four arguments required for "
- + getClass().getSimpleName());
- }
- mDir = params[3];
- return super.doInBackground(params);
- }
- @Override
- protected boolean isPost() {
- return false;
- }
- @Override
- protected OutputStream getOutput() throws IOException {
- return new FileOutputStream(mDir);
- }
- @Override
- protected String getResponse(OutputStream output, String charset)
- throws UnsupportedEncodingException {
- return mDir;
- }
- }
- /**
- * Tailor-made HTTP request for Microsoft Azure. Toggles between POST and GET
- * based on {@link isPost()}.
- */
- private class HttpRequest extends AsyncTask<String, Integer, String> {
- @Override
- protected String doInBackground(String... params) {
- if (params.length < 2) {
- throw new IllegalArgumentException(
- "Two arguments required for "
- + getClass().getSimpleName());
- }
- String response = null;
- String uri = params[0];
- String query = params[1];
- try {
- Log.d(TAG, "Requesting " + uri
- + (query.length() > 0 ? "?" + query : ""));
- if (!isPost() && query.length() > 0) {
- uri += "?" + query;
- }
- URL url = new URL(uri);
- HttpURLConnection connection = (HttpURLConnection) url
- .openConnection();
- if (isPost()) {
- connection.setDoOutput(true);
- }
- connection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- if (params.length > 2) {
- String auth = "Bearer " + params[2];
- Log.v(TAG, "Authorization: " + auth);
- connection.setRequestProperty("Authorization", auth);
- }
- if (isPost()) {
- OutputStream output = null;
- try {
- output = connection.getOutputStream();
- output.write(query.getBytes(PREFERRED_CHARSET));
- } finally {
- if (output != null) {
- try {
- output.close();
- } catch (IOException logOrIgnore) {
- }
- }
- }
- } else {
- connection.connect();
- }
- int fileLength = connection.getContentLength();
- String charset = PREFERRED_CHARSET;
- if (connection.getContentEncoding() != null) {
- charset = connection.getContentEncoding();
- }
- int responseCode = connection.getResponseCode();
- for (Entry<String, List<String>> header : connection
- .getHeaderFields().entrySet()) {
- Log.v(TAG,
- "Header: "
- + (header.getKey() == null ? "" :
- "[" + header.getKey() + "]=")
- + header.getValue());
- }
- Log.v(TAG, "Response code " + responseCode);
- Log.v(TAG, "Content encoding " + charset);
- InputStream input;
- OutputStream output;
- boolean isError = false;
- try {
- input = connection.getInputStream();
- output = getOutput();
- } catch (IOException e) {
- input = connection.getErrorStream();
- output = getErrorOutput();
- isError = true;
- }
- byte data[] = new byte[1024];
- long total = 0;
- int count;
- while ((count = input.read(data)) != -1) {
- total += count;
- // publishing the progress....
- publishProgress((int) (total * 100 / fileLength));
- output.write(data, 0, count);
- }
- output.flush();
- if (!isError) {
- response = getResponse(output, charset);
- } else {
- response = getErrorResponse(output, charset);
- Log.e(TAG, response);
- response = null;
- }
- output.close();
- input.close();
- } catch (Exception e) {
- Log.e(TAG, "Failed requesting " + uri, e);
- }
- return response;
- }
- @Override
- protected void onProgressUpdate(Integer... values) {
- Log.d(TAG, "progress: " + values[0] + "%");
- }
- protected boolean isPost() {
- return true;
- }
- protected OutputStream getOutput() throws IOException {
- return new ByteArrayOutputStream();
- }
- protected OutputStream getErrorOutput() throws IOException {
- return new ByteArrayOutputStream();
- }
- protected String getResponse(OutputStream output, String charset)
- throws UnsupportedEncodingException {
- return ((ByteArrayOutputStream) output).toString(charset);
- }
- protected String getErrorResponse(OutputStream output, String charset)
- throws UnsupportedEncodingException {
- return ((ByteArrayOutputStream) output).toString(charset);
- }
- }
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.ac_main);
- try {
- String clientId = encode(CLIENT_ID);
- String clientSecret = encode(CLIENT_SECRET);
- 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.");
- String fromLanguage = encode("nl");
- String toLanguage = encode("en");
- String accessToken = null;
- String file = "test.wav";
- if (true) {
- HttpRequest task = new HttpRequest();
- task.execute(
- getString(R.string.url_oauth),
- getString(R.string.url_oauth_query, clientId,
- clientSecret));
- String response = task.get();
- if (response != null) {
- Log.d(TAG, response);
- JSONObject json = new JSONObject(response);
- accessToken = json.getString("access_token");
- } else {
- Log.w(TAG, "response was null");
- }
- }
- if (accessToken != null) {
- String translated = null;
- if (TRANSLATE) {
- HttpRequest task = new HttpRequest();
- task.execute(
- getString(R.string.url_translate),
- getString(R.string.url_translate_query,
- text, fromLanguage, toLanguage),
- accessToken);
- String response = task.get();
- if (response != null) {
- Log.d(TAG, response);
- // Do something with the response
- } else {
- Log.w(TAG, "response was null");
- }
- } else {
- translated = text;
- toLanguage = fromLanguage;
- }
- if (translated != null) {
- HttpDownloadFile task = new HttpDownloadFile();
- task.execute(
- getString(R.string.url_speak),
- getString(R.string.url_speak_query,
- text, toLanguage, file),
- accessToken,
- Environment.getExternalStorageDirectory().getPath()
- + PATH + file);
- String response = task.get();
- if (response == null) {
- Log.w(TAG, "response was null");
- } else {
- Log.i(TAG, response);
- }
- }
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- private String encode(String str) throws UnsupportedEncodingException {
- return URLEncoder.encode(
- str,
- PREFERRED_CHARSET);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement