Contournement du bug mystère au niveau du réseau (à la fac).

This commit is contained in:
Georges Dupéron 2011-03-09 11:51:29 +01:00
parent 2b20c3bc51
commit badb971fb4
2 changed files with 147 additions and 66 deletions

View File

@ -0,0 +1,99 @@
package org.pticlic.model;
/***
Copyright (c) 2009
Author: Stefan Klumpp <stefan.klumpp@gmail.com>
Web: http://stefanklumpp.com
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.GZIPInputStream;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.util.Log;
public class HttpClient {
private static final String TAG = "HttpClient";
public static String SendHttpPost(String URL) {
try {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpPostRequest = new HttpGet(URL);
//StringEntity se;
//se = new StringEntity(str);
// Set HTTP parameters
//httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression
long t = System.currentTimeMillis();
HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
// Get hold of the response entity (-> the data):
HttpEntity entity = response.getEntity();
if (entity != null) {
// Read the content stream
InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}
// convert content stream to a String
BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
instream.close();
instream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
} else {
return null;
}
}
catch (Exception e)
{
// More about HTTP exception handling in another tutorial.
// For now we just print the stack trace.
e.printStackTrace();
return null;
}
}
}

View File

@ -7,7 +7,6 @@ import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.io.Serializable; import java.io.Serializable;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import org.pticlic.exception.PtiClicException; import org.pticlic.exception.PtiClicException;
@ -30,22 +29,22 @@ import com.google.gson.stream.JsonReader;
* puisse insérer la contribution de l'utilisateur, mais aussi pouvoir calculer le score de celui-ci. * puisse insérer la contribution de l'utilisateur, mais aussi pouvoir calculer le score de celui-ci.
*/ */
public class Network { public class Network {
public static class Check implements Serializable { public static class Check implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private boolean login_ok = false; private boolean login_ok = false;
public boolean isLogin_ok() { public boolean isLogin_ok() {
return login_ok; return login_ok;
} }
public void setLogin_ok(boolean login_ok) { public void setLogin_ok(boolean login_ok) {
this.login_ok = login_ok; this.login_ok = login_ok;
} }
} }
String newGameJson = null; String newGameJson = null;
public enum Action { public enum Action {
GET_GAMES(0), GET_GAMES(0),
SEND_GAME(1), SEND_GAME(1),
@ -117,35 +116,26 @@ public class Network {
* @return <code>true</code> si la combinaison login/mdp est correct <code>false</code> sinon * @return <code>true</code> si la combinaison login/mdp est correct <code>false</code> sinon
*/ */
public static boolean isLoginCorrect(Context context) { public static boolean isLoginCorrect(Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
String serverURL = sp.getString(Constant.SERVER_URL, Constant.SERVER) + "/server.php"; String serverURL = sp.getString(Constant.SERVER_URL, Constant.SERVER) + "/server.php";
String id = sp.getString(Constant.USER_ID, "joueur"); String id = sp.getString(Constant.USER_ID, "joueur");
String passwd = sp.getString(Constant.USER_PASSWD, ""); String passwd = sp.getString(Constant.USER_PASSWD, "");
URL url = null;
Gson gson = null; Gson gson = null;
BufferedReader reader = null;
String json = null; String json = null;
boolean res = false; boolean res = false;
try {
String urlS = serverURL String urlS = serverURL
+ "action=" + Action.CHECK_LOGIN.value() + "?action=" + Action.CHECK_LOGIN.value()
+ "&user=" + id + "&user=" + id
+ "&passwd=" + passwd; + "&passwd=" + passwd;
url = new URL(urlS); gson = new Gson();
gson = new Gson(); json = HttpClient.SendHttpPost(urlS);
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
json = reader.readLine();
Check check = gson.fromJson(json, Check.class); Check check = gson.fromJson(json, Check.class);
res = check.isLogin_ok(); res = check.isLogin_ok();
} catch (MalformedURLException e) {
return false;
} catch (IOException e) {
return false;
}
return res; return res;
} }
@ -165,32 +155,29 @@ public class Network {
} }
private DownloadedBaseGame DownloadBaseGame(int nbGames) throws PtiClicException, Exception { private DownloadedBaseGame DownloadBaseGame(int nbGames) throws PtiClicException, Exception {
DownloadedBaseGame game = null;
URL url = null;
Gson gson = null; Gson gson = null;
BufferedReader reader = null;
String json = null; String json = null;
try { DownloadedBaseGame game = null;
// TODO : ne restera le temps que les requete du serveur passe du GET au POST
String urlS = this.serverURL // URLConnection connection = url.openConnection();
+ "action=" + Action.GET_GAMES.value() // connection.addRequestProperty("action", Action.GET_GAMES.value());
// connection.addRequestProperty("user", this.id);
// connection.addRequestProperty("passwd", this.passwd);
// connection.addRequestProperty("nb", String.valueOf(nbGames));
// connection.addRequestProperty("mode", mode.value());
String urlS = this.serverURL
+ "?action=" + Action.GET_GAMES.value()
+ "&user=" + this.id + "&user=" + this.id
+ "&passwd=" + this.passwd + "&passwd=" + this.passwd
+ "&nb=" + String.valueOf(nbGames) + "&nb=" + String.valueOf(nbGames)
+ "&mode="+mode.value(); + "&mode="+mode.value();
url = new URL(urlS); gson = new Gson();
json = HttpClient.SendHttpPost(urlS);
try {
// URLConnection connection = url.openConnection();
// connection.addRequestProperty("action", Action.GET_GAMES.value());
// connection.addRequestProperty("user", this.id);
// connection.addRequestProperty("passwd", this.passwd);
// connection.addRequestProperty("nb", String.valueOf(nbGames));
// connection.addRequestProperty("mode", mode.value());
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
json = reader.readLine();
gson = new Gson();
//JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
InputStream in = new ByteArrayInputStream(json.getBytes("UTF-8")); InputStream in = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jsonReader = new JsonReader(new InputStreamReader(in)); JsonReader jsonReader = new JsonReader(new InputStreamReader(in));
@ -260,7 +247,7 @@ public class Network {
reader.endObject(); reader.endObject();
return new DownloadedBaseGame(id, gid, pgid, cat1, cat2, cat3, cat4, center, cloud); return new DownloadedBaseGame(id, gid, pgid, cat1, cat2, cat3, cat4, center, cloud);
} }
/** /**
* Cette méthode permet d'envoyer les parties au serveur pour qu'il puisse les * Cette méthode permet d'envoyer les parties au serveur pour qu'il puisse les
* rajouter à la base de données, et calculer le score. * rajouter à la base de données, et calculer le score.
@ -275,25 +262,23 @@ public class Network {
return -1; return -1;
} }
} }
public double sendBaseGame(Match game) throws PtiClicException, Exception { public double sendBaseGame(Match game) throws PtiClicException, Exception {
double score = -1; double score = -1;
URL url = null;
Gson gson = null; Gson gson = null;
BufferedReader reader = null;
String json = null; String json = null;
try { try {
// TODO : ne restera le temps que les requete du serveur passe du GET au POST // TODO : ne restera le temps que les requete du serveur passe du GET au POST
String urlS = this.serverURL String urlS = this.serverURL
+ "action=" + Action.SEND_GAME.value() + "?action=" + Action.SEND_GAME.value()
+ "&user=" + this.id + "&user=" + this.id
+ "&passwd=" + this.passwd + "&passwd=" + this.passwd
+ "&pgid=" + game.getGame().getPgid() + "&pgid=" + game.getGame().getPgid()
+ "&gid=" + game.getGame().getGid() + "&gid=" + game.getGame().getGid()
+ "&mode="+mode.value(); + "&mode="+mode.value();
// TODO : faut gere le mode // TODO : faut gere le mode
for (Integer i : game.getRelation1()) { for (Integer i : game.getRelation1()) {
urlS += "&" + i + "=" + ((DownloadedBaseGame)game.getGame()).getCat1() ; urlS += "&" + i + "=" + ((DownloadedBaseGame)game.getGame()).getCat1() ;
@ -307,21 +292,18 @@ public class Network {
for (Integer i : game.getRelation4()) { for (Integer i : game.getRelation4()) {
urlS += "&" + i + "=" + ((DownloadedBaseGame)game.getGame()).getCat4(); urlS += "&" + i + "=" + ((DownloadedBaseGame)game.getGame()).getCat4();
} }
url = new URL(urlS);
// URL url = new URL(this.serverURL); // Attention ! this.serverURL contient "/server.php" // URL url = new URL(this.serverURL); // Attention ! this.serverURL contient "/server.php"
// URLConnection connection = url.openConnection(); // URLConnection connection = url.openConnection();
// connection.addRequestProperty("action", Action.SEND_GAME.value()); // connection.addRequestProperty("action", Action.SEND_GAME.value());
// connection.addRequestProperty("user", this.id); // connection.addRequestProperty("user", this.id);
// connection.addRequestProperty("passwd", this.passwd); // connection.addRequestProperty("passwd", this.passwd);
// connection.addRequestProperty("mode", mode.value()); // connection.addRequestProperty("mode", mode.value());
// connection.addRequestProperty("pgid", String.valueOf(game.getGame().getId())); // connection.addRequestProperty("pgid", String.valueOf(game.getGame().getId()));
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
json = reader.readLine();
gson = new Gson(); gson = new Gson();
json = HttpClient.SendHttpPost(urlS);
//JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); //JsonReader reader = new JsonReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
InputStream in = new ByteArrayInputStream(json.getBytes("UTF-8")); InputStream in = new ByteArrayInputStream(json.getBytes("UTF-8"));
JsonReader jsonReader = new JsonReader(new InputStreamReader(in)); JsonReader jsonReader = new JsonReader(new InputStreamReader(in));
@ -341,13 +323,13 @@ public class Network {
} catch (IOException e1) { } catch (IOException e1) {
throw new PtiClicException(0, "Impossible de recuperer l'erreur, nous avons pris note de cette erreur.\n Merci"); throw new PtiClicException(0, "Impossible de recuperer l'erreur, nous avons pris note de cette erreur.\n Merci");
} }
return score; return score;
} }
private double getScore(JsonReader reader, Gson gson) throws IOException { private double getScore(JsonReader reader, Gson gson) throws IOException {
double score = -1; double score = -1;
reader.beginObject(); reader.beginObject();
while (reader.hasNext()) { while (reader.hasNext()) {
String name = reader.nextName(); String name = reader.nextName();
@ -363,7 +345,7 @@ public class Network {
reader.endObject(); reader.endObject();
return score; return score;
} }
public String getNewGame() { public String getNewGame() {
return this.newGameJson; return this.newGameJson;
} }