диплом (1222502), страница 9
Текст из файла (страница 9)
die(json_encode($response));
}
return $prep->fetchColumn();
}
$uID = $prep->fetchColumn();
$query = "select oFCityID,
oFStreetID,
oFHouse,
oFBuilding,
oTCityID,
oTStreetID,
oTHouse,
oTBuilding,
oInsurance,
oSize,
oMass,
oCustom,
oDuty,
oStatID,
oCreationDate
from orders
where oClientID = :uid and oID = :oID;";
$opt = array(":uid" => $uID,
":oID" => $_POST["oID"]);
try{
$prep = $db->prepare($query);
$prep->execute($opt);
}
catch (PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please try again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
$rows = $prep->fetchAll();
if($rows){
$response["success"] = 1;
$response["message"] = "Orders have been found!";
$response["orders"] = array();
foreach ($rows as $row) {
$order = array();
$fcity = findCity($db,$row["oFCityID"]);
$tcity = findCity($db, $row["oTCityID"]);
$fstreet = findStreet($db, $row["oFStreetID"]);
$tstreet = findStreet($db, $row["oTStreetID"]);
$status = findStatus($db, $row["oStatID"]);
$order["oID"] = $_POST["oID"];
$order["oFCity"] = $fcity;
$order["oFStreet"] = $fstreet;
$order["oFHouse"] = $row["oFHouse"];
$order["oFBuilding"] = $row["oFBuilding"];
$order["oTCity"] = $tcity;
$order["oTStreet"] = $tstreet;
$order["oTHouse"] = $row["oTHouse"];
$order["oTBuilding"] = $row["oTBuilding"];
$order["oInsurance"] = $row["oInsurance"];
$order["oSize"] = $row["oSize"];
$order["oMass"] = $row["oMass"];
$order["oCustom"] = $row["oCustom"];
$order["oDuty"] = $row["oDuty"];
$order["oStat"] = $status;
$order["oCreationDate"] = $row["oCreationDate"];
array_push($response["orders"], $order);
}
echo json_encode($response);
}
else {
$response["success"] = 0;
$response["message"] = "No orders available.";
die(json_encode($response));
}
}
}
else {
$response["success"] = 0;
$response["message"] = "Please login.";
die(json_encode($response));
}
Листинг Б.3 – Обновление почтовых данных пользователя
<?php
require("dbConfig.php");
if(!empty($_POST['username'])){
$query = "select uCustomerID from users where uLogin = :username;";
$opt = array(':username' => $_POST['username']);
try{
$prep = $db->prepare($query);
$prep->execute($opt);
}
catch (PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please try again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
$cID = $prep->fetchColumn();
$query = "select ctID from city where ctCityName = :city;";
$opt = array(':city' => $_POST['city']);
try{
$prep = $db->prepare($query);
$result = $prep->execute($opt);
}
catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please Try Again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
$row = $prep->fetch();
if(!$row){
$query = "insert into city (ctCityName) values (:city);";
try{
$prep = $db->prepare($query);
$result = $prep->execute($opt);
}
catch (PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please Try Again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
}
$query = "select ctID from city where ctCityName = :city;";
$opt = array(':city' => $_POST['city']);
try{
$prep = $db->prepare($query);
$result = $prep->execute($opt);
}
catch(PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please Try Again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
//save city ID for the further usage
$city = $prep->fetchColumn();
$query =
"update customers set cPostCityID = :city,
cPostCode = :code,
cPOB = :pob,
where cID = :cid;";
$opt = array(':city' => $city,
':code' => $_POST['code'],
':pob' => $_POST['pob'],
':cid' => $cID);
try{
$prep = $db->prepare($query);
$prep->execute($opt);
}
catch (PDOException $ex){
$response["success"] = 0;
$response["message"] = "Database Error! Please try again.";
$response["error"] = $ex->getMessage();
die(json_encode($response));
}
$response["success"] = 1;
$response["message"] = "Почтовый адрес был обновлен.";
}
else {
$response["success"] = 0;
$response["message"] = "Пожалуйста, войдите в систему";
die(json_encode($response));
}
Приложение В
(рекомендуемое)
Реализация приложения
Листинг В.1 – Генератор хэша
package com.example.acid.continent;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Base64;
import android.util.Log;
public class HashGenerator {
private String SHAHash;
private static String toHex(byte[] data) throws java.io.IOException{
StringBuffer sb = new StringBuffer();
String hex = null;
hex = Base64.encodeToString(data, 0, data.length, Base64.DEFAULT);
sb.append(hex);
return sb.toString();
}
public String getShaHash(String password){
MessageDigest sha1 = null;
try{
sha1 = MessageDigest.getInstance("SHA-1");
}
catch (NoSuchAlgorithmException ex){
Log.e("hash","Can't initialize SHA-1 message digest.");
}
try {
sha1.update(password.getBytes("ASCII"));
}
catch (UnsupportedEncodingException ex){
ex.printStackTrace();
}
byte[] data = sha1.digest();
try{
SHAHash = toHex(data);
}
catch (IOException ex){
ex.printStackTrace();
}
return SHAHash.toString();
}
}
Листинг В.2 – Менеджер сессии пользователя
package com.example.acid.continent;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class SessionManager {
SharedPreferences preference;
Editor editor;
Context context;
int mode = 0;
private static final String prfName = "Login";
private static final String isLogged = "IsLoggedIn";
static final String pass = "password";
static final String login = "username";
public SessionManager(Context _context){
this.context = _context;
preference = context.getSharedPreferences(prfName, mode);
editor = preference.edit();
}
public void initializeSession(String _username, String _password){
editor.putBoolean(isLogged, true);
editor.putString(login, _username);
editor.putString(pass,_password);
editor.commit();
}
public boolean isLoggedIn(){
return preference.getBoolean(isLogged,false);
}
public void checkLogin(){
if(!this.isLoggedIn()){
Intent intent = new Intent(context, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
public void logOut(){
editor.clear();
editor.commit();
Intent intent = new Intent(context, Login.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
public void updateLoginData(String _password){
editor.remove(pass);
editor.putString(pass,_password);
editor.commit();
}
public HashMap<String,String> getSessionData(){
HashMap<String,String> userData = new HashMap<String,String>();
userData.put(login,preference.getString(login,null));
userData.put(pass,preference.getString(pass,null));
return userData;
}
}
Листинг В.3 – Запрос данных с сервера
package com.example.acid.continent;
import android.util.Log;
import org.json.JSONObject;
import org.json.JSONException;
import java.io.DataOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONRequest {
private static final String charset = "UTF-8";
private HttpURLConnection connect;
private DataOutputStream doStream;
private StringBuilder res;
private URL urlObject;
private JSONObject jsonObject;
private StringBuilder parameters;
private String prmString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String,String> param){
parameters = new StringBuilder();
int i = 0;
for(String key : param.keySet()){
try{
if(i!=0){
parameters.append("&");
}
parameters.append(key).append("=")
.append(URLEncoder.encode(param.get(key),charset));
}
catch (UnsupportedEncodingException ex){
ex.printStackTrace();
}
i++;
}
if(method.equals("POST")){
try{
urlObject = new URL(url);
connect = (HttpURLConnection)urlObject.openConnection();
connect.setDoOutput(true);
connect.setRequestMethod("POST");
connect.setRequestProperty("Accept-Charset",charset);
connect.setReadTimeout(10000);
connect.setConnectTimeout(15000);
connect.connect();
prmString = parameters.toString();
doStream = new DataOutputStream(connect.getOutputStream());
doStream.writeBytes(prmString);
doStream.flush();
doStream.close();
}
catch (IOException ex){
ex.printStackTrace();
}
}
else if(method.equals("GET")){
if(parameters.length() !=0){
url += "?" + parameters.toString();
}
try {
urlObject = new URL(url);
connect = (HttpURLConnection) urlObject.openConnection();
connect.setDoOutput(false);
connect.setRequestMethod("GET");
connect.setRequestProperty("Accept-Charset",charset);
connect.setConnectTimeout(15000);
connect.connect();
}
catch (IOException ex){
ex.printStackTrace();
}
}
try {
InputStream inStream = new BufferedInputStream(connect.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
res = new StringBuilder();
String str;
while ((str = reader.readLine())!= null){
res.append(str);
}
Log.d("JSON Request","result: " + res.toString());
}
catch (IOException ex){
ex.printStackTrace();
}
connect.disconnect();
try{
jsonObject = new JSONObject(res.toString());
}
catch (JSONException ex){
Log.e("JSON Parser", "Error parsing data " + ex.toString());
}
return jsonObject;
}
}