Author: chabotc
Date: Sat Aug  9 10:10:21 2008
New Revision: 684297

URL: http://svn.apache.org/viewvc?rev=684297&view=rev
Log:
SHINDIG-496 by Gonzalo Aune: PHP handler for canonical json db

Added:
    incubator/shindig/trunk/php/src/social-api/canonical/
    
incubator/shindig/trunk/php/src/social-api/canonical/JsonDbOpensocialService.php
    incubator/shindig/trunk/php/test/social-api/JsonDbOpensocialServiceTest.php
Modified:
    incubator/shindig/trunk/javascript/sampledata/canonicaldb.json
    incubator/shindig/trunk/php/config/container.php
    incubator/shindig/trunk/php/src/social-api/dataservice/ActivitiesService.php
    incubator/shindig/trunk/php/src/social-api/dataservice/AppDataService.php
    incubator/shindig/trunk/php/src/social-api/dataservice/MessagesService.php
    incubator/shindig/trunk/php/src/social-api/dataservice/PeopleService.php
    incubator/shindig/trunk/php/src/social-api/dataservice/RestRequestItem.php
    incubator/shindig/trunk/php/src/social-api/http/RestServlet.php
    
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicActivitiesService.php
    
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicAppDataService.php
    
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicMessagesService.php
    
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicPeopleService.php
    incubator/shindig/trunk/php/test/ShindigAllTests.php
    incubator/shindig/trunk/php/test/index.php

Modified: incubator/shindig/trunk/javascript/sampledata/canonicaldb.json
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/javascript/sampledata/canonicaldb.json?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/javascript/sampledata/canonicaldb.json (original)
+++ incubator/shindig/trunk/javascript/sampledata/canonicaldb.json Sat Aug  9 
10:10:21 2008
@@ -1,5 +1,6 @@
+
 //  WARNING! Changing this file will affect unit-tests
-//  A canonical JSON backed DB of OpenSocial datastrcutres in their RESTful 
forms
+//  A canonical JSON backed DB of OpenSocial datastructures in their RESTful 
forms
 //
 //  Basic structure:
 //  { people : Array<Person>,
@@ -66,7 +67,7 @@
     "food" : ["sushi","burgers"],
     "gender" : {
       "key" : "MALE",
-      "displayvalue" : "Male"
+      "displayValue" : "Male"
     },
     "happiestWhen" : "coding",
     "hasApp" : true,
