View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  The ASF licenses this file to You
4    * under the Apache License, Version 2.0 (the "License"); you may not
5    * use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.  For additional information regarding
15   * copyright in this work, please see the NOTICE file in the top level
16   * directory of this distribution.
17   */
18  package org.apache.shindig.social.dataservice.integration;
19  
20  import org.apache.shindig.social.core.model.AddressImpl;
21  import org.apache.shindig.social.core.model.BodyTypeImpl;
22  import org.apache.shindig.social.core.model.EnumImpl;
23  import org.apache.shindig.social.core.model.ListFieldImpl;
24  import org.apache.shindig.social.core.model.NameImpl;
25  import org.apache.shindig.social.core.model.OrganizationImpl;
26  import org.apache.shindig.social.core.model.PersonImpl;
27  import org.apache.shindig.social.core.model.UrlImpl;
28  import org.apache.shindig.social.opensocial.model.Address;
29  import org.apache.shindig.social.opensocial.model.BodyType;
30  import org.apache.shindig.social.opensocial.model.Enum;
31  import org.apache.shindig.social.opensocial.model.ListField;
32  import org.apache.shindig.social.opensocial.model.Name;
33  import org.apache.shindig.social.opensocial.model.Organization;
34  import org.apache.shindig.social.opensocial.model.Person;
35  import org.apache.shindig.social.opensocial.model.Url;
36  
37  import com.google.common.collect.Lists;
38  import com.google.common.collect.Maps;
39  import org.json.JSONArray;
40  import org.json.JSONException;
41  import org.json.JSONObject;
42  import org.junit.Test;
43  
44  import java.util.Date;
45  import java.util.List;
46  import java.util.Map;
47  
48  public class RestfulJsonPeopleTest extends AbstractLargeRestfulTests {
49    private Person canonical;
50  
51    protected void setUp() throws Exception {
52      super.setUp();
53      NameImpl name = new NameImpl("Sir Shin H. Digg Social Butterfly");
54      name.setAdditionalName("H");
55      name.setFamilyName("Digg");
56      name.setGivenName("Shin");
57      name.setHonorificPrefix("Sir");
58      name.setHonorificSuffix("Social Butterfly");
59      canonical = new PersonImpl("canonical", "Shin Digg", name);
60  
61      canonical.setAboutMe("I have an example of every piece of data");
62      canonical.setActivities(Lists.newArrayList("Coding Shindig"));
63  
64      Address address = new AddressImpl("PoBox 3565, 1 OpenStandards Way, Apache, CA");
65      address.setCountry("US");
66      address.setLatitude(28.3043F);
67      address.setLongitude(143.0859F);
68      address.setLocality("who knows");
69      address.setPostalCode("12345");
70      address.setRegion("Apache, CA");
71      address.setStreetAddress("1 OpenStandards Way");
72      address.setType("home");
73      address.setFormatted("PoBox 3565, 1 OpenStandards Way, Apache, CA");
74      canonical.setAddresses(Lists.newArrayList(address));
75  
76      canonical.setAge(33);
77      BodyTypeImpl bodyType = new BodyTypeImpl();
78      bodyType.setBuild("svelte");
79      bodyType.setEyeColor("blue");
80      bodyType.setHairColor("black");
81      bodyType.setHeight(1.84F);
82      bodyType.setWeight(74F);
83      canonical.setBodyType(bodyType);
84  
85      canonical.setBooks(Lists.newArrayList("The Cathedral & the Bazaar", "Catch 22"));
86      canonical.setCars(Lists.newArrayList("beetle", "prius"));
87      canonical.setChildren("3");
88      AddressImpl location = new AddressImpl();
89      location.setLatitude(48.858193F);
90      location.setLongitude(2.29419F);
91      canonical.setCurrentLocation(location);
92  
93      canonical.setBirthday(new Date());
94      canonical.setDrinker(new EnumImpl<Enum.Drinker>(Enum.Drinker.SOCIALLY));
95      ListField email = new ListFieldImpl("work", "shindig-dev@incubator.apache.org");
96      canonical.setEmails(Lists.newArrayList(email));
97  
98      canonical.setEthnicity("developer");
99      canonical.setFashion("t-shirts");
100     canonical.setFood(Lists.newArrayList("sushi", "burgers"));
101     canonical.setGender(Person.Gender.male);
102     canonical.setHappiestWhen("coding");
103     canonical.setHasApp(true);
104     canonical.setHeroes(Lists.newArrayList("Doug Crockford", "Charles Babbage"));
105     canonical.setHumor("none to speak of");
106     canonical.setInterests(Lists.newArrayList("PHP", "Java"));
107     canonical.setJobInterests("will work for beer");
108 
109     Organization job1 = new OrganizationImpl();
110     job1.setAddress(new AddressImpl("1 Shindig Drive"));
111     job1.setDescription("lots of coding");
112     job1.setEndDate(new Date());
113     job1.setField("Software Engineering");
114     job1.setName("Apache.com");
115     job1.setSalary("$1000000000");
116     job1.setStartDate(new Date());
117     job1.setSubField("Development");
118     job1.setTitle("Grand PooBah");
119     job1.setWebpage("http://incubator.apache.org/projects/shindig.html");
120     job1.setType("job");
121 
122     Organization job2 = new OrganizationImpl();
123     job2.setAddress(new AddressImpl("1 Skid Row"));
124     job2.setDescription("");
125     job2.setEndDate(new Date());
126     job2.setField("College");
127     job2.setName("School of hard Knocks");
128     job2.setSalary("$100");
129     job2.setStartDate(new Date());
130     job2.setSubField("Lab Tech");
131     job2.setTitle("Gopher");
132     job2.setWebpage("");
133     job2.setType("job");
134 
135     canonical.setOrganizations(Lists.newArrayList(job1, job2));
136 
137     canonical.setUpdated(new Date());
138     canonical.setLanguagesSpoken(Lists.newArrayList("English", "Dutch", "Esperanto"));
139     canonical.setLivingArrangement("in a house");
140     Enum<Enum.LookingFor> lookingForRandom =
141         new EnumImpl<Enum.LookingFor>(Enum.LookingFor.RANDOM, "Random");
142     Enum<Enum.LookingFor> lookingForNetworking =
143         new EnumImpl<Enum.LookingFor>(Enum.LookingFor.NETWORKING, "Networking");
144     canonical.setLookingFor(Lists.newArrayList(lookingForRandom, lookingForNetworking));
145     canonical.setMovies(Lists.newArrayList("Iron Man", "Nosferatu"));
146     canonical.setMusic(Lists.newArrayList("Chieftains", "Beck"));
147     canonical.setNetworkPresence(new EnumImpl<Enum.NetworkPresence>(Enum.NetworkPresence.ONLINE));
148     canonical.setNickname("diggy");
149     canonical.setPets("dog,cat");
150     canonical.setPhoneNumbers(Lists.<ListField> newArrayList(new ListFieldImpl("work",
151         "111-111-111"), new ListFieldImpl("mobile", "999-999-999")));
152 
153     canonical.setPoliticalViews("open leaning");
154     canonical.setProfileSong(new UrlImpl("http://www.example.org/songs/OnlyTheLonely.mp3",
155         "Feelin' blue", "road"));
156     canonical.setProfileVideo(new UrlImpl("http://www.example.org/videos/Thriller.flv",
157         "Thriller", "video"));
158 
159     canonical.setQuotes(Lists.newArrayList("I am therfore I code", "Doh!"));
160     canonical.setRelationshipStatus("married to my job");
161     canonical.setReligion("druidic");
162     canonical.setRomance("twice a year");
163     canonical.setScaredOf("COBOL");
164     canonical.setSexualOrientation("north");
165     canonical.setSmoker(new EnumImpl<Enum.Smoker>(Enum.Smoker.NO));
166     canonical.setSports(Lists.newArrayList("frisbee", "rugby"));
167     canonical.setStatus("happy");
168     canonical.setTags(Lists.newArrayList("C#", "JSON", "template"));
169     canonical.setThumbnailUrl("http://www.example.org/pic/?id=1");
170     canonical.setUtcOffset(-8L);
171     canonical.setTurnOffs(Lists.newArrayList("lack of unit tests", "cabbage"));
172     canonical.setTurnOns(Lists.newArrayList("well document code"));
173     canonical.setTvShows(Lists.newArrayList("House", "Battlestar Galactica"));
174 
175     canonical.setUrls(Lists.<Url>newArrayList(
176         new UrlImpl("http://www.example.org/?id=1", "my profile", "Profile"),
177         new UrlImpl("http://www.example.org/pic/?id=1", "my awesome picture", "Thumbnail")));
178   }
179 
180   /***
181    * Expected response for john.doe's json:
182    *
183    * { 'entry' : {
184    *     'id' : 'john.doe',
185    *     'name' : {'unstructured' : 'John Doe'},
186    *     'phoneNumbers' : [
187    *       { 'number' : '+33H000000000', 'type' : 'home'},
188    *     ],
189    *     'addresses' : [
190    *       {'formattedAddress' : 'My home address'}
191    *     ],
192    *     'emails' : [
193    *       { 'value' : 'john.doe@work.bar', 'type' : 'work'},
194    *     ]
195    *
196    *    ... etc, etc for all fields in the person object
197    *   }
198    * }
199    * TODO: Finish up this test and make refactor so that it is easier to read
200    *
201    * @throws Exception if test encounters an error
202    */
203   @Test
204   public void testGetPersonJson() throws Exception {
205     // TODO(doll): Test all of the date fields
206 
207     Map<String, String> extraParams = Maps.newHashMap();
208     String allFieldsParam = "";
209     for (String allField : Person.Field.ALL_FIELDS) {
210       allFieldsParam += allField + ",";
211     }
212     extraParams.put("fields", allFieldsParam);
213 
214     // Currently, for Shindig {pid}/@all/{uid} == {uid}/@self
215     String resp = getResponse("/people/canonical/@self", "GET", extraParams, null, "application/json");
216     JSONObject result = getJson(resp).getJSONObject("entry");
217 
218     assertStringField(result, canonical.getAboutMe(), Person.Field.ABOUT_ME);
219     assertStringListField(result, canonical.getActivities(),
220         Person.Field.ACTIVITIES);
221 
222     JSONObject jsonAddress = result.getJSONArray(
223         Person.Field.ADDRESSES.toString()).getJSONObject(0);
224     assertAddressField(canonical.getAddresses().get(0), jsonAddress);
225 
226     assertEquals(canonical.getAge().intValue(), result.getInt(
227         Person.Field.AGE.toString()));
228 
229     JSONObject jsonBody = result.getJSONObject(
230         Person.Field.BODY_TYPE.toString());
231     BodyType body = canonical.getBodyType();
232     assertStringField(jsonBody, body.getBuild(), BodyType.Field.BUILD);
233     assertStringField(jsonBody, body.getEyeColor(), BodyType.Field.EYE_COLOR);
234     assertStringField(jsonBody, body.getHairColor(), BodyType.Field.HAIR_COLOR);
235     assertFloatField(jsonBody, body.getHeight(), BodyType.Field.HEIGHT);
236     assertFloatField(jsonBody, body.getWeight(), BodyType.Field.WEIGHT);
237 
238     assertStringListField(result, canonical.getBooks(), Person.Field.BOOKS);
239     assertStringListField(result, canonical.getCars(), Person.Field.CARS);
240     assertStringField(result, canonical.getChildren(), Person.Field.CHILDREN);
241 
242     JSONObject currentLocation = result.getJSONObject(Person.Field.CURRENT_LOCATION.toString());
243     assertFloatField(currentLocation, canonical.getCurrentLocation().getLatitude(),
244         Address.Field.LATITUDE);
245     assertFloatField(currentLocation, canonical.getCurrentLocation().getLongitude(),
246         Address.Field.LONGITUDE);
247 
248     assertStringField(result, canonical.getDisplayName(), Person.Field.DISPLAY_NAME);
249 
250 //    assertLongField(result, canonical.getBirthday().getTime(),
251 //        Person.Field.BIRTHDAY);
252 //    assertEnumField(result, canonical.getDrinker(), Person.Field.DRINKER);
253 
254     JSONArray emailArray = result.getJSONArray(Person.Field.EMAILS.toString());
255     assertEquals(1, emailArray.length());
256 
257     for (int i = 0; i < canonical.getEmails().size(); i++) {
258       ListField expectedEmail = canonical.getEmails().get(i);
259       JSONObject actualEmail = emailArray.getJSONObject(i);
260       assertEquals(expectedEmail.getType(),
261           actualEmail.getString(ListField.Field.TYPE.toString()));
262       assertEquals(expectedEmail.getValue(),
263           actualEmail.getString(ListField.Field.VALUE.toString()));
264     }
265 
266     assertStringField(result, canonical.getEthnicity(), Person.Field.ETHNICITY);
267     assertStringField(result, canonical.getFashion(), Person.Field.FASHION);
268     assertStringListField(result, canonical.getFood(), Person.Field.FOOD);
269     assertStringField(result, canonical.getGender().toString(), Person.Field.GENDER);
270     assertStringField(result, canonical.getHappiestWhen(),
271         Person.Field.HAPPIEST_WHEN);
272     assertBooleanField(result, canonical.getHasApp(), Person.Field.HAS_APP);
273     assertStringListField(result, canonical.getHeroes(), Person.Field.HEROES);
274     assertStringField(result, canonical.getHumor(), Person.Field.HUMOR);
275     assertStringField(result, canonical.getId(), Person.Field.ID);
276     assertStringListField(result, canonical.getInterests(),
277         Person.Field.INTERESTS);
278     assertStringField(result, canonical.getJobInterests(),
279         Person.Field.JOB_INTERESTS);
280 
281     assertOrganizationField(canonical.getOrganizations().get(0),
282         result.getJSONArray(Person.Field.ORGANIZATIONS.toString()).getJSONObject(0));
283 
284     assertStringListField(result, canonical.getLanguagesSpoken(),
285         Person.Field.LANGUAGES_SPOKEN);
286 //    assertDateField(result, canonical.getUpdated(), Person.Field.LAST_UPDATED);
287     assertStringField(result, canonical.getLivingArrangement(),
288         Person.Field.LIVING_ARRANGEMENT);
289     assertListEnumField(result, canonical.getLookingFor(),
290         Person.Field.LOOKING_FOR);
291     assertStringListField(result, canonical.getMovies(), Person.Field.MOVIES);
292     assertStringListField(result, canonical.getMusic(), Person.Field.MUSIC);
293 
294     assertEquals(canonical.getName().getUnstructured(),
295         result.getJSONObject(Person.Field.NAME.toString()).getString(
296             Name.Field.UNSTRUCTURED.toString()));
297 
298     assertEnumField(result, canonical.getNetworkPresence(),
299         Person.Field.NETWORKPRESENCE);
300     assertStringField(result, canonical.getNickname(), Person.Field.NICKNAME);
301     assertStringField(result, canonical.getPets(), Person.Field.PETS);
302 
303     JSONArray phoneArray = result.getJSONArray(
304         Person.Field.PHONE_NUMBERS.toString());
305     assertEquals(canonical.getPhoneNumbers().size(), phoneArray.length());
306 
307     for (int i = 0; i < canonical.getPhoneNumbers().size(); i++) {
308       ListField expectedPhone = canonical.getPhoneNumbers().get(i);
309       JSONObject actualPhone = phoneArray.getJSONObject(i);
310       assertEquals(expectedPhone.getType(), actualPhone.getString(
311           ListField.Field.TYPE.toString()));
312       assertEquals(expectedPhone.getValue(), actualPhone.getString(
313           ListField.Field.VALUE.toString()));
314     }
315 
316     assertStringField(result, canonical.getPoliticalViews(),
317         Person.Field.POLITICAL_VIEWS);
318 
319     assertUrlField(canonical.getProfileSong(), result.getJSONObject(
320         Person.Field.PROFILE_SONG.toString()));
321     assertStringField(result, canonical.getProfileUrl(),
322         Person.Field.PROFILE_URL);
323     assertUrlField(canonical.getProfileVideo(), result.getJSONObject(
324         Person.Field.PROFILE_VIDEO.toString()));
325 
326     assertStringListField(result, canonical.getQuotes(), Person.Field.QUOTES);
327     assertStringField(result, canonical.getRelationshipStatus(),
328         Person.Field.RELATIONSHIP_STATUS);
329     assertStringField(result, canonical.getReligion(), Person.Field.RELIGION);
330     assertStringField(result, canonical.getRomance(), Person.Field.ROMANCE);
331     assertStringField(result, canonical.getScaredOf(), Person.Field.SCARED_OF);
332 
333     assertStringField(result, canonical.getSexualOrientation(), Person.Field.SEXUAL_ORIENTATION);
334     assertEnumField(result, canonical.getSmoker(), Person.Field.SMOKER);
335     assertStringListField(result, canonical.getSports(), Person.Field.SPORTS);
336     assertStringField(result, canonical.getStatus(), Person.Field.STATUS);
337     assertStringListField(result, canonical.getTags(), Person.Field.TAGS);
338     assertStringField(result, canonical.getThumbnailUrl(),
339         Person.Field.THUMBNAIL_URL);
340     // TODO: time zone
341     assertStringListField(result, canonical.getTurnOffs(),
342         Person.Field.TURN_OFFS);
343     assertStringListField(result, canonical.getTurnOns(), Person.Field.TURN_ONS);
344     assertStringListField(result, canonical.getTvShows(), Person.Field.TV_SHOWS);
345   }
346 
347   private void assertAddressField(Address expected, JSONObject actual)
348       throws JSONException {
349     assertStringField(actual, expected.getCountry(),
350         Address.Field.COUNTRY);
351     assertFloatField(actual, expected.getLatitude(), Address.Field.LATITUDE);
352     assertStringField(actual, expected.getLocality(), Address.Field.LOCALITY);
353     assertFloatField(actual, expected.getLongitude(), Address.Field.LONGITUDE);
354     assertStringField(actual, expected.getPostalCode(),
355         Address.Field.POSTAL_CODE);
356     assertStringField(actual, expected.getRegion(), Address.Field.REGION);
357     assertStringField(actual, expected.getStreetAddress(),
358         Address.Field.STREET_ADDRESS);
359     assertStringField(actual, expected.getType(), Address.Field.TYPE);
360     assertStringField(actual, expected.getFormatted(),
361         Address.Field.FORMATTED);
362   }
363 
364   private void assertUrlField(Url expected, JSONObject actual)
365       throws JSONException {
366     assertStringField(actual, expected.getValue(), Url.Field.VALUE);
367     assertStringField(actual, expected.getLinkText(), Url.Field.LINK_TEXT);
368     assertStringField(actual, expected.getType(), Url.Field.TYPE);
369   }
370 
371   private void assertOrganizationField(Organization expected, JSONObject actual)
372       throws JSONException {
373     assertStringField(actual.getJSONObject(Organization.Field.ADDRESS.toString()),
374         expected.getAddress().getFormatted(), Address.Field.FORMATTED);
375     assertStringField(actual, expected.getDescription(),
376         Organization.Field.DESCRIPTION);
377 //    assertDateField(actual, expected.getEndDate(), Organization.Field.END_DATE);
378     assertStringField(actual, expected.getField(), Organization.Field.FIELD);
379     assertStringField(actual, expected.getName(), Organization.Field.NAME);
380     assertStringField(actual, expected.getSalary(), Organization.Field.SALARY);
381 //    assertDateField(actual, expected.getStartDate(), Organization.Field.START_DATE);
382     assertStringField(actual, expected.getSubField(), Organization.Field.SUB_FIELD);
383     assertStringField(actual, expected.getTitle(), Organization.Field.TITLE);
384     assertStringField(actual, expected.getWebpage(), Organization.Field.WEBPAGE);
385     assertStringField(actual, expected.getType(), Organization.Field.TYPE);
386   }
387 
388   private void assertBooleanField(JSONObject result, boolean expected,
389       Object field) throws JSONException {
390     assertEquals(expected, result.getBoolean(field.toString()));
391   }
392 
393   private void assertFloatField(JSONObject result, Float expected,
394       Object field) throws JSONException {
395     assertEquals(expected.intValue(), result.getInt(field.toString()));
396   }
397 
398   private void assertStringField(JSONObject result, String expected,
399       Object field) throws JSONException {
400     assertEquals(expected, result.getString(field.toString()));
401   }
402 
403   private void assertStringListField(JSONObject result, List<String> list,
404       Person.Field field) throws JSONException {
405     JSONArray actual = result.getJSONArray(field.toString());
406     assertEquals(list.get(0), actual.getString(0));
407   }
408 
409   private void assertEnumField(JSONObject result, Enum expected,
410       Person.Field field) throws JSONException {
411     JSONObject actual = result.getJSONObject(field.toString());
412     assertEquals(expected.getDisplayValue(), actual.getString("displayValue"));
413     assertEquals(expected.getValue().toString(), actual.getString("value"));
414   }
415 
416   private void assertListEnumField(JSONObject result,
417       List<? extends Enum<? extends Enum.EnumKey>> expected,
418       Person.Field field) throws JSONException {
419     JSONArray actual = result.getJSONArray(field.toString());
420     for (int i = 0; i < actual.length(); i++) {
421       assertEquals(expected.get(i).getDisplayValue(),
422           actual.getJSONObject(i).getString("displayValue"));
423       assertEquals(expected.get(i).getValue().toString(),
424           actual.getJSONObject(i).getString("value"));
425     }
426   }
427 
428   /***
429    * Expected response for a list of people in json:
430    *
431    * {
432    *  "totalResults" : 3,
433    *  "startIndex" : 0
434    *  "entry" : [
435    *     {<jane doe>}, // layed out like above
436    *     {<george doe>},
437    *     {<maija m>},
438    *  ]
439    * }
440    *
441    * @throws Exception if test encounters an error
442    */
443   @Test
444   public void testGetPeople() throws Exception {
445     Map<String, String> extraParams = Maps.newHashMap();
446     extraParams.put("sortBy", "name");
447     extraParams.put("sortOrder", null);
448     extraParams.put("filterBy", null);
449     extraParams.put("startIndex", null);
450     extraParams.put("count", "20");
451     extraParams.put("fields", null);
452 
453     // Currently, for Shindig @all == @friends
454     String resp = getResponse("/people/john.doe/@friends", "GET", extraParams, null, "application/json");
455     JSONObject result = getJson(resp);
456 
457     assertEquals(3, result.getInt("totalResults"));
458     assertEquals(0, result.getInt("startIndex"));
459 
460     JSONArray people = result.getJSONArray("entry");
461 
462     // The users should be in alphabetical order
463     assertPerson(people.getJSONObject(0), "george.doe", "George Doe");
464     assertPerson(people.getJSONObject(1), "jane.doe", "Jane Doe");
465   }
466 
467   @Test
468   public void testGetPeoplePagination() throws Exception {
469     Map<String, String> extraParams = Maps.newHashMap();
470     extraParams.put("sortBy", "name");
471     extraParams.put("sortOrder", null);
472     extraParams.put("filterBy", null);
473     extraParams.put("startIndex", "0");
474     extraParams.put("count", "1");
475     extraParams.put("fields", null);
476 
477     String resp = getResponse("/people/john.doe/@friends", "GET", extraParams, null, "application/json");
478     JSONObject result = getJson(resp);
479 
480     assertEquals(3, result.getInt("totalResults"));
481     assertEquals(0, result.getInt("startIndex"));
482 
483     JSONArray people = result.getJSONArray("entry");
484     assertPerson(people.getJSONObject(0), "george.doe", "George Doe");
485 
486     // Get the second page
487     extraParams.put("startIndex", "1");
488     resp = getResponse("/people/john.doe/@friends", "GET", extraParams, null, "application/json");
489     result = getJson(resp);
490 
491     assertEquals(3, result.getInt("totalResults"));
492     assertEquals(1, result.getInt("startIndex"));
493 
494     people = result.getJSONArray("entry");
495     assertPerson(people.getJSONObject(0), "jane.doe", "Jane Doe");
496   }
497 
498   private void assertPerson(JSONObject person, String expectedId, String expectedName)
499       throws Exception {
500     assertEquals(expectedId, person.getString("id"));
501     assertEquals(expectedName, person.getJSONObject("name").getString("unstructured"));
502   }
503 
504   // TODO: Add tests for fields parameter
505   // TODO: Add tests for networkDistance
506 }