Browse Source

[UPDATE] Creation compte client + verifs en cours

master
DAMBRINE Arthur 5 years ago
parent
commit
4de7857bce
  1. 1
      app/src/main/AndroidManifest.xml
  2. 20
      app/src/main/java/com/speculos/myapplicationoc/APICommandes.java
  3. 46
      app/src/main/java/com/speculos/myapplicationoc/JsonTraductor.java
  4. 27
      app/src/main/java/com/speculos/myapplicationoc/MainActivity.java
  5. 7
      app/src/main/java/com/speculos/myapplicationoc/MyApplication.java
  6. 5
      app/src/main/java/com/speculos/myapplicationoc/PaymentActivity.java
  7. 25
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivity.java
  8. 88
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivityAdmin.java
  9. 37
      app/src/main/java/com/speculos/myapplicationoc/ThreadPing.java

1
app/src/main/AndroidManifest.xml

@ -8,6 +8,7 @@
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"

20
app/src/main/java/com/speculos/myapplicationoc/APICommandes.java

@ -1,6 +1,7 @@
package com.speculos.myapplicationoc;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
@ -28,6 +29,7 @@ public class APICommandes {
static String getMethod(String url) throws IOException {
if (SDK_INT > 8) /*Eviter l'erreur android qui empêche call API dans le main thread*/
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
@ -39,7 +41,12 @@ public class APICommandes {
try {
URL myurl = new URL(url);
Log.d("API-debug","GET sur myurl: "+url);
con = (HttpURLConnection) myurl.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setRequestMethod("GET");
@ -60,6 +67,13 @@ public class APICommandes {
response = content.toString();
} catch (Exception e){
// handle exception here
Log.d("API-debug","Exception, GET a echoue, we return empty string");
return "";
} finally {
con.disconnect();
@ -90,6 +104,8 @@ public class APICommandes {
URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setDoOutput(true);
con.setRequestMethod("POST");
@ -118,6 +134,10 @@ public class APICommandes {
//System.out.println(content.toString());
response = content.toString();
} catch (Exception e) {
Log.d("API-debug","Exception, le call POST echoue");
} finally {
con.disconnect();

46
app/src/main/java/com/speculos/myapplicationoc/JsonTraductor.java

@ -1,5 +1,7 @@
package com.speculos.myapplicationoc;
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
@ -32,31 +34,45 @@ public class JsonTraductor {
// Parse le json et tiens à jour une liste d'objets json
listJson.clear();
if(jsonIsArray(json)){
try {
JsonArray entries = (JsonArray) new JsonParser().parse(json);
//String id = ((JsonObject)entries.get(0)).get("id").toString();
//System.out.println(id);
if(jsonIsArray(json)){
for(int i = 0; i<entries.size(); i++){
listJson.add(((JsonObject)entries.get(i)));
}
JsonArray entries = (JsonArray) new JsonParser().parse(json);
//String id = ((JsonObject)entries.get(0)).get("id").toString();
//System.out.println(id);
for(int i = 0; i<entries.size(); i++){
listJson.add(((JsonObject)entries.get(i)));
}
} else {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
JsonObject jsonObjectOne = jsonElement.getAsJsonObject();
//System.out.println(jsonObject.get("id"));
listJson.add(jsonObjectOne);
//System.out.println(listJson.get(0).get("id"));
} else {
JsonParser parser = new JsonParser();
JsonElement jsonElement = parser.parse(json);
JsonObject jsonObjectOne = jsonElement.getAsJsonObject();
//System.out.println(jsonObject.get("id"));
listJson.add(jsonObjectOne);
//System.out.println(listJson.get(0).get("id"));
}
} catch (Exception e){
// handle exception here
}
}
private static Boolean jsonIsArray(String json){
Log.d("JsonTraductor-debug","Json: "+json);
if (json != null){
return json.toCharArray()[0] != '{';
} else {
return false;
}
return json.toCharArray()[0] != '{';
}

27
app/src/main/java/com/speculos/myapplicationoc/MainActivity.java

@ -1,26 +1,24 @@
package com.speculos.myapplicationoc;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.app.PendingIntent;
import android.content.IntentFilter;
import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.UnsupportedEncodingException;
public class MainActivity extends AppCompatActivity {
@ -33,8 +31,11 @@ public class MainActivity extends AppCompatActivity {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
// Ping à mettre dans un thread
ThreadPing threadping = new ThreadPing();
ThreadPing threadping = new ThreadPing(myApplication.getServerURL());
threadping.start();
threadping.addListener(new PingListener() {

7
app/src/main/java/com/speculos/myapplicationoc/MyApplication.java

@ -4,10 +4,11 @@ import android.app.Application;
public class MyApplication extends Application {
private String serverIP = "art-dev";
private String serverURL = "http://art-dev:8080";
String getServerIP(){
return serverIP;
public String getServerURL(){
return serverURL;
}
}

5
app/src/main/java/com/speculos/myapplicationoc/PaymentActivity.java

@ -19,8 +19,11 @@ public class PaymentActivity extends AppCompatActivity {
static String hexa_id, title, soldeString;
static float solde;
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
String srvURL = myApplication.getServerURL();
// Temporaire
String srvURL = "http://192.168.1.21";
static String nfcId = "azerty";
@Override

25
app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivity.java

@ -17,14 +17,20 @@ public class TagDetectedActivity extends Activity {
String hexa_id, mail;
float solde = 0;
String srvURL;
// Temporaire
String srvURL = "http://192.168.1.21";
String nfcId = "azerty";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL();
setContentView(R.layout.activity_tag_detected);
hexa_id = getIntent().getStringExtra("hexa_id");
@ -47,20 +53,20 @@ public class TagDetectedActivity extends Activity {
e.printStackTrace();
}
String json = stringAPI;
JsonTraductor maListeJson = new JsonTraductor(json);
JsonTraductor maListeJson = new JsonTraductor(stringAPI);
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 0));
mail = maListeJson.getJsonData("email", 0);
mail = mail.substring(1,mail.length()-1);
if(mail == null){
if( (mail = maListeJson.getJsonData("email", 0)) != null ){
mail = mail.substring(1,mail.length()-1);
} else {
mail = "-";//Assign default string
}
TextView value_mail = findViewById(R.id.value_mail);
value_mail.setText(mail);
solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));
try {solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));} catch(Exception e) { solde = 0;}
TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde+" €");
@ -109,11 +115,10 @@ public class TagDetectedActivity extends Activity {
e.printStackTrace();
}
String json = stringAPI2;
JsonTraductor maListeJson = new JsonTraductor(json);
JsonTraductor maListeJson = new JsonTraductor(stringAPI2);
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 0));
solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));
try{solde = Float.parseFloat(maListeJson.getJsonData("solde", 0));} catch(Exception e){solde = 0;}
TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde+" €");
}

88
app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivityAdmin.java

@ -1,7 +1,6 @@
package com.speculos.myapplicationoc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
@ -13,19 +12,26 @@ import android.widget.Toast;
import androidx.annotation.Nullable;
import java.io.IOException;
import java.util.regex.Pattern;
public class TagDetectedActivityAdmin extends Activity {
String hexa_id, mail;
String hexa_id, mail, username;
// recuperation de MyApplication contenant les variables globales
// MyApplication myApplication = (MyApplication) getApplication();
String srvURL;
// Temporaire
String srvURL = "http://192.168.1.21";
String nfcId = "azerty";
// String nfcId = "azerty";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL();
setContentView(R.layout.activity_tag_detected_admin);
hexa_id = getIntent().getStringExtra("hexa_id");
@ -47,7 +53,79 @@ public class TagDetectedActivityAdmin extends Activity {
// Vérifications et Call API créer le compte
EditText value_mail = findViewById(R.id.value_mail);
mail = value_mail.getText().toString();
Toast.makeText(TagDetectedActivityAdmin.this, mail, Toast.LENGTH_LONG).show();
username = mail.subSequence(0,mail.indexOf("@")).toString();
// Validation du champ email
String regex = "^[\\w!#$%&'*+/=?`{|}~^-]+(?:\\.[\\w!#$%&'*+/=?`{|}~^-]+)*@(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,6}$";
Pattern pattern = Pattern.compile(regex);
if(pattern.matcher(mail).matches()){
// L'email est validé par la regex on va pouvoir préparer la requête de verif si compte existe
// Call l'API pour voir si un client avec ce mail existe
String apiResponse = "";
try {
apiResponse = APICommandes.getMethod(srvURL + "/api/clients.json?email=" + mail);
} catch (IOException e) {
e.printStackTrace();
}
if(apiResponse.length() <=3 ) {
// Le mail n'est pas présent créer un nouveau compte.
Toast.makeText(TagDetectedActivityAdmin.this, "Création de compte NFC Cashless, mail:"+mail+" name:"+username+" bracelet:"+hexa_id, Toast.LENGTH_LONG).show();
String response = "";
try {
response = APICommandes.postMethod(srvURL + "/api/clients","{\"name\": \"" + username + "\", \"email\": \"" + mail + "\", \"solde\" :"+0+"}");
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(TagDetectedActivityAdmin.this, "Error", Toast.LENGTH_LONG).show();
}
if(response.length() <=3 ) {
// Info sur le retour du POST Creation client
Toast.makeText(TagDetectedActivityAdmin.this, "Server not responding: " + response, Toast.LENGTH_LONG).show();
} else {
// Creation du compte réussie, link le bracelet au compte client (TODO: penser à faire les verifs si bracelet existe avant de créer un compte client)
// Une fois qu'on a vérifié que le bracelet n'existe pas dans la base on l'ajoute au client
// On commence par parser la reponse de l'appel POST précédent pour avoir l'idClient sans refaire de requête
JsonTraductor maListeJson = new JsonTraductor(response);
int idClient = Integer.parseInt((maListeJson.getJsonData("id", 0)));
// On peut maintenant link le bracelet grace à l'hexa_id et l'idClient
try {
response = APICommandes.postMethod(srvURL + "/api/bracelets","{\"nfcId\": \"" + hexa_id + "\", \"client\": \"/api/clients/" + idClient + "\", \"state\" :"+0+"}");
Toast.makeText(TagDetectedActivityAdmin.this, "Message: " + response, Toast.LENGTH_LONG).show();
Log.d("DEBUG-CLIENT",response);
try{
maListeJson = new JsonTraductor(response);
String violationMessage = ((maListeJson.getJsonData("violations", 0)));
Toast.makeText(TagDetectedActivityAdmin.this, "Message: "+violationMessage, Toast.LENGTH_LONG).show();
} catch (Exception e) {}
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
// Le mail est déjà present en base
Toast.makeText(TagDetectedActivityAdmin.this, "Le mail est déjà présent en base. Souhaitez vous ajouter ce bracelet au compte: "+mail, Toast.LENGTH_LONG).show();
}
} else {
// Le mail ne match pas la regex mail
Toast.makeText(TagDetectedActivityAdmin.this, "Message:"+mail+" non valide", Toast.LENGTH_LONG).show();
}
}
});

37
app/src/main/java/com/speculos/myapplicationoc/ThreadPing.java

@ -1,20 +1,24 @@
package com.speculos.myapplicationoc;
import java.net.InetAddress;
import java.io.IOException;
public class ThreadPing extends Thread {
public static Boolean isReachable;
// Temporaire
private String ipA = "192.168.1.21";
/* Ce ThreadPing n'est pas un "ping" à proprement parler
* on réalise un call GET sur http://domain.dev/api
* pour savoir si le serveur répond
* */
public static Boolean isReachable;
private String url;
// private String ipA =
// Constructeur
public ThreadPing(String url){
this.url = url;
}
private int delay = 3000; // temps entre chaque ping 3sec
private int delay = 3000; // temps entre chaque ping 5sec
private PingListener listen = null;
@ -26,26 +30,29 @@ public class ThreadPing extends Thread {
while(true) {
try {
String ipAddress = ipA;
InetAddress inet = InetAddress.getByName(ipAddress);
//System.out.println("Sending Ping Request to " + ipAddress);
if (inet.isReachable(4000)) {
String apiResponse = "";
try {
apiResponse = APICommandes.getMethod(url + "/api");
// Si PING OK declenche l'event ping(isReachable)
} catch (IOException e) {
e.printStackTrace();
}
if (apiResponse != "") {
// Si PING OK declenche l'event ping(isReachable)
isReachable = true;
if(listen != null) listen.ping(isReachable);
} else {
// Si PING NOT OK declenche l'event ping(isReachable)
isReachable = false;
if(listen != null) listen.ping(isReachable);
}
} catch (Exception e) {
System.out.println("Exception:" + e.getMessage());
}
try {

Loading…
Cancel
Save