From f597cf6456b8ad6bf8dc8bc0698a6b45b353df9c Mon Sep 17 00:00:00 2001 From: aj Date: Fri, 31 Jan 2020 22:30:28 +0000 Subject: [PATCH] added initial http method and login task --- .../com/example/applogin/Login2Activity.java | 77 ++++--------- .../applogin/network/AbstractNetworkTask.java | 109 ++++++++++++++++++ .../example/applogin/network/LoginTask.java | 37 ++++++ 3 files changed, 169 insertions(+), 54 deletions(-) create mode 100644 app/src/main/java/com/example/applogin/network/AbstractNetworkTask.java create mode 100644 app/src/main/java/com/example/applogin/network/LoginTask.java diff --git a/app/src/main/java/com/example/applogin/Login2Activity.java b/app/src/main/java/com/example/applogin/Login2Activity.java index ad8eedb..9c3b3a9 100644 --- a/app/src/main/java/com/example/applogin/Login2Activity.java +++ b/app/src/main/java/com/example/applogin/Login2Activity.java @@ -1,6 +1,5 @@ package com.example.applogin; -import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; @@ -11,30 +10,13 @@ import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.Bundle; -import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; -import com.android.volley.Request; -import com.android.volley.RequestQueue; -import com.android.volley.Response; -import com.android.volley.VolleyError; -import com.android.volley.toolbox.JsonObjectRequest; -import com.android.volley.toolbox.StringRequest; -import com.android.volley.toolbox.Volley; -import com.google.android.gms.tasks.OnCompleteListener; -import com.google.android.gms.tasks.Task; -import com.google.firebase.iid.FirebaseInstanceId; -import com.google.firebase.iid.InstanceIdResult; - -import org.json.JSONException; -import org.json.JSONObject; - -import java.net.ConnectException; -import java.util.HashMap; -import java.util.Map; +import com.example.applogin.network.LoginTask; +import java.util.concurrent.ExecutionException; public class Login2Activity extends AppCompatActivity { @@ -96,44 +78,31 @@ public class Login2Activity extends AppCompatActivity { private void tryLogin(String username, String password) { - // Instantiate the RequestQueue. - RequestQueue queue = Volley.newRequestQueue(this); - String url ="https://ev-scheduler.appspot.com/api/auth/login"; + LoginTask task = new LoginTask(username, password); + task.execute(); - HashMap dict = new HashMap<>(); - dict.put("username", username); - dict.put("password", password); - JSONObject json = new JSONObject(dict); + try { + String result = task.get(); - // Request a string response from the provided URL. - final JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, json, - new Response.Listener() { - @Override - public void onResponse(JSONObject response) { - try { - //Toast.makeText(Login2Activity.this, response.getString("token"), Toast.LENGTH_SHORT).show(); - //System.out.println(response.toString()); - SharedPreferences context = getApplicationContext().getSharedPreferences("scheduler_preferences", Context.MODE_PRIVATE); - SharedPreferences.Editor editor = context.edit(); - editor.putString("api_key", response.getString("token")); - editor.apply(); - Intent myIntent = new Intent(Login2Activity.this, JoinQueueActivity.class); - startActivity(myIntent); - }catch(JSONException e){ - //could put an error message here - } - } - }, new Response.ErrorListener() { - @Override - public void onErrorResponse(VolleyError error) { - //Toast.makeText(Login2Activity.this, Integer.toString(error.networkResponse.statusCode), Toast.LENGTH_SHORT).show(); - //Put error message (failed login, 3 different messages) - //if error.networkResponse.statusCode == 401 , message wrong password (auth_blueprint.py) + if (result == null) { + + Toast.makeText(Login2Activity.this, "error", Toast.LENGTH_SHORT).show(); + + }else{ + + SharedPreferences context = getApplicationContext().getSharedPreferences("scheduler_preferences", Context.MODE_PRIVATE); + SharedPreferences.Editor editor = context.edit(); + editor.putString("api_key", result); + editor.apply(); + Intent myIntent = new Intent(Login2Activity.this, JoinQueueActivity.class); + startActivity(myIntent); } - }); -// Add the request to the RequestQueue. - queue.add(stringRequest); + } catch (ExecutionException e) { + e.printStackTrace(); + } catch (InterruptedException e) { + e.printStackTrace(); + } } diff --git a/app/src/main/java/com/example/applogin/network/AbstractNetworkTask.java b/app/src/main/java/com/example/applogin/network/AbstractNetworkTask.java new file mode 100644 index 0000000..905354b --- /dev/null +++ b/app/src/main/java/com/example/applogin/network/AbstractNetworkTask.java @@ -0,0 +1,109 @@ +package com.example.applogin.network; + +import android.os.AsyncTask; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.util.HashMap; +import java.net.URL; +import java.net.HttpURLConnection; +import java.util.Map; + +import org.json.JSONException; +import org.json.JSONObject; + +public abstract class AbstractNetworkTask extends AsyncTask { + + private static final int READ_TIMEOUT = 15000; + private static final int CONNECTION_TIMEOUT = 15000; + + protected class Result { + public JSONObject response; + public int statusCode; + } + + public enum HTTPMethod { + GET, POST, PUT, DELETE + } + + protected String getAPIUrl(String suffix){ + return "https://ev-scheduler.appspot.com/" + suffix; + } + + protected Result makeAuthenticatedRequest(String url, HTTPMethod method, HashMap params, HashMap headers, String api_key){ + + if (headers == null) { + headers = new HashMap<>(); + } + + headers.put("Authorization", "Bearer " + api_key); + return makeRequest(url, method, params, headers); + } + + protected Result makeRequest(String url, HTTPMethod method, HashMap params, HashMap headers) { + Result result = new Result(); + String inputLine; + HttpURLConnection connection = null; + try { + //Create a URL object holding our url + URL myUrl = new URL(url); + connection = (HttpURLConnection) myUrl.openConnection(); + + if(method == HTTPMethod.POST || method == HTTPMethod.PUT){ + connection.setDoOutput(true); + connection.setRequestProperty("Content-Type", "application/json; utf-8"); + } + + if (headers != null) { + for (Map.Entry entry : headers.entrySet()) { + connection.setRequestProperty(entry.getKey(), entry.getKey()); + } + } + + connection.setRequestMethod(method.toString()); + connection.setRequestProperty("Accept", "application/json"); + connection.setReadTimeout(READ_TIMEOUT); + connection.setConnectTimeout(CONNECTION_TIMEOUT); + + connection.connect(); + + if(method == HTTPMethod.POST || method == HTTPMethod.PUT){ + JSONObject body = new JSONObject(params); + OutputStream os = connection.getOutputStream(); + byte[] input = body.toString().getBytes("utf-8"); + os.write(input, 0, input.length); + os.flush(); + os.close(); + } + + InputStreamReader streamReader = new InputStreamReader(connection.getInputStream()); + BufferedReader reader = new BufferedReader(streamReader); + StringBuilder stringBuilder = new StringBuilder(); + + while((inputLine = reader.readLine()) != null){ + stringBuilder.append(inputLine); + } + reader.close(); + streamReader.close(); + + result.statusCode = connection.getResponseCode(); + result.response = new JSONObject(stringBuilder.toString()); + } + catch (IOException e) { + e.printStackTrace(); + } + catch (JSONException e) { + e.printStackTrace(); + } + finally { + if (connection != null) { + connection.disconnect(); + } + } + + return result; + + } +} diff --git a/app/src/main/java/com/example/applogin/network/LoginTask.java b/app/src/main/java/com/example/applogin/network/LoginTask.java new file mode 100644 index 0000000..59bb7da --- /dev/null +++ b/app/src/main/java/com/example/applogin/network/LoginTask.java @@ -0,0 +1,37 @@ +package com.example.applogin.network; + +import org.json.JSONException; + +import java.util.HashMap; + +public class LoginTask extends AbstractNetworkTask { + + private String username; + private String password; + + public LoginTask(String username, String password){ + super(); + this.username = username; + this.password = password; + } + + @Override + protected String doInBackground(Void... params) { + HashMap body = new HashMap<>(); + body.put("username", username); + body.put("password", password); + + Result result = makeRequest(getAPIUrl("api/auth/login"), HTTPMethod.POST, body, null); + + try { + if (200 <= result.statusCode && result.statusCode < 300) + return result.response.getString("token"); + + } catch (JSONException e) { + e.printStackTrace(); + } + + return null; + + } +}