Browse Source

[Refactoring] nouveau code avec okHtpp et JSONObject

master
art.dambrine 5 years ago
parent
commit
861eeb5ce8
  1. BIN
      app/libs/gson-2.8.6-javadoc.jar
  2. BIN
      app/libs/gson-2.8.6.jar
  3. 150
      app/src/main/java/com/speculos/myapplicationoc/APICommandes.java
  4. 92
      app/src/main/java/com/speculos/myapplicationoc/JsonTraductor.java
  5. 36
      app/src/main/java/com/speculos/myapplicationoc/MainActivity.java
  6. 2
      app/src/main/java/com/speculos/myapplicationoc/MyApplication.java
  7. 121
      app/src/main/java/com/speculos/myapplicationoc/PaymentActivity.java
  8. 124
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivity.java
  9. 77
      app/src/main/java/com/speculos/myapplicationoc/TagDetectedActivityAdmin.java
  10. 29
      app/src/main/java/com/speculos/myapplicationoc/ThreadPing.java

BIN
app/libs/gson-2.8.6-javadoc.jar

Binary file not shown.

BIN
app/libs/gson-2.8.6.jar

Binary file not shown.

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

@ -1,150 +0,0 @@
package com.speculos.myapplicationoc;
import android.os.StrictMode;
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class APICommandes {
private static HttpURLConnection con;
private static String response;
private static int SDK_INT = android.os.Build.VERSION.SDK_INT;
/*
A propos de l'implementation JWT :
Using the token
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("Authorization", "Bearer " + accessToken);
*/
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()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
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");
StringBuilder content;
try (BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = in.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
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();
}
return response;
}
public static String postMethod(String url, String urlParameters) throws IOException {
/*
Exemple de paramètres pour faire un POST :
String urlParameters = "{\"name\": \"user4\", \"solde\": 22, \"email\": \"user4@mail.fr\"}";
*/
if (SDK_INT > 8) /*Eviter l'erreur android qui empêche call API dans le main thread*/
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
}
byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
try {
URL myurl = new URL(url);
con = (HttpURLConnection) myurl.openConnection();
con.setConnectTimeout(5000);
con.setReadTimeout(5000);
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", "Java client");
con.setRequestProperty("Content-Type", "application/json");
try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
wr.write(postData);
}
StringBuilder content;
try (BufferedReader br = new BufferedReader(
new InputStreamReader(con.getInputStream()))) {
String line;
content = new StringBuilder();
while ((line = br.readLine()) != null) {
content.append(line);
content.append(System.lineSeparator());
}
}
//System.out.println(content.toString());
response = content.toString();
} catch (Exception e) {
Log.d("API-debug","Exception, le call POST echoue");
} finally {
con.disconnect();
}
return response;
}
}

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

@ -1,92 +0,0 @@
package com.speculos.myapplicationoc;
import android.util.Log;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.util.ArrayList;
import java.util.List;
public class JsonTraductor {
private String json;
private List<JsonObject> listJson = new ArrayList<JsonObject>();
public JsonTraductor(){
// Json de test
// {"id":1,"nfcId":"azerty","client":{"id":1,"name":"Omer"},"state":1}
// "[{\"id\":1,\"nfcId\":\"azerty\",\"client\":{\"id\":1,\"name\":\"Omer\"},\"state\":1},{\"id\":2,\"nfcId\":\"oui\",\"client\":null,\"state\":0}]";
json = "{\"id\":1,\"nfcId\":\"azerty\",\"client\":{\"id\":1,\"name\":\"Omer\"},\"state\":1}";
}
JsonTraductor(String jsonEntry){
json = jsonEntry;
buildList();
}
private void buildList(){
// Parse le json et tiens à jour une liste d'objets json
listJson.clear();
try {
if(jsonIsArray(json)){
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"));
}
} 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;
}
}
String getJsonData(String jsonId, int jsonIndex){
if(jsonIndex >= listJson.size()){
// pour ne pas depasser l'index final
return null;
} else {
return listJson.get(jsonIndex).get(jsonId).toString();
}
}
}

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

