Changeset d55ec21 for src/webservice
- Timestamp:
- Sep 1, 2015, 4:45:03 PM (11 years ago)
- Branches:
- master
- Children:
- 256102b
- Parents:
- 02fbeb8
- Location:
- src/webservice
- Files:
-
- 3 added
- 5 edited
-
CMakeLists.txt (modified) (1 diff)
-
htdocs/SiWeather/Webservice/DatabaseHandler.php (modified) (2 diffs)
-
htdocs/SiWeather/Webservice/WebserviceApi.php (added)
-
htdocs/index.php (modified) (2 diffs)
-
tests/SetupTest.php (modified) (5 diffs)
-
tests/StationsTest.php (modified) (7 diffs)
-
tests/TestHelpers/TestSetup.php (added)
-
tests/bootstrap.php (added)
Legend:
- Unmodified
- Added
- Removed
-
src/webservice/CMakeLists.txt
r02fbeb8 rd55ec21 20 20 ###################### 21 21 22 SET(WEBSERVICE_OUTPUT_DIRECTORY "${WEB_OUTPUT_DIRECTORY}/webservice")23 22 SET(WEBSERVICE_OUTPUT_APP_DIRECTORY "${WEBSERVICE_OUTPUT_DIRECTORY}/${WEBSERVICE_API_VERSION}") 24 SET(WEBSERVICE_TEST_OUTPUT_DIRECTORY "${WEB_TEST_OUTPUT_DIRECTORY}/webservice")25 23 26 24 # switch Slim mode according to CMake debug mode -
src/webservice/htdocs/SiWeather/Webservice/DatabaseHandler.php
r02fbeb8 rd55ec21 147 147 public function versionSpatialite(){ 148 148 if(is_null($this->_database)){ 149 $this->setLastErrorMessage(" Unknown (No database connection)");149 $this->setLastErrorMessage("No database connection"); 150 150 return 0; 151 151 } … … 162 162 public function versionSqlite(){ 163 163 if(is_null($this->_database)){ 164 $this->setLastErrorMessage(" Unknown (No database connection)");164 $this->setLastErrorMessage("No database connection"); 165 165 return 0; 166 166 } -
src/webservice/htdocs/index.php
r02fbeb8 rd55ec21 22 22 23 23 $settings = new SiWeather\Webservice\WebserviceConfig(); 24 25 /**26 * @brief Handles the stations (list) REST requests27 */28 function stations(){29 $stations = Array();30 31 $db = new SiWeather\Webservice\DatabaseHandler();32 if(!$db->connect()){33 echo json_encode34 (35 [36 "result" => "failed",37 "message" => "Could not connect to the database",38 ]39 );40 return;41 }42 $db->exec("BEGIN");43 44 $sqlStatement = $db->prepare("SELECT stations.uuid as uuid, stations.name as name, X(stations.location) as longitude, Y(stations.location) as latitude, cities.name as city FROM stations, cities WHERE stations.city=cities.id");45 if(!$sqlStatement){46 $db->exec("ROLLBACK");47 echo json_encode48 (49 [50 "result" => "failed",51 "message" => "Could not fetch stations from database",52 ]53 );54 return;55 }56 $result = $sqlStatement->execute();57 while($row = $result->fetchArray()){58 $station = Array();59 $station["uuid"] = $row["uuid"];60 $station["name"] = $row["name"];61 $station["longitude"] = $row["longitude"];62 $station["latitude"] = $row["latitude"];63 $station["city"] = $row["city"];64 // $station["values"] = Array();65 // $station["values"][] = "temperature";66 // $station["values"][] = "humidity";67 $station["url"] = "stations/". $station["uuid"];68 $stations[] = $station;69 }70 $db->exec("COMMIT");71 72 echo json_encode($stations);73 }74 75 /**76 * @brief Registers a new weather station77 *78 * @note Call this function with a big timeout > 2seconds, because we use another webservice79 * to fetch location data. This fetch runs already 2seconds.80 * @note Requires php-pecl-uuid81 */82 function stationsRegister(){83 $geoLocationRadius = 5;84 85 try{86 $app = \Slim\Slim::getInstance("siweather");87 $body = $app->request->getBody();88 $json = json_decode($body, true);89 90 $app->response()->header("Content-Type", "application/json");91 92 $expectedKeys = array("name", "city", "longitude", "latitude", "email");93 $missingKeys = array();94 foreach($expectedKeys as $key){95 if(!array_key_exists($key, $json))96 $missingKeys[] = $key;97 }98 if(count($missingKeys) > 0){99 echo json_encode100 (101 [102 "result" => "missingkeys",103 "message" => "Your request misses the following keys: ". implode(", ", $missingKeys),104 ]105 );106 return;107 }108 109 if(!SiWeather\Webservice\Location::ValidLatitude($json["latitude"])){110 echo json_encode111 (112 [113 "result" => "invalid latitude",114 "message" => "Your specified an invalid latitude: ". $json["latitude"],115 ]116 );117 return;118 }119 if(!SiWeather\Webservice\Location::ValidLongitude($json["longitude"])){120 echo json_encode121 (122 [123 "result" => "invalid longitude",124 "message" => "Your specified an invalid longitude: ". $json["longitude"],125 ]126 );127 return;128 }129 if(empty($json["email"]) || !filter_var($json["email"], FILTER_VALIDATE_EMAIL)){130 echo json_encode131 (132 [133 "result" => "invalid email",134 "message" => "Your specified an invalid email address: ". $json["email"],135 ]136 );137 return;138 }139 140 $errorMessage = "";141 $locations = SiWeather\Webservice\GeoLocator::locations($json["latitude"], $json["longitude"], $geoLocationRadius, $errorMessage);142 if(!$locations || count($locations) < 1){143 error_log($errorMessage);144 echo json_encode145 (146 [147 "result" => "unprovenlocation",148 "message" => "Could not check the city (". $json["city"] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send with help of your city and geo coordinates. Please make sure, your data is correct.",149 ]150 );151 return;152 }153 else{154 $validatedLocation = false;155 foreach($locations as $location){156 if($location->city() == $json["city"]){157 $validatedLocation = $location;158 }159 }160 if(!$validatedLocation){161 $message = "The city (". $json[city] .") and location (". $json["latitude"] .", ". $json["longitude"] .") you send, does not suite with locations we found at your given location (city, latitude, longitude):\n";162 foreach($locations as $location){163 $message .= " ". $location->city() .": ". $location->latitude() .", ". $location->longitude() ."\n";164 }165 $message .= " Please make sure, your data is correct.";166 167 echo json_encode168 (169 [170 "result" => "unprovenlocation",171 "message" => $message,172 ]173 );174 return;175 }176 }177 178 $db = new SiWeather\Webservice\DatabaseHandler();179 if(!$db->connect()){180 echo json_encode181 (182 [183 "result" => "failed",184 "message" => "Could not connect to the database",185 ]186 );187 return;188 }189 $db->exec("BEGIN");190 191 // find out, if the city is already there192 $cityId = -1;193 $sqlStatement = $db->prepare("SELECT id FROM cities WHERE name=:name AND location=:location");194 if(!$sqlStatement){195 $db->exec("ROLLBACK");196 echo json_encode197 (198 [199 "result" => "failed",200 "message" => "Could not fetch city from database",201 ]202 );203 return;204 }205 $sqlStatement->bindValue(":name", $validatedLocation->city());206 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");207 $result = $sqlStatement->execute();208 if($result->numColumns() && $result->columnType(0) != SQLITE3_NULL){209 error_log("not cool");210 $row = $result->fetchArray();211 $cityId = $row[0];212 error_log($row[0]);213 }214 else{215 $sqlStatement = $db->prepare("INSERT INTO cities (name, location) VALUES(:name, GeomFromText(:location, 4326))");216 if(!$sqlStatement){217 $db->exec("ROLLBACK");218 echo json_encode219 (220 [221 "result" => "failed",222 "message" => "Could insert city into the database",223 ]224 );225 return;226 }227 $sqlStatement->bindValue(":name", $validatedLocation->city());228 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");229 $sqlResult = $sqlStatement->execute();230 if(!$sqlResult){231 error_log("Failed to add city to the database: ". $db->lastDatabaseErrorMessage());232 $db->exec("ROLLBACK");233 echo json_encode234 (235 [236 "result" => "failed",237 "message" => "Could not add city to the database",238 ]239 );240 return;241 }242 $cityId = $db->lastInsertRowId();243 }244 if($cityId < 0){245 error_log("Failed to select city from the database: ". $db->lastDatabaseErrorMessage());246 $db->exec("ROLLBACK");247 echo json_encode248 (249 [250 "result" => "failed",251 "message" => "Could not select city from the database",252 ]253 );254 return;255 }256 257 // insert station258 $uuid = uuid_create(4);259 $sqlStatement = $db->prepare("INSERT INTO stations (name, city, uuid, ownerMail, location) VALUES(:name, :city, :uuid, :ownerMail, GeomFromText(:location, 4326))");260 if(!$sqlStatement){261 $db->exec("ROLLBACK");262 echo json_encode263 (264 [265 "result" => "failed",266 "message" => "Could insert station into the database",267 ]268 );269 return;270 }271 $sqlStatement->bindValue(":name", $json["name"]);272 $sqlStatement->bindValue(":city", $cityId);273 $sqlStatement->bindValue(":uuid", $uuid);274 $sqlStatement->bindValue(":ownerMail",$json["email"]);275 $sqlStatement->bindValue(":location", "POINT(". $location->locationWkt() .")");276 $sqlResult = $sqlStatement->execute();277 if(!$sqlResult){278 error_log("Failed to add station to the database: ". $db->lastDatabaseErrorMessage());279 $db->query("ROLLBACK");280 echo json_encode281 (282 [283 "result" => "failed",284 "message" => "Could not add station to the database",285 ]286 );287 return;288 }289 290 // finish transaction291 $db->exec("COMMIT");292 293 echo json_encode294 (295 [296 "result" => "success",297 "uuid" => $uuid,298 ]299 );300 }301 catch(Exception $exception){302 error_log("Caught exception handling request stationsRegister: ". $exception->getMessage());303 $app->response()->status(400);304 $app->response()->header("X-Status-Reason", $exception->getMessage());305 }306 }307 24 308 25 $app = new \Slim\Slim … … 346 63 $app->render("setup.php"); 347 64 }); 348 349 $app->get("/stations", "stations"); 350 $app->post("/stations/register", "stationsRegister"); 65 $app->get("/stations", function () use ($app){ 66 \SiWeather\Webservice\WebserviceApi::stations(); 67 }); 68 $app->post("/stations/register", function () use ($app){ 69 \SiWeather\Webservice\WebserviceApi::stationsRegister(); 70 }); 351 71 352 72 $app->run(); -
src/webservice/tests/SetupTest.php
r02fbeb8 rd55ec21 19 19 */ 20 20 21 require_once(__DIR__ ."/TestHelpers/TestSetup.php"); 22 21 23 class SetupTest extends PHPUnit_Framework_TestCase 22 24 { … … 31 33 32 34 require_once($testconfig["webserviceDirectory"] ."/inc/envsetup.php"); 33 35 34 36 self::$_webserviceConfig = new SiWeather\Webservice\WebserviceConfig(); 35 37 self::assertNotNull(self::$_webserviceConfig); … … 38 40 self::assertInternaltype("string", self::$_dataDirectory); 39 41 self::assertTrue(!empty(self::$_dataDirectory)); 42 if(file_exists(self::$_dataDirectory)) 43 self::assertTrue(TestHelpers\TestSetup::wipeDataDirectory()); 44 40 45 self::assertTrue(!file_exists(self::$_dataDirectory)); 41 46 } … … 43 48 public static function tearDownAfterClass() 44 49 { 45 if(!file_exists(self::$_dataDirectory)){ 46 return; 47 } 48 // clear data directory (not recursive, because there should be only a database file in it 49 $content = scandir(self::$_dataDirectory); 50 self::assertInternalType("array", $content); 51 foreach($content as $file){ 52 if(!in_array($file, array(".",".."))){ 53 self::assertTrue(unlink(self::$_dataDirectory ."/". $file)); 54 } 55 } 56 57 // remove datadirectory 58 self::assertTrue(rmdir(self::$_dataDirectory)); 50 if(file_exists(self::$_dataDirectory)) 51 self::assertTrue(TestHelpers\TestSetup::wipeDataDirectory()); 59 52 } 60 53 … … 163 156 $this->assertLessThan($versionSpatalite, 0, $prefix ." (Could not determine Spatalite version: ". $errorMessage .")"); 164 157 $this->assertTrue(empty($errorMessage), "Error message \"". $errorMessage ."\" is not empty"); 165 }158 } 166 159 167 protected static $_webserviceConfig;168 protected static $_dataDirectory;169 protected static $_testconfig;160 protected static $_webserviceConfig; 161 protected static $_dataDirectory; 162 protected static $_testconfig; 170 163 } 171 164 ?> -
src/webservice/tests/StationsTest.php
r02fbeb8 rd55ec21 19 19 */ 20 20 21 /** 22 * @todo Reset database before this test is run 23 */ 21 require_once(__DIR__ ."/TestHelpers/TestSetup.php"); 22 24 23 class StationsTest extends PHPUnit_Framework_TestCase 25 24 { … … 37 36 $this->_webserviceConfig = new SiWeather\Webservice\WebserviceConfig(); 38 37 $this->assertNotNull($this->_webserviceConfig); 38 39 $this->_dataDirectory = $this->_webserviceConfig->getConfig("dataDirectory"); 40 $this->assertInternaltype("string", $this->_dataDirectory); 41 $this->assertTrue(!empty($this->_dataDirectory)); 42 if(file_exists($this->_dataDirectory)) 43 $this->assertTrue(TestHelpers\TestSetup::wipeDataDirectory()); 44 $this->assertTrue(TestHelpers\TestSetup::databaseSetup()); 45 } 46 47 protected function tearDown(){ 48 if(file_exists($this->_dataDirectory)) 49 $this->assertTrue(TestHelpers\TestSetup::wipeDataDirectory()); 39 50 } 40 51 … … 44 55 45 56 $this->assertInternalType("array", $stations); 57 $message = ""; 58 if(array_key_exists("message", $stations)) 59 $message = $stations["message"]; 60 $this->assertTrue(!array_key_exists("result", $stations), $message); 46 61 $this->assertEquals(count($stations), 0); 47 62 } 48 49 public function testStationRewrite()50 {51 $stations = $this->query("stations");52 63 53 $this->assertInternalType("array", $stations);54 $this->assertEquals(count($stations), 0);55 }56 57 64 public function testRegisterStationUnprovenLocation() 58 65 { 59 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();66 $baseUrl = TestHelpers\TestSetup::webserviceTestBaseUrl(); 60 67 $this->assertInternalType('string', $baseUrl, "baseUrl is not of type string: ". $baseUrl); 61 68 $this->assertTrue(!empty($baseUrl), "baseUrl is empty: ". $baseUrl); … … 82 89 public function testRegisterStation() 83 90 { 84 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();91 $baseUrl = TestHelpers\TestSetup::webserviceTestBaseUrl(); 85 92 $this->assertInternalType('string', $baseUrl, "baseUrl is not of type string: ". $baseUrl); 86 93 $this->assertTrue(!empty($baseUrl), "baseUrl is empty: ". $baseUrl); … … 94 101 ); 95 102 96 // sending must failing register request, caused by unproven location97 103 $response = $client->post("index.php/stations/register", 98 104 [ "json" => ["name" => "My Weather Station", "city" => "Clausthal-Zellerfeld", "longitude" => 10.28152, "latitude" => 51.8281, "email" => "test@example.org"]] … … 113 119 114 120 protected function query($url){ 115 $baseUrl = $this->_webserviceConfig->webserviceBaseUrl();121 $baseUrl = TestHelpers\TestSetup::webserviceTestBaseUrl(); 116 122 $this->assertInternalType('string', $baseUrl, "baseUrl is not of type string: ". $baseUrl); 117 123 $this->assertTrue(!empty($baseUrl), "baseUrl is empty: ". $baseUrl); … … 138 144 protected $_testconfig; 139 145 protected $_webserviceConfig; 146 protected $_dataDirectory; 140 147 } 141 148 ?>
Note:
See TracChangeset
for help on using the changeset viewer.
![(please configure the [header_logo] section in trac.ini)](/siweather/chrome/site/your_project_logo.png)