@@ -147,7 +148,7 @@
     "scaredOf" : "COBOL",
     "schools" : [{
       "address" : {
-        "unstructuredAddress" : "1 Edu St.",
+        "unstructuredAddress" : "1 Edu St."
       },
       "description" : "High School",
       "endDate" : "1991-01-01",
@@ -186,7 +187,7 @@
     "id" : "john.doe",
     "gender" : {
       "key" : "MALE",
-      "displayvalue" : "Male"
+      "displayValue" : "Male"
     },
     "hasApp" : true,
     "name" : {
@@ -199,7 +200,7 @@
     "id" : "jane.doe",
     "gender" : {
       "key" : "FEMALE",
-      "displayvalue" : "Female"
+      "displayValue" : "Female"
     },
     "hasApp" : true,
     "name" : {
@@ -212,7 +213,7 @@
     "id" : "george.doe",
     "gender" : {
       "key" : "MALE",
-      "displayvalue" : "Female"
+      "displayValue" : "Female"
     },
     "hasApp" : true,
     "name" : {
@@ -225,7 +226,7 @@
     "id" : "mario.rossi",
     "gender" : {
       "key" : "MALE",
-      "displayvalue" : "Male"
+      "displayValue" : "Male"
     },
     "hasApp" : true,
     "name" : {
@@ -238,7 +239,7 @@
     "id" : "maija.m",
     "gender" : {
       "key" : "FEMALE",
-      "displayvalue" : "Female"
+      "displayValue" : "Female"
     },
     "hasApp" : true,
     "name" : {
@@ -322,7 +323,7 @@
       "id" : "1",
       "userId" : "john.doe",
       "title" : "yellow",
-      "body" : "what a color!",
+      "body" : "what a color!"
     }],
     "jane.doe" : [{
       "id" : "1",

Modified: incubator/shindig/trunk/php/config/container.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/config/container.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/config/container.php (original)
+++ incubator/shindig/trunk/php/config/container.php Sat Aug  9 10:10:21 2008
@@ -72,7 +72,8 @@
        // The OAuth SSL certificates to use, and the pass phrase for the 
private key  
        'private_key_file' => realpath(dirname(__FILE__) . 
'/../certs').'/private.key', 
        'public_key_file' => realpath(dirname(__FILE__) . 
'/../certs').'/public.crt', 
-       'private_key_phrase' => 'partuza', 
+       'private_key_phrase' => 'partuza', 
+       'jsondb_path' => realpath(dirname(__FILE__) . 
'/../../javascript/sampledata').'/canonicaldb.json',
 
        // Force these libraries to be external (included through <script 
src="..."> tags), this way they could be cached by the browser
        'focedJsLibs' => '', 
@@ -87,10 +88,10 @@
        // Old-style wire format data handler, this is being depreciated 
        'handlers' => '',
        // New RESTful API data service classes to use
-       'people_service' => 'BasicPeopleService',
-       'activity_service' => 'BasicActivitiesService',
-       'app_data_service' => 'BasicAppDataService',
-       'messages_service' => 'BasicMessagesService',
+       'people_service' => 'JsonDbOpensocialService',
+       'activity_service' => 'JsonDbOpensocialService',
+       'app_data_service' => 'JsonDbOpensocialService',
+       'messages_service' => 'JsonDbOpensocialService',
        // Also scan these directories when looking for <Class>.php files. You 
can include multiple paths by seperating them with a , 
        'extension_class_paths' => '',
        

Added: 
incubator/shindig/trunk/php/src/social-api/canonical/JsonDbOpensocialService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/canonical/JsonDbOpensocialService.php?rev=684297&view=auto
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/canonical/JsonDbOpensocialService.php
 (added)
+++ 
incubator/shindig/trunk/php/src/social-api/canonical/JsonDbOpensocialService.php
 Sat Aug  9 10:10:21 2008
@@ -0,0 +1,427 @@
+<?php
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ * Implementation of supported services backed by a JSON DB
+ */
+class JsonDbOpensocialService implements ActivitiesService, PeopleService, 
AppDataService, MessagesService {
+       
+       /**
+        * The DB
+        */
+       private $db;
+       
+       /**
+        * db["activities"] -> Array<Person>
+        */
+       private static $PEOPLE_TABLE = "people";
+       
+       /**
+        * db["people"] -> Map<Person.Id, Array<Activity>>
+        */
+       private static $ACTIVITIES_TABLE = "activities";
+       
+       /**
+        * db["data"] -> Map<Person.Id, Map<String, String>>
+        */
+       private static $DATA_TABLE = "data";
+       
+       /**
+        * db["friendLinks"] -> Map<Person.Id, Array<Person.Id>>
+        */
+       private static $FRIEND_LINK_TABLE = "friendLinks";
+       
+       private $allPeople = null;
+       
+       private $allData = null;
+       
+       private $allActivities = null;
+       
+       private $jsonDbFileName = 'ShindigDb.json';
+
+       public function getDb()
+       {
+               try {
+                       $fileName = sys_get_temp_dir() . '/' . 
$this->jsonDbFileName;
+                       if (file_exists($fileName)) {
+                               if (! is_readable($fileName)) {
+                                       throw new Exception("Could not read 
temp json db file: $fileName, check permissions");
+                               }
+                               $cachedDb = file_get_contents($fileName);
+                               $jsonDecoded = json_decode($cachedDb, true);
+                               if ($jsonDecoded == $cachedDb) {
+                                       throw new Exception("Failed to decode 
the json db");
+                               }
+                               return $jsonDecoded;
+                       } else {
+                               $jsonDb = Config::get('jsondb_path');
+                               if (! file_exists($jsonDb) || ! 
is_readable($jsonDb)) {
+                                       throw new Exception("Could not read 
json db file: $jsonDb, check if the file exists & has proper permissions");
+                               }
+                               $dbConfig = @file_get_contents($jsonDb);
+                               $contents = 
preg_replace('/[^http:\/\/|^https:\/\/]\/\/.*$/m', '', 
preg_replace('@/\\*(?:.|[\\n\\r])*?\\*/@', '', $dbConfig));
+                               $jsonDecoded = json_decode($contents, true);
+                               if ($jsonDecoded == $contents) {
+                                       throw new Exception("Failed to decode 
the json db");
+                               }
+                               $this->saveDb($jsonDecoded);
+                               return $jsonDecoded;
+                       }
+               } catch (Exception $e) {
+                       throw new Exception("An error occured while 
reading/writing the json db: " . $e);
+               }
+       }
+
+       private function saveDb($db)
+       {
+               if (! @file_put_contents(sys_get_temp_dir() . '/' . 
$this->jsonDbFileName, json_encode($db))) {
+                       throw new Exception("Could not save json db: " . 
sys_get_temp_dir() . '/' . $this->jsonDbFileName);
+               }
+       }
+
+       /**
+        * Get the set of user id's from a user and group
+        */
+       private function getIdSet(UserId $user, $group, SecurityToken $token)
+       {
+               $userId = $user->getUserId($token);
+               if ($group == null) {
+                       return array($userId);
+               }
+               $returnVal = array();
+               switch ($group->getType()) {
+                       case 'all':
+                       case 'friends':
+                       case 'groupId':
+                               $db = $this->getDb();
+                               $friendsLinkTable = 
$db[self::$FRIEND_LINK_TABLE];
+                               if (isset($friendsLinkTable[$userId])) {
+                                       $friends = $friendsLinkTable[$userId];
+                                       foreach ($friends as $friend) {
+                                               $returnVal[$friend['id']] = 
$friend;
+                                       }
+                               }
+                               break;
+                       case 'self':
+                               $returnVal[$userId] = $userId;
+                               break;
+               }
+               return $returnVal;
+       }
+
+       private function getAllPeople()
+       {
+               if (is_null($this->allPeople)) {
+                       $db = $this->getDb();
+                       $peopleTable = $db[self::$PEOPLE_TABLE];
+                       foreach ($peopleTable as $people) {
+                               $this->allPeople[$people['id']] = $people;
+                       }
+                       $db[self::$PEOPLE_TABLE] = $this->allPeople;
+               }
+               return $this->allPeople;
+       }
+
+       private function getAllData()
+       {
+               if (is_null($this->allData)) {
+                       $db = $this->getDb();
+                       $dataTable = $db[self::$DATA_TABLE];
+                       foreach ($dataTable as $key => $value) {
+                               $this->allData[$key] = $value;
+                       }
+                       $db[self::$DATA_TABLE] = $this->allData;
+               }
+               return $this->allData;
+       }
+
+       private function getAllActivities()
+       {
+               if (is_null($this->allActivities)) {
+                       $db = $this->getDb();
+                       $activitiesTable = $db[self::$ACTIVITIES_TABLE];
+                       foreach ($activitiesTable as $key => $value) {
+                               $this->allActivities[$key] = $value;
+                       }
+                       $db[self::$ACTIVITIES_TABLE] = $this->allActivities;
+               }
+               return $this->allActivities;
+       }
+
+       private function getPeopleWithApp($appId)
+       {
+               $peopleWithApp = array();
+               $allPeople = $this->getAllPeople();
+               foreach ($allPeople as $people) {
+                       if ($people['hasApp'] == 1) {
+                               $peopleWithApp = $people['id'];
+                       }
+               }
+               return $peopleWithApp;
+       }
+
+       public function getPerson($userId, $groupId, $profileDetails, 
SecurityToken $token)
+       {
+               $person = $this->getPeople($userId, $groupId, null, null, null, 
null, $profileDetails, null, $token);
+               // return of getPeople is a 
ResponseItem(RestfulCollection(ArrayOfPeople)), disassemble to return just one 
person
+               $person = $person->getResponse()->getEntry();
+               if (is_array($person) && count($person) == 1) {
+                       return new ResponseItem(null, null, $person[0]);
+               }
+               return new ResponseItem(NOT_FOUND, "Person not found", null);
+       }
+
+       public function getPeople($userId, $groupId, $sortOrder, $filter, 
$first, $max, $profileDetails, $networkDistance, SecurityToken $token)
+       {
+               $db = $this->getDb();
+               $friendsTable = $db[self::$FRIEND_LINK_TABLE];
+               $ids = array();
+               $group = is_object($groupId) ? $groupId->getType() : '';
+               switch ($group) {
+                       case 'all':
+                       case 'friends':
+                               if (is_array($friendsTable) && 
count($friendsTable) && isset($friendsTable[$userId->getUserId($token)])) {
+                                       $ids = 
$friendsTable[$userId->getUserId($token)];
+                               }
+                               break;
+                       case 'self':
+                       default:
+                               $ids[] = $userId->getUserId($token);
+                               break;
+               }
+               $allPeople = $this->getAllPeople();
+               if (! $token->isAnonymous() && $filter == "hasApp") {
+                       $appId = $token->getAppId();
+                       $peopleWithApp = $this->getPeopleWithApp($appId);
+               }
+               $people = array();
+               foreach ($ids as $id) {
+                       if ($filter == "hasApp" && ! in_array($id, 
$peopleWithApp)) {
+                               continue;
+                       }
+                       $person = null;
+                       if (is_array($allPeople) && isset($allPeople[$id])) {
+                               $person = $allPeople[$id];
+                               if (! $token->isAnonymous() && $id == 
$token->getViewerId()) {
+                                       $person['isViewer'] = true;
+                               }
+                               if (! $token->isAnonymous() && $id == 
$token->getOwnerId()) {
+                                       $person['isOwner'] = true;
+                               }
+                               if (is_array($profileDetails) && 
count($profileDetails) && ! in_array('all', $profileDetails)) {
+                                       $newPerson = array();
+                                       $newPerson['isOwner'] = 
isset($person['isOwner']) ? $person['isOwner'] : false;
+                                       $newPerson['isViewer'] = 
isset($person['isViewer']) ? $person['isViewer'] : false;
+                                       $newPerson['name'] = $person['name'];
+                                       foreach ($profileDetails as $field) {
+                                               if (isset($person[$field]) && ! 
isset($newPerson[$field])) {
+                                                       $newPerson[$field] = 
$person[$field];
+                                               }
+                                       }
+                                       $person = $newPerson;
+                               }
+                               $people[] = $person;
+                       }
+               }
+               if ($sortOrder == 'name') {
+                       usort($people, array($this, 'comparator'));
+               }
+               //TODO: The samplecontainer doesn't support any filters yet. We 
should fix this.
+               $totalSize = count($people);
+               $last = $first + $max;
+               $last = min($last, $totalSize);
+               if ($first !== false && $first != null && $last) {
+                       $people = array_slice($people, $first, $last);
+               }
+               $collection = new RestfulCollection($people, $first, 
$totalSize);
+               return new ResponseItem(null, null, $collection);
+       }
+
+       public function getPersonData(UserId $userId, GroupId $groupId, 
$fields, $appId, SecurityToken $token)
+       {
+               $db = $this->getDb();
+               $allData = $this->getAllData();
+               $friendsTable = $db[self::$FRIEND_LINK_TABLE];
+               $data = array();
+               $ids = array();
+               switch ($groupId->getType()) {
+                       case 'self':
+                               $ids[] = $userId->getUserId($token);
+                               break;
+                       case 'all':
+                       case 'friends':
+                               if (is_array($friendsTable) && 
count($friendsTable) && isset($friendsTable[$userId->getUserId($token)])) {
+                                       $ids = 
$friendsTable[$userId->getUserId($token)];
+                               }
+                               break;
+                       default:
+                               return new ResponseItem(NOT_IMPLEMENTED, "We 
don't support fetching data in batches yet", null);
+                               break;
+               }
+               foreach ($ids as $id) {
+                       if (isset($allData[$id])) {
+                               $allPersonData = $allData[$id];
+                               $personData = array();
+                               foreach (array_keys($allPersonData) as $key) {
+                                       if (in_array($key, $fields) || 
(isset($fields[0]) && $fields[0] == "*")) {
+                                               $personData[$key] = 
$allPersonData[$key];
+                                       }
+                               }
+                               $data[$id] = $personData;
+                       }
+               }
+               return new ResponseItem(null, null, 
RestFulCollection::createFromEntry($data));
+       }
+
+       public function updatePersonData(UserID $userId, GroupId $groupId, 
$fields, $values, $appId, SecurityToken $token)
+       {
+               $db = $this->getDb();
+               foreach ($fields as $key) {
+                       if (! $this->isValidKey($key)) {
+                               return new ResponseItem(BAD_REQUEST, "The 
person app data key had invalid characters", null);
+                       }
+               }
+               $allData = $this->getAllData();
+               $person = $allData[$userId->getUserId($token)];
+               switch ($groupId->getType()) {
+                       case 'self':
+                               foreach ($fields as $key) {
+                                       $value = isset($values[$key]) ? 
@$values[$key] : null;
+                                       $person[$key] = $value;
+                               }
+                               break;
+                       default:
+                               return new ResponseItem(NOT_IMPLEMENTED, "We 
don't support updating data in batches yet", null);
+                               break;
+               }
+               $allData[$userId->getUserId($token)] = $person;
+               $db[self::$DATA_TABLE] = $allData;
+               $this->saveDb($db);
+               return new ResponseItem(null, null, array());
+       }
+
+       public function deletePersonData(UserId $userId, GroupId $groupId, 
$fields, $appId, SecurityToken $token)
+       {
+               foreach ($fields as $key) {
+                       if (! $this->isValidKey($key)) {
+                               return new ResponseItem(BAD_REQUEST, "The 
person app data key had invalid characters", null);
+                       }
+               }
+               switch ($groupId->getType()) {
+                       case 'self':
+                               foreach ($fields as $key) {     //TODO: 
Implement this!
+                               }
+                               break;
+                       default:
+                               return new ResponseItem(NOT_IMPLEMENTED, "We 
don't support deleting data in batches yet", null);
+                               break;
+               }
+               return new ResponseItem(null, null, array());
+       }
+
+       public function getActivities(UserId $userId, $groupId, $first, $max, 
SecurityToken $token)
+       {
+               $db = $this->getDb();
+               $friendsTable = $db[self::$FRIEND_LINK_TABLE];
+               $ids = array();
+               switch ($groupId->getType()) {
+                       case 'all':
+                       case 'friends':
+                               if (is_array($friendsTable) && 
count($friendsTable) && isset($friendsTable[$userId->getUserId($token)])) {
+                                       $ids = 
$friendsTable[$userId->getUserId($token)];
+                               }
+                               break;
+                       case 'self':
+                               $ids[] = $userId->getUserId($token);
+                               break;
+               }
+               $allActivities = $this->getAllActivities();
+               $activities = array();
+               foreach ($ids as $id) {
+                       if (isset($allActivities[$id])) {
+                               $activities = array_merge($activities, 
$allActivities[$id]);
+                       }
+               }
+               // TODO: Sort them
+               return new ResponseItem(null, null, 
RestfulCollection::createFromEntry($activities));
+       }
+
+       public function createActivity(UserId $userId, $activity, SecurityToken 
$token)
+       {
+               $db = $this->getDb();
+               $activitiesTable = $this->getAllActivities();
+               $activity['appId'] = $token->getAppId();
+               array_push($activitiesTable[$userId->getUserId($token)], 
$activity);
+               $db[self::$ACTIVITIES_TABLE] = $activitiesTable;
+               $this->saveDb($db);
+               return new ResponseItem(null, null, array());
+       }
+
+       public function getActivity(UserId $userId, $groupId, $activityId, 
$first, $max, SecurityToken $token)
+       {
+               $activities = $this->getActivities($userId, $groupId, null, 
null, $token);
+               $activities = $activities->getResponse();
+               if ($activities instanceof RestFulCollection) {
+                       $activities = $activities->getEntry();
+                       foreach ($activities as $activity) {
+                               if ($activity['id'] == $activityId) {
+                                       return new ResponseItem(null, null, 
$activity);
+                               }
+                       }
+               }
+               return new ResponseItem(NOT_FOUND, "Activity not found", null);
+       }
+
+       public function createMessage($userId, $message, SecurityToken $token)
+       {
+               return new ResponseItem(NOT_IMPLEMENTED, "Not implemented", 
null);
+       }
+
+       /**
+        * Determines whether the input is a valid key.
+        *
+        * @param key the key to validate.
+        * @return true if the key is a valid appdata key, false otherwise.
+        */
+       public static function isValidKey($key)
+       {
+               if (empty($key)) {
+                       return false;
+               }
+               for ($i = 0; $i < strlen($key); ++ $i) {
+                       $c = substr($key, $i, 1);
+                       if (($c >= 'a' && $c <= 'z') || ($c >= 'A' && $c <= 
'Z') || ($c >= '0' && $c <= '9') || ($c == '-') || ($c == '_') || ($c == '.')) {
+                               continue;
+                       }
+                       return false;
+               }
+               return true;
+       }
+
+       private function comparator($person, $person1)
+       {
+               $name = $person['name']['unstructured'];
+               $name1 = $person1['name']['unstructured'];
+               if ($name == $name1) {
+                       return 0;
+               }
+               return ($name < $name1) ? - 1 : 1;
+       }
+}

Modified: 
incubator/shindig/trunk/php/src/social-api/dataservice/ActivitiesService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/dataservice/ActivitiesService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/dataservice/ActivitiesService.php 
(original)
+++ 
incubator/shindig/trunk/php/src/social-api/dataservice/ActivitiesService.php 
Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-abstract class ActivitiesService {
+interface ActivitiesService {
 
        /**
         * Returns a list of activities that correspond to the passed in person 
ids.
@@ -25,9 +25,9 @@
         * @param token A valid SecurityToken
         * @return a response item with the list of activities.
         */
-       abstract public function getActivities(UserId $userId, $groupId, 
$first, $max, SecurityToken $token);
+       function getActivities(UserId $userId, $groupId, $first, $max, 
SecurityToken $token);
 
-       abstract public function getActivity(UserId $userId, $groupId, 
$activityId, $first, $max, SecurityToken $token);
+       function getActivity(UserId $userId, $groupId, $activityId, $first, 
$max, SecurityToken $token);
 
        /**
         * Creates the passed in activity for the given user. Once 
createActivity is
@@ -37,5 +37,5 @@
         * @param token A valid SecurityToken
         * @return a response item containing any errors
         */
-       abstract public function createActivity(UserId $userId, $activity, 
SecurityToken $token);
+       function createActivity(UserId $userId, $activity, SecurityToken 
$token);
 }

Modified: 
incubator/shindig/trunk/php/src/social-api/dataservice/AppDataService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/dataservice/AppDataService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/social-api/dataservice/AppDataService.php 
(original)
+++ incubator/shindig/trunk/php/src/social-api/dataservice/AppDataService.php 
Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-abstract class AppDataService {
+interface AppDataService {
 
        /**
         * Fetch data for a list of ids.
@@ -28,9 +28,9 @@
         * @return ResponseItem a response item with the error code set if
         *     there was a problem
         */
-       abstract public function getPersonData(UserId $userId, GroupId 
$groupId, $fields, $appId, SecurityToken $token);
+       function getPersonData(UserId $userId, GroupId $groupId, $fields, 
$appId, SecurityToken $token);
 
-       abstract public function deletePersonData(UserId $userId, GroupId 
$groupId, $fields, $appId, SecurityToken $token);
+       function deletePersonData(UserId $userId, GroupId $groupId, $fields, 
$appId, SecurityToken $token);
 
        /**
         * Updates the data key for the given person with the new value.
@@ -42,5 +42,5 @@
         * @return ResponseItem a response item with the error code set if
         *     there was a problem
         */
-       abstract public function updatePersonData(UserID $userId, GroupId 
$groupId, $fields, $values, $appId, SecurityToken $token);
+       function updatePersonData(UserID $userId, GroupId $groupId, $fields, 
$values, $appId, SecurityToken $token);
 }

Modified: 
incubator/shindig/trunk/php/src/social-api/dataservice/MessagesService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/dataservice/MessagesService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/social-api/dataservice/MessagesService.php 
(original)
+++ incubator/shindig/trunk/php/src/social-api/dataservice/MessagesService.php 
Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-abstract class MessagesService {
+interface MessagesService {
 
        /**  $message is an array containing the following fields:
         *  [id] => {msgid}
@@ -29,5 +29,5 @@
         *          [1] => example.org:997638BAA6F25AD
         *      )
         */
-       abstract public function createMessage($userId, $message, SecurityToken 
$token);
+       public function createMessage($userId, $message, SecurityToken $token);
 }

Modified: 
incubator/shindig/trunk/php/src/social-api/dataservice/PeopleService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/dataservice/PeopleService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/social-api/dataservice/PeopleService.php 
(original)
+++ incubator/shindig/trunk/php/src/social-api/dataservice/PeopleService.php 
Sat Aug  9 10:10:21 2008
@@ -17,10 +17,8 @@
  * specific language governing permissions and limitations under the License.
  */
 
-abstract class PeopleService {
-       public static $sortOrder = array('topFriends', 'name');
-       public static $filterType = array('all', 'hasApp', 'topFriends');
-
+interface PeopleService {
+
        /**
         * Returns a Person object for person with $id or false on not found
         *
@@ -28,7 +26,7 @@
         * @param profileDetails the details to return
         * @param security token $token
         */
-       abstract public function getPerson($userId, $groupId, $profileDetails, 
SecurityToken $token);
+       function getPerson($userId, $groupId, $profileDetails, SecurityToken 
$token);
 
        /**
         * Returns a list of people that correspond to the passed in person ids.
@@ -40,5 +38,10 @@
         * @param max The max number of people to fetch.
         * @return a list of people.
         */
-       abstract public function getPeople($userId, $groupId, $sortOrder, 
$filter, $first, $max, $profileDetails, $networkDistance, SecurityToken $token);
+       function getPeople($userId, $groupId, $sortOrder, $filter, $first, 
$max, $profileDetails, $networkDistance, SecurityToken $token);
 }
+
+class PeopleOptions {
+       public static $sortOrder = array('topFriends', 'name');
+       public static $filterType = array('all', 'hasApp', 'topFriends');
+}
\ No newline at end of file

Modified: 
incubator/shindig/trunk/php/src/social-api/dataservice/RestRequestItem.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/dataservice/RestRequestItem.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/social-api/dataservice/RestRequestItem.php 
(original)
+++ incubator/shindig/trunk/php/src/social-api/dataservice/RestRequestItem.php 
Sat Aug  9 10:10:21 2008
@@ -162,7 +162,7 @@
                if (! empty($this->parameters[self::$ORDER_BY])) {
                        return $this->parameters[self::$ORDER_BY];
                } else {
-                       return PeopleService::$sortOrder;
+                       return PeopleOptions::$sortOrder;
                }
        }
 
@@ -180,7 +180,7 @@
                if (! empty($this->parameters[self::$FILTER_BY])) {
                        return $this->parameters[self::$FILTER_BY];
                } else {
-                       return PeopleService::$filterType;
+                       return PeopleOptions::$filterType;
                }
        }
 

Modified: incubator/shindig/trunk/php/src/social-api/http/RestServlet.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/http/RestServlet.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/src/social-api/http/RestServlet.php (original)
+++ incubator/shindig/trunk/php/src/social-api/http/RestServlet.php Sat Aug  9 
10:10:21 2008
@@ -53,6 +53,7 @@
 require 'src/social-api/converters/InputConverter.php';
 require 'src/social-api/converters/InputAtomConverter.php';
 require 'src/social-api/converters/InputJsonConverter.php';
+require 'src/social-api/canonical/JsonDbOpensocialService.php';
 
 class RestException extends Exception {}
 

Modified: 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicActivitiesService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicActivitiesService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicActivitiesService.php
 (original)
+++ 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicActivitiesService.php
 Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-class BasicActivitiesService extends ActivitiesService {
+class BasicActivitiesService implements ActivitiesService {
 
        public function getActivity(UserId $userId, $groupId, $activityId, 
$first, $max, SecurityToken $token)
        {

Modified: 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicAppDataService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicAppDataService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicAppDataService.php
 (original)
+++ 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicAppDataService.php
 Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-class BasicAppDataService extends AppDataService {
+class BasicAppDataService implements AppDataService {
 
        public function deletePersonData(UserId $userId, GroupId $groupId, 
$fields, $appId, SecurityToken $token)
        {

Modified: 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicMessagesService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicMessagesService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicMessagesService.php
 (original)
+++ 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicMessagesService.php
 Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-class BasicMessagesService extends MessagesService {
+class BasicMessagesService implements MessagesService {
 
        public function createMessage($userId, $message, SecurityToken $token)
        {

Modified: 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicPeopleService.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicPeopleService.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicPeopleService.php
 (original)
+++ 
incubator/shindig/trunk/php/src/social-api/samplecontainer/BasicPeopleService.php
 Sat Aug  9 10:10:21 2008
@@ -17,7 +17,7 @@
  * specific language governing permissions and limitations under the License.
  */
 
-class BasicPeopleService extends PeopleService {
+class BasicPeopleService implements PeopleService {
 
        private function comparator($person, $person1)
        {

Modified: incubator/shindig/trunk/php/test/ShindigAllTests.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/test/ShindigAllTests.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/test/ShindigAllTests.php (original)
+++ incubator/shindig/trunk/php/test/ShindigAllTests.php Sat Aug  9 10:10:21 
2008
@@ -28,23 +28,14 @@
 function __autoload($className)
 {
        $basePath = realpath('./php');
-       $locations = array(
-                                       'src/common',
-                                       'src/common/samplecontainer',
-                                       'src/gadgets', 
-                                       'src/gadgets/http',
-                                       'src/gadgets/oauth',
-                                       'src/gadgets/samplecontainer',
-                                       'src/social-api',
-                                       'src/social-api/http',
-                                       'src/social-api/dataservice',
-                                       'src/social-api/converters',
-                                       'src/social-api/opensocial',
-                                       'src/social-api/opensocial/model',
-                                       'src/social-api/samplecontainer'
-                               );
+       $locations = array('src/common', 'src/common/samplecontainer', 
'src/gadgets', 
+                       'src/gadgets/http', 'src/gadgets/oauth', 
'src/gadgets/samplecontainer', 
+                       'src/social-api', 'src/social-api/http', 
'src/social-api/canonical', 
+                       'src/social-api/dataservice', 
'src/social-api/converters', 
+                       'src/social-api/opensocial', 
'src/social-api/opensocial/model', 
+                       'src/social-api/samplecontainer');
        $extension_class_paths = Config::get('extension_class_paths');
-       if (!empty($extension_class_paths)) {
+       if (! empty($extension_class_paths)) {
                $locations = array_merge(explode(',', $extension_class_paths), 
$locations);
        }
        // Check for the presense of this class in our all our directories.
@@ -57,12 +48,11 @@
        }
 }
 
-set_include_path(get_include_path(). PATH_SEPARATOR . realpath('./php') . 
PATH_SEPARATOR . realpath('./php/external'));
+set_include_path(get_include_path() . PATH_SEPARATOR . realpath('./php') . 
PATH_SEPARATOR . realpath('./php/external'));
 ini_set('error_reporting', E_COMPILE_ERROR | E_ERROR | E_CORE_ERROR);
 require_once 'config.php';
 require_once 'test/TestContext.php';
 
-
 if (defined('PHPUnit_MAIN_METHOD') === false) {
        define('PHPUnit_MAIN_METHOD', 'ShindigAllTests::main');
 }

Modified: incubator/shindig/trunk/php/test/index.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/test/index.php?rev=684297&r1=684296&r2=684297&view=diff
==============================================================================
--- incubator/shindig/trunk/php/test/index.php (original)
+++ incubator/shindig/trunk/php/test/index.php Sat Aug  9 10:10:21 2008
@@ -22,29 +22,20 @@
 
 require_once "PHPUnit/Framework/TestSuite.php";
 require_once "PHPUnit/TextUI/TestRunner.php";
-require_once realpath('../')."/config.php";
-require_once realpath('../')."/test/TestContext.php";
+require_once realpath('../') . "/config.php";
+require_once realpath('../') . "/test/TestContext.php";
 
 function __autoload($className)
 {
        $basePath = realpath('../');
-       $locations = array(
-                                       'src/common',
-                                       'src/common/samplecontainer',
-                                       'src/gadgets', 
-                                       'src/gadgets/http',
-                                       'src/gadgets/oauth',
-                                       'src/gadgets/samplecontainer',
-                                       'src/social-api',
-                                       'src/social-api/http',
-                                       'src/social-api/dataservice',
-                                       'src/social-api/converters',
-                                       'src/social-api/opensocial',
-                                       'src/social-api/opensocial/model',
-                                       'src/social-api/samplecontainer'
-                               );
+       $locations = array('src/common', 'src/common/samplecontainer', 
'src/gadgets', 
+                       'src/gadgets/http', 'src/gadgets/oauth', 
'src/gadgets/samplecontainer', 
+                       'src/social-api', 'src/social-api/canonical', 
'src/social-api/http', 
+                       'src/social-api/dataservice', 
'src/social-api/converters', 
+                       'src/social-api/opensocial', 
'src/social-api/opensocial/model', 
+                       'src/social-api/samplecontainer');
        $extension_class_paths = Config::get('extension_class_paths');
-       if (!empty($extension_class_paths)) {
+       if (! empty($extension_class_paths)) {
                $locations = array_merge(explode(',', $extension_class_paths), 
$locations);
        }
        // Check for the presense of this class in our all our directories.

Added: 
incubator/shindig/trunk/php/test/social-api/JsonDbOpensocialServiceTest.php
URL: 
http://svn.apache.org/viewvc/incubator/shindig/trunk/php/test/social-api/JsonDbOpensocialServiceTest.php?rev=684297&view=auto
==============================================================================
--- incubator/shindig/trunk/php/test/social-api/JsonDbOpensocialServiceTest.php 
(added)
+++ incubator/shindig/trunk/php/test/social-api/JsonDbOpensocialServiceTest.php 
Sat Aug  9 10:10:21 2008
@@ -0,0 +1,312 @@
+<?
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ * Implementation tests based on supported services backed by a JSON DB
+ */
+class JsonDbOpensocialServiceTest extends PHPUnit_Framework_TestCase {
+       
+       /**
+        * @var JsonDbOpensocialService
+        */
+       private $JsonDbOpensocialService;
+
+       /**
+        * Prepares the environment before running a test.
+        */
+       protected function setUp()
+       {
+               parent::setUp();
+               $this->clearFileCache();
+               $this->JsonDbOpensocialService = new JsonDbOpensocialService();
+       }
+
+       /**
+        * Cleans up the environment after running a test.
+        */
+       protected function tearDown()
+       {
+               $this->JsonDbOpensocialService = null;
+               $this->clearFileCache();
+               parent::tearDown();
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->getPeople()
+        */
+       public function testGetPeople()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $sortOrder = null;
+               $filter = null;
+               $first = null;
+               $max = null;
+               $profileDetails = array('id', 'name', 'thumbnailUrl');
+               $networkDistance = null;
+               
+               //With existing data
+               $token = BasicSecurityToken::createFromValues('john.doe', 
'john.doe', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getPeople($userId, $groupId, $sortOrder, 
$filter, $first, $max, $profileDetails, $networkDistance, $token);
+               $response = $responseItem->getResponse();
+               $entry = $response->getEntry();
+               $this->assertEquals(1, $response->getTotalResults());
+               $this->assertEquals(1, count($entry));
+               $this->assertEquals('john.doe', $entry[0]['id']);
+               $this->assertEquals('Doe', $entry[0]['name']['familyName']);
+               $this->assertEquals('John', $entry[0]['name']['givenName']);
+               $this->assertEquals('John Doe', 
$entry[0]['name']['unstructured']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getPeople($userId, $groupId, $sortOrder, 
$filter, $first, $max, $profileDetails, $networkDistance, $token);
+               $response = $responseItem->getResponse();
+               $this->assertEquals(0, $response->getTotalResults());
+               $this->assertEquals(0, count($response->getEntry()));
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->getPerson()
+        */
+       public function testGetPerson()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $profileDetails = array('id', 'name', 'thumbnailUrl');
+               
+               //With existing data
+               $token = BasicSecurityToken::createFromValues('john.doe', 
'john.doe', 'app', 'domain', 'appUrl', '1');
+               $person = $this->JsonDbOpensocialService->getPerson($userId, 
$groupId, $profileDetails, $token);
+               $response = $person->getResponse();
+               $this->assertNotNull($response);
+               $this->assertEquals('john.doe', $response['id']);
+               $this->assertEquals('Doe', $response['name']['familyName']);
+               $this->assertEquals('John', $response['name']['givenName']);
+               $this->assertEquals('John Doe', 
$response['name']['unstructured']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $person = $this->JsonDbOpensocialService->getPerson($userId, 
$groupId, $profileDetails, $token);
+               $response = $person->getResponse();
+               $this->assertEquals('NOT_FOUND', $person->getError());
+               $this->assertEquals('Person not found', 
$person->getErrorMessage());
+               $this->assertNull($person->getResponse());
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->getPersonData()
+        */
+       public function testGetPersonData()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $profileDetails = array('count', 'size');
+               $appId = 'app';
+               
+               //With existing data
+               $token = BasicSecurityToken::createFromValues('canonical', 
'canonical', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getPersonData($userId, $groupId, 
$profileDetails, $appId, $token);
+               $response = $responseItem->getResponse();
+               $entry = $response->getEntry();
+               $this->assertEquals(1, $response->getTotalResults());
+               $this->assertEquals(1, count($entry));
+               $this->assertEquals(2, $entry['canonical']['count']);
+               $this->assertEquals(100, $entry['canonical']['size']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getPersonData($userId, $groupId, 
$profileDetails, $appId, $token);
+               $response = $responseItem->getResponse();
+               $this->assertEquals(0, $response->getTotalResults());
+               $this->assertEquals(0, count($response->getEntry()));
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->updatePersonData()
+        */
+       public function testUpdatePersonData()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $profileDetails = array('count', 'size');
+               $values = array();
+               $values['count'] = 10;
+               $values['size'] = 500;
+               $appId = 'app';
+               
+               //With existing data
+               $token = BasicSecurityToken::createFromValues('canonical', 
'canonical', 'app', 'domain', 'appUrl', '1');
+               $this->JsonDbOpensocialService->updatePersonData($userId, 
$groupId, $profileDetails, $values, $appId, $token);
+               $responseItem = 
$this->JsonDbOpensocialService->getPersonData($userId, $groupId, 
$profileDetails, $appId, $token);
+               $response = $responseItem->getResponse();
+               $entry = $response->getEntry();
+               $this->assertEquals(1, $response->getTotalResults());
+               $this->assertEquals(1, count($entry));
+               $this->assertEquals(10, $entry['canonical']['count']);
+               $this->assertEquals(500, $entry['canonical']['size']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $this->JsonDbOpensocialService->updatePersonData($userId, 
$groupId, $profileDetails, $values, $appId, $token);
+               $responseItem = 
$this->JsonDbOpensocialService->getPersonData($userId, $groupId, 
$profileDetails, $appId, $token);
+               $response = $responseItem->getResponse();
+               $entry = $response->getEntry();
+               $this->assertEquals(1, $response->getTotalResults());
+               $this->assertEquals(1, count($entry));
+               $this->assertEquals(10, $entry['notexists']['count']);
+               $this->assertEquals(500, $entry['notexists']['size']);
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->deletePersonData()
+        */
+       public function testDeletePersonData()
+       {
+               //TODO: Implement me!
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->getActivities()
+        */
+       public function testGetActivities()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               
+               //With existing data
+               $token = BasicSecurityToken::createFromValues('canonical', 
'canonical', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getActivities($userId, $groupId, null, null, 
$token);
+               $response = $responseItem->getResponse();
+               $entry = $response->getEntry();
+               $this->assertEquals(2, $response->getTotalResults());
+               $this->assertEquals(2, count($entry));
+               $this->assertEquals(1, $entry[0]['appId']);
+               $this->assertEquals('Went rafting', $entry[0]['body']);
+               $this->assertEquals(1, $entry[0]['bodyId']);
+               $this->assertEquals('http://www.example.org/123456', 
$entry[0]['externalId']);
+               $this->assertEquals(1, $entry[0]['id']);
+               $this->assertEquals('2008-06-06T12:12:12Z', 
$entry[0]['updated']);
+               $this->assertEquals('image/*', 
$entry[0]['mediaItems'][0]['mimeType']);
+               $this->assertEquals('image', 
$entry[0]['mediaItems'][0]['type']);
+               
$this->assertEquals('http://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Rafting_em_Brotas.jpg/800px-Rafting_em_Brotas.jpg',
 $entry[0]['mediaItems'][0]['url']);
+               $this->assertEquals('audio/mpeg', 
$entry[0]['mediaItems'][1]['mimeType']);
+               $this->assertEquals('audio', 
$entry[0]['mediaItems'][1]['type']);
+               
$this->assertEquals('http://www.archive.org/download/testmp3testfile/mpthreetest.mp3',
 $entry[0]['mediaItems'][1]['url']);
+               $this->assertEquals(1111111111, $entry[0]['postedTime']);
+               $this->assertEquals(0.7, $entry[0]['priority']);
+               
$this->assertEquals('http://upload.wikimedia.org/wikipedia/commons/0/02/Nuvola_apps_edu_languages.gif',
 $entry[0]['streamFaviconUrl']);
+               
$this->assertEquals('http://www.example.org/canonical/streamsource', 
$entry[0]['streamSourceUrl']);
+               $this->assertEquals('All my activities', 
$entry[0]['streamTitle']);
+               
$this->assertEquals('http://www.example.org/canonical/activities', 
$entry[0]['streamUrl']);
+               $this->assertEquals(true, $entry[0]['templateParams']['small']);
+               $this->assertEquals('and got wet', 
$entry[0]['templateParams']['otherContent']);
+               $this->assertEquals('My trip', $entry[0]['title']);
+               $this->assertEquals(1, $entry[0]['titleId']);
+               
$this->assertEquals('http://www.example.org/canonical/activities/1', 
$entry[0]['url']);
+               $this->assertEquals('canonical', $entry[0]['userId']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getActivities($userId, $groupId, null, null, 
$token);
+               $response = $responseItem->getResponse();
+               $this->assertEquals(0, $response->getTotalResults());
+               $this->assertEquals(0, count($response->getEntry()));
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->getActivity()
+        */
+       public function testGetActivity()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $token = BasicSecurityToken::createFromValues('canonical', 
'canonical', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getActivity($userId, $groupId, '1', null, null, 
$token);
+               $entry = $responseItem->getResponse();
+               $this->assertEquals(1, count($responseItem));
+               $this->assertEquals(1, $entry['appId']);
+               $this->assertEquals('Went rafting', $entry['body']);
+               $this->assertEquals(1, $entry['bodyId']);
+               $this->assertEquals('http://www.example.org/123456', 
$entry['externalId']);
+               $this->assertEquals(1, $entry['id']);
+               $this->assertEquals('2008-06-06T12:12:12Z', $entry['updated']);
+               $this->assertEquals('image/*', 
$entry['mediaItems'][0]['mimeType']);
+               $this->assertEquals('image', $entry['mediaItems'][0]['type']);
+               
$this->assertEquals('http://upload.wikimedia.org/wikipedia/commons/thumb/7/77/Rafting_em_Brotas.jpg/800px-Rafting_em_Brotas.jpg',
 $entry['mediaItems'][0]['url']);
+               $this->assertEquals('audio/mpeg', 
$entry['mediaItems'][1]['mimeType']);
+               $this->assertEquals('audio', $entry['mediaItems'][1]['type']);
+               
$this->assertEquals('http://www.archive.org/download/testmp3testfile/mpthreetest.mp3',
 $entry['mediaItems'][1]['url']);
+               $this->assertEquals(1111111111, $entry['postedTime']);
+               $this->assertEquals(0.7, $entry['priority']);
+               
$this->assertEquals('http://upload.wikimedia.org/wikipedia/commons/0/02/Nuvola_apps_edu_languages.gif',
 $entry['streamFaviconUrl']);
+               
$this->assertEquals('http://www.example.org/canonical/streamsource', 
$entry['streamSourceUrl']);
+               $this->assertEquals('All my activities', $entry['streamTitle']);
+               
$this->assertEquals('http://www.example.org/canonical/activities', 
$entry['streamUrl']);
+               $this->assertEquals(true, $entry['templateParams']['small']);
+               $this->assertEquals('and got wet', 
$entry['templateParams']['otherContent']);
+               $this->assertEquals('My trip', $entry['title']);
+               $this->assertEquals(1, $entry['titleId']);
+               
$this->assertEquals('http://www.example.org/canonical/activities/1', 
$entry['url']);
+               $this->assertEquals('canonical', $entry['userId']);
+               
+               //With non existing data
+               $token = BasicSecurityToken::createFromValues('notexists', 
'notexists', 'app', 'domain', 'appUrl', '1');
+               $activity = 
$this->JsonDbOpensocialService->getActivity($userId, $groupId, '1', null, null, 
$token);
+               $this->assertEquals('NOT_FOUND', $activity->getError());
+               $this->assertEquals('Activity not found', 
$activity->getErrorMessage());
+               $this->assertNull($activity->getResponse());
+       }
+
+       /**
+        * Tests JsonDbOpensocialService->createActivity()
+        */
+       public function testCreateActivity()
+       {
+               $userId = new UserId('viewer', null);
+               $groupId = new GroupId('self', null);
+               $token = BasicSecurityToken::createFromValues('john.doe', 
'john.doe', 'app', 'domain', 'appUrl', '1');
+               $activity = array();
+               $activity['id'] = 2;
+               $activity['title'] = 'John Doe wrote: asdasd';
+               $activity['body'] = 'write back!';
+               $activity['mediaItems'] = array();
+               $activity['mediaItems'][0]['type'] = 'image';
+               $activity['mediaItems'][0]['mimeType'] = 'image';
+               $activity['mediaItems'][0]['image'] = 
'http://cdn.davesdaily.com/pictures/784-awesome-hands.jpg';
+               $this->JsonDbOpensocialService->createActivity($userId, 
$activity, $token);
+               
+               //Validating the created activity
+               $token = BasicSecurityToken::createFromValues('john.doe', 
'john.doe', 'app', 'domain', 'appUrl', '1');
+               $responseItem = 
$this->JsonDbOpensocialService->getActivity($userId, $groupId, 2, null, null, 
$token);
+               $entry = $responseItem->getResponse();
+               $this->assertEquals(2, $entry['id']);
+               $this->assertEquals('John Doe wrote: asdasd', $entry['title']);
+               $this->assertEquals('write back!', $entry['body']);
+               $this->assertEquals('image', 
$activity['mediaItems'][0]['type']);
+               $this->assertEquals('image', 
$activity['mediaItems'][0]['mimeType']);
+               
$this->assertEquals('http://cdn.davesdaily.com/pictures/784-awesome-hands.jpg', 
$activity['mediaItems'][0]['image']);
+               $this->assertEquals('app', $entry['appId']);
+       }
+
+       private function clearFileCache()
+       {
+               unlink(sys_get_temp_dir() . "ShindigDb.json");
+       }
+}


Reply via email to