@ -44,19 +44,19 @@ public class MainActivity extends AppCompatActivity {
TextView indicateur_etat_connexion = findViewById(R.id.indicateur_etat_connexion);
TextView indicateur_nfc_actif = findViewById(R.id.indicateur_nfc_actif);
if(isReachable){
Log.d("PING"," is reachable.");
if (isReachable) {
Log.d("PING", " is reachable.");
indicateur_etat_connexion.setText("OK");
} else {
Log.d("PING"," NOT reachable.");
Log.d("PING", " NOT reachable.");
indicateur_etat_connexion.setText("NOT OK");
}
if(nfcAdapter.isEnabled()){
Log.d("NFC"," is enabled.");
if (nfcAdapter.isEnabled()) {
Log.d("NFC", " is enabled.");
indicateur_nfc_actif.setText("OK");
} else {
Log.d("NFC"," NOT enabled.");
Log.d("NFC", " NOT enabled.");
indicateur_nfc_actif.setText("NOT OK");
}
}
@ -73,7 +73,7 @@ public class MainActivity extends AppCompatActivity {
Button myButton = findViewById(R.id.submit_button);
if(modeEdition){
if (modeEdition) {
modeEdition = false;
title.setText("NFC Reader");
myButton.setText("Aller au mode Edition");
@ -96,7 +96,7 @@ public class MainActivity extends AppCompatActivity {
// Verif NFC Actif
TextView indicateur_nfc_actif = findViewById(R.id.indicateur_nfc_actif);
if(nfcAdapter.isEnabled()){
if (nfcAdapter.isEnabled()) {
indicateur_nfc_actif.setText("OK");
} else {
indicateur_nfc_actif.setText("NOT OK");
@ -253,8 +253,8 @@ public class MainActivity extends AppCompatActivity {
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
NdefMessage msg = new NdefMessage(new NdefRecord[]{record});
msgs = new NdefMessage[]{msg};
}
return buildTagViews(msgs);
@ -281,7 +281,7 @@ public class MainActivity extends AppCompatActivity {
} catch (UnsupportedEncodingException e) {
Log.e("UnsupportedEncoding", e.toString());
}
Log.d("buildTagViews",text);
Log.d("buildTagViews", text);
return text;
}
@ -306,7 +306,7 @@ public class MainActivity extends AppCompatActivity {
}
@Override
protected void onNewIntent(Intent intent) {
protected void onNewIntent(Intent intent) {
//String action = intent.getAction();
//Toast.makeText(this, action, Toast.LENGTH_SHORT).show();
@ -315,13 +315,13 @@ public class MainActivity extends AppCompatActivity {
String lines[] = NFC_info.split("\\r?\\n");
Log.d("StringToParse",lines[0]);
Log.d("StringToParse", lines[0]);
int left = lines[0].indexOf(":"); /* correspond à (hex): 80 5e 2b 22 3d 8f 04 */
String sub = lines[0].substring(left+1);
String sub = lines[0].substring(left + 1);
sub = sub.trim();
Log.d("StringToParse",sub);
Log.d("StringToParse", sub);
Toast.makeText(this, "Tag NFC détecté", Toast.LENGTH_SHORT).show();
@ -329,16 +329,16 @@ public class MainActivity extends AppCompatActivity {
super.onNewIntent(intent);
if(modeEdition){
if (modeEdition) {
Intent myIntent = new Intent(MainActivity.this, TagDetectedActivityAdmin.class);
myIntent.putExtra("hexa_id",sub);
myIntent.putExtra("hexa_id", sub);
startActivity(myIntent);
} else {
Intent myIntent = new Intent(MainActivity.this, TagDetectedActivity.class);
myIntent.putExtra("hexa_id",sub);
myIntent.putExtra("hexa_id", sub);
startActivity(myIntent);
}

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

@ -6,9 +6,7 @@ public class MyApplication extends Application {
private String serverURL = "http://art-dev:8080";
public String getServerURL(){
return serverURL;
}
}

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

@ -12,28 +12,40 @@ import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class PaymentActivity extends AppCompatActivity {
static String hexa_id, title, soldeString;
static String hexa_id, title, soldeString, srvURL;
static float solde;
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
String srvURL = myApplication.getServerURL();
// Temporaire
static String nfcId = "azerty";
// static 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();
// Load le layout
setContentView(R.layout.activity_payment);
hexa_id = getIntent().getStringExtra("hexa_id");
if(hexa_id == null){
if (hexa_id == null) {
hexa_id = "-";//Assign default string
}
@ -43,7 +55,7 @@ public class PaymentActivity extends AppCompatActivity {
title_payment.setText("Error");
if(isPayment()){
if (isPayment()) {
title_payment.setText("Payer");
soldeString = getIntent().getStringExtra("solde");
solde = Float.parseFloat(soldeString);
@ -59,48 +71,72 @@ public class PaymentActivity extends AppCompatActivity {
edit_number.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);
InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Button button_valid = findViewById(R.id.button_valid);
button_valid.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Call api payment
String transaction_label = ((EditText)(findViewById(R.id.edit_number))).getText().toString();
String transaction_label = ((EditText) (findViewById(R.id.edit_number))).getText().toString();
float transaction_value = Float.parseFloat(transaction_label);
Boolean valider_transaction = false;
if (transaction_label.contains(".")){
if (transaction_label.contains(".")) {
// Valeur float avec virgule
if(transaction_label.split("[.]")[1].length() > 2){
if (transaction_label.split("[.]")[1].length() > 2) {
Log.d("PAYMENT-debug","Error too long");
Log.d("PAYMENT-debug", "Error too long");
Toast.makeText(PaymentActivity.this, "Trop long!", Toast.LENGTH_LONG).show();
} else {
Log.d("PAYMENT-debug",""+transaction_value);
Log.d("PAYMENT-debug", "" + transaction_value);
valider_transaction = true;
}
} else {
// Valeur float sans virgule
Log.d("PAYMENT-debug",""+transaction_value);
Log.d("PAYMENT-debug", "" + transaction_value);
valider_transaction = true;
}
if(valider_transaction){
if(isPayment()){
if(solde < transaction_value){
if (valider_transaction) {
if (isPayment()) {
if (solde < transaction_value) {
Toast.makeText(PaymentActivity.this, "Pas assez d'argent!", Toast.LENGTH_LONG).show();
} else {
// Call API Paiement
try {
String response = APICommandes.postMethod(srvURL + "/api/payment","{\"nfcId\": \"" + nfcId + "\", \"price\": " + transaction_value + "}");
Log.d("PAYMENT-debug",response);
} catch (IOException e) {
Toast.makeText(PaymentActivity.this, "Pas assez d'argent!", Toast.LENGTH_LONG).show();
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"price\": " + transaction_value + "}\n");
Request request = new Request.Builder()
.url(srvURL + "/api/payment")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
Log.d("PAYMENT-debug", response.body().toString());
JSONObject jsonReader = null;
jsonReader = new JSONObject(response.body().string());
String message = jsonReader.getString("message");
if (response.code() == 200) {
// Paiement effectué
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
}
} catch (IOException | JSONException e) {
Toast.makeText(PaymentActivity.this, "Erreur lors de la connexion au serveur", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@ -109,10 +145,38 @@ public class PaymentActivity extends AppCompatActivity {
} else {
//Call API Rechargement
try {
String response = APICommandes.postMethod(srvURL + "/api/load","{\"nfcId\": \"" + nfcId + "\", \"price\": " + transaction_value + "}");
Log.d("PAYMENT-debug",response);
} catch (IOException e) {
Toast.makeText(PaymentActivity.this, "Erreur rechargement!", Toast.LENGTH_LONG).show();
// String response = APICommandes.postMethod(srvURL + "/api/load","{\"nfcId\": \"" + hexa_id + "\", \"price\": " + transaction_value + "}");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"price\": " + transaction_value + "}\n");
Request request = new Request.Builder()
.url(srvURL + "/api/load")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
Log.d("PAYMENT-debug", response.body().toString());
JSONObject jsonReader = null;
jsonReader = new JSONObject(response.body().string());
String message = jsonReader.getString("message");
if (response.code() == 200) {
// Rechargement effectué
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
finish();
} else if (response.code() == 406) {
Toast.makeText(PaymentActivity.this, message, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(PaymentActivity.this, "Erreur rechargement! " + message, Toast.LENGTH_LONG).show();
}
} catch (IOException | JSONException e) {
Toast.makeText(PaymentActivity.this, "Erreur lors de la connexion au serveur", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
@ -120,14 +184,13 @@ public class PaymentActivity extends AppCompatActivity {
}
}
});
}
private static Boolean isPayment(){
if(title.equals("Payer")){
private static Boolean isPayment() {
if (title.equals("Payer")) {
return true;
} else {
return false;

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

@ -3,29 +3,39 @@ package com.speculos.myapplicationoc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class TagDetectedActivity extends Activity {
String hexa_id, mail;
String hexa_id, mail, srvURL;
float solde = 0;
String srvURL;
// Temporaire
String nfcId = "azerty";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Tweak pour contourner l'erreur android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// recuperation de MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL();
@ -35,7 +45,7 @@ public class TagDetectedActivity extends Activity {
hexa_id = getIntent().getStringExtra("hexa_id");
if(hexa_id == null){
if (hexa_id == null) {
hexa_id = "-";//Assign default string
}
@ -47,41 +57,61 @@ public class TagDetectedActivity extends Activity {
String stringAPI = "";
try {
stringAPI = APICommandes.getMethod(srvURL + "/api/bracelets.json?nfcId="+ nfcId);
Log.d("API-debug",stringAPI);
} catch (IOException e) {
e.printStackTrace();
}
JsonTraductor maListeJson = new JsonTraductor(stringAPI);
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 0));
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/bracelets.json?nfcId=" + hexa_id)
.method("GET", null)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
String in = response.body().string();
in = in.substring(1, in.length() - 1); // on retire le [] autour de notre json premier et dernier char
Log.d("API-debug-in", in);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(in);
jsonObject = new JSONObject(jsonObject.get("client").toString()); // recup client embed dans l'objet parent
} catch (JSONException e) {
Log.d("API-debug", e.getMessage());
}
if( (mail = maListeJson.getJsonData("email", 0)) != null ){
mail = mail.substring(1,mail.length()-1);
} else {
mail = "-";//Assign default string
}
String mail = null;
mail = jsonObject.getString("email");
solde = Float.parseFloat(jsonObject.getString("solde"));
TextView value_mail = findViewById(R.id.value_mail);
value_mail.setText(mail);
TextView value_mail = findViewById(R.id.value_mail);
value_mail.setText(mail);
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+" €");
} catch (IOException | JSONException e) {
e.printStackTrace();
Log.d("API-debug-exception", e.getMessage());
Toast.makeText(TagDetectedActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
finish();
}
TextView value_solde = findViewById(R.id.value_solde);
value_solde.setText(solde + " €");
Button button_payer = findViewById(R.id.button_enregistrer);
button_payer.setOnClickListener( new View.OnClickListener() {
button_payer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(TagDetectedActivity.this, PaymentActivity.class);
myIntent.putExtra("hexa_id",hexa_id);
myIntent.putExtra("title","Payer");
myIntent.putExtra("solde", ""+solde);
myIntent.putExtra("hexa_id", hexa_id);
myIntent.putExtra("title", "Payer");
myIntent.putExtra("solde", "" + solde);
startActivity(myIntent);
}
@ -89,12 +119,12 @@ public class TagDetectedActivity extends Activity {
Button button_recharger = findViewById(R.id.button_retour);
button_recharger.setOnClickListener( new View.OnClickListener() {
button_recharger.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent myIntent = new Intent(TagDetectedActivity.this, PaymentActivity.class);
myIntent.putExtra("hexa_id",hexa_id);
myIntent.putExtra("title","Recharger");
myIntent.putExtra("hexa_id", hexa_id);
myIntent.putExtra("title", "Recharger");
startActivity(myIntent);
}
@ -106,20 +136,40 @@ public class TagDetectedActivity extends Activity {
super.onResume();
// code à la fermeture de myIntent
String stringAPI2 = "";
try {
stringAPI2 = APICommandes.getMethod(srvURL + "/api/bracelets.json?nfcId="+ nfcId);
Log.d("API-debug",stringAPI2);
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/bracelets.json?nfcId=" + hexa_id)
.method("GET", null)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
String in = response.body().string();
in = in.substring(1, in.length() - 1);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(in);
jsonObject = new JSONObject(jsonObject.get("client").toString()); // recup client embed dans l'objet parent
solde = Float.parseFloat(jsonObject.getString("solde"));
} catch (JSONException e) {
Log.d("API-debug", e.getMessage());
}
} catch (IOException e) {
e.printStackTrace();
}
JsonTraductor maListeJson = new JsonTraductor(stringAPI2);
maListeJson = new JsonTraductor(maListeJson.getJsonData("client", 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+" €");
value_solde.setText(solde + " €");
}
}

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

@ -2,6 +2,7 @@ package com.speculos.myapplicationoc;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
@ -15,6 +16,7 @@ import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import okhttp3.MediaType;
@ -27,24 +29,27 @@ public class TagDetectedActivityAdmin extends Activity {
String hexa_id, mail, username, srvURL;
// recuperation de MyApplication contenant les variables globales
// MyApplication myApplication = (MyApplication) getApplication();
// Temporaire
// String nfcId = "azerty";
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Tweak pour contourner l'erreur android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
// Récupération MyApplication contenant les variables globales
MyApplication myApplication = (MyApplication) getApplication();
srvURL = myApplication.getServerURL();
// Setup de la vue à partir du layout
setContentView(R.layout.activity_tag_detected_admin);
hexa_id = getIntent().getStringExtra("hexa_id");
if (hexa_id == null) {
hexa_id = "-";//Assign default string
//Assign default string
hexa_id = "-";
}
TextView value_NFCID = findViewById(R.id.value_NFCID);
@ -57,59 +62,76 @@ public class TagDetectedActivityAdmin extends Activity {
@Override
public void onClick(View view) {
if (hexa_id.equals("-")) return; // si hexa_id non définit return onClick
// Vérifications et Call API créer le compte
EditText value_mail = findViewById(R.id.value_mail);
mail = value_mail.getText().toString();
username = mail.subSequence(0,mail.indexOf("@")).toString();
if (mail.length() > 0) 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()){
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 = "";
Response apiResponse = null;
String strReponse = "";
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(2000, TimeUnit.MILLISECONDS)
.callTimeout(2000, TimeUnit.MILLISECONDS)
.build();
Request request = new Request.Builder()
.url(srvURL + "/api/clients.json?email=" + mail)
.method("GET", null)
.build();
try {
apiResponse = APICommandes.getMethod(srvURL + "/api/clients.json?email=" + mail);
apiResponse = client.newCall(request).execute();
Log.d("API-CLIENT-DEBUG", "api:" + apiResponse.code());
strReponse = apiResponse.body().string();
} catch (IOException e) {
e.printStackTrace();
Log.d("API-CLIENT-DEBUG", "Server not responding");
Toast.makeText(TagDetectedActivityAdmin.this, "Server not responding", Toast.LENGTH_LONG).show();
return;
}
if(apiResponse.length() <=3 ) {
if (strReponse.length() <= 3 && strReponse.length() > 0) {
// 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();
Toast.makeText(TagDetectedActivityAdmin.this, "Création de compte NFC Cashless, mail:" + mail + " name:" + username + " bracelet:" + hexa_id, Toast.LENGTH_LONG).show();
Response responseHttp = null;
try {
// response = APICommandes.postMethod(srvURL + "/api/clients","{\"name\": \"" + username + "\", \"email\": \"" + mail + "\", \"solde\" :"+0+"}");
OkHttpClient client = new OkHttpClient().newBuilder()
client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"name\": \""+username+"\",\"email\": \""+mail+"\",\"solde\": 0}");
Request request = new Request.Builder()
RequestBody body = RequestBody.create(mediaType, "{\"name\": \"" + username + "\",\"email\": \"" + mail + "\",\"solde\": 0}");
request = new Request.Builder()
.url(srvURL + "/api/clients")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
responseHttp = client.newCall(request).execute();
responseHttp = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(TagDetectedActivityAdmin.this, "Error", Toast.LENGTH_LONG).show();
}
if(responseHttp.body().toString().length() <=3 ) {
if (responseHttp.body().toString().length() <= 3) {
// Info sur le retour du POST Creation client
Toast.makeText(TagDetectedActivityAdmin.this, "Server not responding: " + responseHttp.body().toString(), 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*/
@ -125,27 +147,26 @@ public class TagDetectedActivityAdmin extends Activity {
}
// On peut maintenant link le bracelet grace à l'hexa_id et l'idClient
try {
OkHttpClient client = new OkHttpClient().newBuilder()
client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \""+hexa_id+"\",\"client\": \"/api/clients/"+idClient+"\",\"state\": 0}");
Request request = new Request.Builder()
RequestBody body = RequestBody.create(mediaType, "{\"nfcId\": \"" + hexa_id + "\",\"client\": \"/api/clients/" + idClient + "\",\"state\": 0}");
request = new Request.Builder()
.url(srvURL + "/api/bracelets")
.method("POST", body)
.addHeader("Content-Type", "application/json")
.build();
responseHttp = client.newCall(request).execute();
responseHttp = client.newCall(request).execute();
if (responseHttp.code() == 400) {
try {
jsonReader = new JSONObject(responseHttp.body().string());
Log.d("JSON-MSG","violations: "+ jsonReader.getJSONArray("violations").getString(0));
Toast.makeText(TagDetectedActivityAdmin.this, "violations: "+ jsonReader.getJSONArray("violations").getString(0), Toast.LENGTH_LONG).show();
Log.d("JSON-MSG", "violations: " + jsonReader.getJSONArray("violations").getString(0));
Toast.makeText(TagDetectedActivityAdmin.this, "violations: " + jsonReader.getJSONArray("violations").getString(0), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
}
@ -160,13 +181,13 @@ public class TagDetectedActivityAdmin extends Activity {
} 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();
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();
Toast.makeText(TagDetectedActivityAdmin.this, "Message:" + mail + " non valide", Toast.LENGTH_LONG).show();
}
}

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

@ -2,19 +2,23 @@ package com.speculos.myapplicationoc;
import java.io.IOException;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class ThreadPing extends Thread {
/* 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
* */
* 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;
// Constructeur
public ThreadPing(String url){
public ThreadPing(String url) {
this.url = url;
}
@ -22,17 +26,24 @@ public class ThreadPing extends Thread {
private PingListener listen = null;
public void addListener(PingListener listen){
public void addListener(PingListener listen) {
this.listen = listen;
}
public void run() {
while(true) {
while (true) {
try {
String apiResponse = "";
try {
apiResponse = APICommandes.getMethod(url + "/api");
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
Request request = new Request.Builder()
.url(url + "/api")
.method("GET", null)
.build();
Response response = client.newCall(request).execute();
apiResponse = response.body().toString();
} catch (IOException e) {
e.printStackTrace();
@ -42,12 +53,12 @@ public class ThreadPing extends Thread {
// Si PING OK declenche l'event ping(isReachable)
isReachable = true;
if(listen != null) listen.ping(isReachable);
if (listen != null) listen.ping(isReachable);
} else {
isReachable = false;
if(listen != null) listen.ping(isReachable);
if (listen != null) listen.ping(isReachable);
}
} catch (Exception e) {

Loading…
Cancel
Save