Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

CL-161:Create Separate Unit Tests into Seperate Android App

  • Loading branch information...
commit 49238714d6763716b471a204ab2ac3a0b65b5d79 1 parent 31738ac
tanaji authored
Showing with 1,700 additions and 0 deletions.
  1. +8 −0 android/PubnubUnitTest/.classpath
  2. +33 −0 android/PubnubUnitTest/.project
  3. +25 −0 android/PubnubUnitTest/AndroidManifest.xml
  4. +25 −0 android/PubnubUnitTest/bin/AndroidManifest.xml
  5. BIN  android/PubnubUnitTest/bin/PubnubUnitTest.apk
  6. BIN  android/PubnubUnitTest/bin/PubnubUnitTest_.apk
  7. BIN  android/PubnubUnitTest/bin/classes.dex
  8. +3 −0  android/PubnubUnitTest/bin/jarlist.cache
  9. BIN  android/PubnubUnitTest/bin/res/drawable-hdpi/ic_launcher.png
  10. BIN  android/PubnubUnitTest/bin/res/drawable-ldpi/ic_launcher.png
  11. BIN  android/PubnubUnitTest/bin/res/drawable-mdpi/ic_launcher.png
  12. BIN  android/PubnubUnitTest/bin/res/drawable-xhdpi/ic_launcher.png
  13. BIN  android/PubnubUnitTest/bin/resources.ap_
  14. +6 −0 android/PubnubUnitTest/gen/com/sample/pubnubunittest/gui/BuildConfig.java
  15. +35 −0 android/PubnubUnitTest/gen/com/sample/pubnubunittest/gui/R.java
  16. BIN  android/PubnubUnitTest/ic_launcher-web.png
  17. BIN  android/PubnubUnitTest/libs/PubnubCrypto.jar
  18. BIN  android/PubnubUnitTest/libs/android-support-v4.jar
  19. +5 −0 android/PubnubUnitTest/lint.xml
  20. +20 −0 android/PubnubUnitTest/proguard-project.txt
  21. +14 −0 android/PubnubUnitTest/project.properties
  22. BIN  android/PubnubUnitTest/res/drawable-hdpi/ic_launcher.png
  23. BIN  android/PubnubUnitTest/res/drawable-ldpi/ic_launcher.png
  24. BIN  android/PubnubUnitTest/res/drawable-mdpi/ic_launcher.png
  25. BIN  android/PubnubUnitTest/res/drawable-xhdpi/ic_launcher.png
  26. +13 −0 android/PubnubUnitTest/res/layout/activity_item_detail.xml
  27. +9 −0 android/PubnubUnitTest/res/layout/activity_item_list.xml
  28. +22 −0 android/PubnubUnitTest/res/layout/activity_item_twopane.xml
  29. +9 −0 android/PubnubUnitTest/res/layout/fragment_item_detail.xml
  30. +3 −0  android/PubnubUnitTest/res/values-large/refs.xml
  31. +3 −0  android/PubnubUnitTest/res/values-sw600dp/refs.xml
  32. +3 −0  android/PubnubUnitTest/res/values-v11/styles.xml
  33. +3 −0  android/PubnubUnitTest/res/values-v14/styles.xml
  34. +4 −0 android/PubnubUnitTest/res/values/strings.xml
  35. +3 −0  android/PubnubUnitTest/res/values/styles.xml
  36. +41 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemDetailActivity.java
  37. +95 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemDetailFragment.java
  38. +42 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemListActivity.java
  39. +96 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemListFragment.java
  40. +38 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/MenuItemContent.java
  41. +18 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/pubnub/Callback.java
  42. +849 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/pubnub/Pubnub.java
  43. +275 −0 android/PubnubUnitTest/src/com/sample/pubnubunittest/unittest/CL_155.java
View
8 android/PubnubUnitTest/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.LIBRARIES"/>
+ <classpathentry kind="output" path="bin/classes"/>
+</classpath>
View
33 android/PubnubUnitTest/.project
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>PubnubUnitTest</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ResourceManagerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.PreCompilerBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.jdt.core.javabuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>com.android.ide.eclipse.adt.ApkBuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>com.android.ide.eclipse.adt.AndroidNature</nature>
+ <nature>org.eclipse.jdt.core.javanature</nature>
+ </natures>
+</projectDescription>
View
25 android/PubnubUnitTest/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.sample.pubnubunittest.gui"
+ android:versionCode="1"
+ android:versionName="1.0" >
+ <uses-sdk
+ android:minSdkVersion="11"
+ android:targetSdkVersion="15" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <application
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity android:name=".ItemListActivity" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity android:name=".ItemDetailActivity" >
+ <meta-data
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value=".ItemListActivity" />
+ </activity>
+ </application>
+</manifest>
View
25 android/PubnubUnitTest/bin/AndroidManifest.xml
@@ -0,0 +1,25 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="com.sample.pubnubunittest.gui"
+ android:versionCode="1"
+ android:versionName="1.0" >
+ <uses-sdk
+ android:minSdkVersion="11"
+ android:targetSdkVersion="15" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <application
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ <activity android:name=".ItemListActivity" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ <activity android:name=".ItemDetailActivity" >
+ <meta-data
+ android:name="android.support.PARENT_ACTIVITY"
+ android:value=".ItemListActivity" />
+ </activity>
+ </application>
+</manifest>
View
BIN  android/PubnubUnitTest/bin/PubnubUnitTest.apk
Binary file not shown
View
BIN  android/PubnubUnitTest/bin/PubnubUnitTest_.apk
Binary file not shown
View
BIN  android/PubnubUnitTest/bin/classes.dex
Binary file not shown
View
3  android/PubnubUnitTest/bin/jarlist.cache
@@ -0,0 +1,3 @@
+# cache for current jar dependecy. DO NOT EDIT.
+# format is <lastModified> <length> <SHA-1> <path>
+# Encoding is UTF-8
View
BIN  android/PubnubUnitTest/bin/res/drawable-hdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/bin/res/drawable-ldpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/bin/res/drawable-mdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/bin/res/drawable-xhdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/bin/resources.ap_
Binary file not shown
View
6 android/PubnubUnitTest/gen/com/sample/pubnubunittest/gui/BuildConfig.java
@@ -0,0 +1,6 @@
+/** Automatically generated file. DO NOT MODIFY */
+package com.sample.pubnubunittest.gui;
+
+public final class BuildConfig {
+ public final static boolean DEBUG = true;
+}
View
35 android/PubnubUnitTest/gen/com/sample/pubnubunittest/gui/R.java
@@ -0,0 +1,35 @@
+/* AUTO-GENERATED FILE. DO NOT MODIFY.
+ *
+ * This class was automatically generated by the
+ * aapt tool from the resource data it found. It
+ * should not be modified by hand.
+ */
+
+package com.sample.pubnubunittest.gui;
+
+public final class R {
+ public static final class attr {
+ }
+ public static final class drawable {
+ public static final int ic_launcher=0x7f020000;
+ }
+ public static final class id {
+ public static final int item_detail=0x7f060003;
+ public static final int item_detail_container=0x7f060001;
+ public static final int item_list=0x7f060002;
+ public static final int scrollView1=0x7f060000;
+ }
+ public static final class layout {
+ public static final int activity_item_detail=0x7f030000;
+ public static final int activity_item_list=0x7f030001;
+ public static final int activity_item_twopane=0x7f030002;
+ public static final int fragment_item_detail=0x7f030003;
+ }
+ public static final class string {
+ public static final int app_name=0x7f040000;
+ public static final int title_item_list=0x7f040001;
+ }
+ public static final class style {
+ public static final int AppTheme=0x7f050000;
+ }
+}
View
BIN  android/PubnubUnitTest/ic_launcher-web.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/libs/PubnubCrypto.jar
Binary file not shown
View
BIN  android/PubnubUnitTest/libs/android-support-v4.jar
Binary file not shown
View
5 android/PubnubUnitTest/lint.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<lint>
+ <issue id="HandlerLeak" severity="ignore" />
+ <issue id="ParserError" severity="ignore" />
+</lint>
View
20 android/PubnubUnitTest/proguard-project.txt
@@ -0,0 +1,20 @@
+# To enable ProGuard in your project, edit project.properties
+# to define the proguard.config property as described in that file.
+#
+# Add project specific ProGuard rules here.
+# By default, the flags in this file are appended to flags specified
+# in ${sdk.dir}/tools/proguard/proguard-android.txt
+# You can edit the include path and order by changing the ProGuard
+# include property in project.properties.
+#
+# For more details, see
+# http://developer.android.com/guide/developing/tools/proguard.html
+
+# Add any project specific keep options here:
+
+# If your project uses WebView with JS, uncomment the following
+# and specify the fully qualified class name to the JavaScript interface
+# class:
+#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
+# public *;
+#}
View
14 android/PubnubUnitTest/project.properties
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system edit
+# "ant.properties", and override values to adapt the script to your
+# project structure.
+#
+# To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home):
+#proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
+
+# Project target.
+target=android-16
View
BIN  android/PubnubUnitTest/res/drawable-hdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/res/drawable-ldpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/res/drawable-mdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
BIN  android/PubnubUnitTest/res/drawable-xhdpi/ic_launcher.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
View
13 android/PubnubUnitTest/res/layout/activity_item_detail.xml
@@ -0,0 +1,13 @@
+<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
+ android:id="@+id/scrollView1"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent" >
+ <FrameLayout
+ xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:id="@+id/item_detail_container"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ tools:context=".ItemDetailActivity" >
+ </FrameLayout>
+</ScrollView>
View
9 android/PubnubUnitTest/res/layout/activity_item_list.xml
@@ -0,0 +1,9 @@
+<fragment xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:id="@+id/item_list"
+ android:name="com.sample.pubnubunittest.gui.ItemListFragment"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_marginLeft="16dp"
+ android:layout_marginRight="16dp"
+ tools:context=".ItemListActivity" />
View
22 android/PubnubUnitTest/res/layout/activity_item_twopane.xml
@@ -0,0 +1,22 @@
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:layout_marginLeft="16dp"
+ android:layout_marginRight="16dp"
+ android:divider="?android:attr/dividerHorizontal"
+ android:orientation="horizontal"
+ android:showDividers="middle"
+ tools:context=".ItemListActivity" >
+ <fragment
+ android:id="@+id/item_list"
+ android:name="com.sample.pubnubunittest.gui.ItemListFragment"
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="1" />
+ <FrameLayout
+ android:id="@+id/item_detail_container"
+ android:layout_width="0dp"
+ android:layout_height="match_parent"
+ android:layout_weight="3" />
+</LinearLayout>
View
9 android/PubnubUnitTest/res/layout/fragment_item_detail.xml
@@ -0,0 +1,9 @@
+<TextView xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:id="@+id/item_detail"
+ style="?android:attr/textAppearanceLarge"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:padding="16dp"
+ android:textSize="12sp"
+ tools:context=".ItemDetailFragment" />
View
3  android/PubnubUnitTest/res/values-large/refs.xml
@@ -0,0 +1,3 @@
+<resources>
+ <item type="layout" name="activity_item_list">@layout/activity_item_twopane</item>
+</resources>
View
3  android/PubnubUnitTest/res/values-sw600dp/refs.xml
@@ -0,0 +1,3 @@
+<resources>
+ <item type="layout" name="activity_item_list">@layout/activity_item_twopane</item>
+</resources>
View
3  android/PubnubUnitTest/res/values-v11/styles.xml
@@ -0,0 +1,3 @@
+<resources>
+ <style name="AppTheme" parent="android:Theme.Holo.Light" />
+</resources>
View
3  android/PubnubUnitTest/res/values-v14/styles.xml
@@ -0,0 +1,3 @@
+<resources>
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar" />
+</resources>
View
4 android/PubnubUnitTest/res/values/strings.xml
@@ -0,0 +1,4 @@
+<resources>
+ <string name="app_name">PubnubUnitTest</string>
+ <string name="title_item_list">Items</string>
+</resources>
View
3  android/PubnubUnitTest/res/values/styles.xml
@@ -0,0 +1,3 @@
+<resources>
+ <style name="AppTheme" parent="android:Theme.Light" />
+</resources>
View
41 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemDetailActivity.java
@@ -0,0 +1,41 @@
+package com.sample.pubnubunittest.gui;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.v4.app.FragmentActivity;
+import android.support.v4.app.NavUtils;
+import android.view.MenuItem;
+
+public class ItemDetailActivity extends FragmentActivity {
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_item_detail);
+
+ getActionBar().setDisplayHomeAsUpEnabled(true);
+
+ if (savedInstanceState == null) {
+ Bundle arguments = new Bundle();
+ arguments.putString(ItemDetailFragment.ARG_ITEM_ID,
+ getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID));
+ ItemDetailFragment fragment = new ItemDetailFragment();
+ fragment.setArguments(arguments);
+ getSupportFragmentManager().beginTransaction()
+ .add(R.id.item_detail_container, fragment)
+ .commit();
+ }
+
+ setTitle(""+MenuItemContent.ITEM_MAP.get(getIntent().getStringExtra(ItemDetailFragment.ARG_ITEM_ID)));
+ }
+
+ @Override
+ public boolean onOptionsItemSelected(MenuItem item) {
+ if (item.getItemId() == android.R.id.home) {
+ NavUtils.navigateUpTo(this, new Intent(this, ItemListActivity.class));
+ return true;
+ }
+
+ return super.onOptionsItemSelected(item);
+ }
+}
View
95 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemDetailFragment.java
@@ -0,0 +1,95 @@
+package com.sample.pubnubunittest.gui;
+
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.TextView;
+
+import com.sample.pubnubunittest.unittest.CL_155;
+
+public class ItemDetailFragment extends Fragment {
+
+ public static final String ARG_ITEM_ID = "item_id";
+ UnitTestExicute exicute=null;
+ MenuItemContent.MenuItem mItem;
+ TextView text;
+ public ItemDetailFragment() {
+ }
+
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ if (getArguments().containsKey(ARG_ITEM_ID)) {
+ mItem = MenuItemContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
+
+ }
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container,
+ Bundle savedInstanceState) {
+ View rootView = inflater.inflate(R.layout.fragment_item_detail, container, false);
+ if (mItem != null) {
+ text= (TextView) rootView.findViewById(R.id.item_detail);
+ exicute= new UnitTestExicute();
+ exicute.execute(mItem.id+"");
+ }
+ return rootView;
+ }
+
+ Handler handler= new Handler()
+ {
+ @Override
+ public void handleMessage(Message msg) {
+ // TODO Auto-generated method stub
+ super.handleMessage(msg);
+ String message=msg.getData().getString("MESSAGE");
+ text.setText(text.getText()+"\n"+message);
+ }
+
+ };
+ public void onDestroy() {
+
+ if(exicute !=null)
+ {
+ exicute.cancel(true);
+ }
+ super.onDestroy();
+ };
+
+ class UnitTestExicute extends AsyncTask<String, Void, Boolean> {
+
+ @Override
+ protected Boolean doInBackground(String... params) {
+
+ int id=Integer.parseInt(params[0]);
+
+ switch (id) {
+ case 1:
+ CL_155 ut= new CL_155();
+ ut.RunUnitTest(handler);
+ break;
+
+ default:
+ break;
+ }
+
+
+ return Boolean.TRUE;
+ }
+
+ @Override
+ protected void onPreExecute() {
+ }
+
+ protected void onPostExecute(Boolean result) {
+ }
+ }
+
+}
View
42 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemListActivity.java
@@ -0,0 +1,42 @@
+package com.sample.pubnubunittest.gui;
+
+import android.content.Intent;
+import android.os.Bundle;
+import android.support.v4.app.FragmentActivity;
+
+public class ItemListActivity extends FragmentActivity
+ implements ItemListFragment.IemListCallbacks {
+
+ private boolean mTwoPane;
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_item_list);
+
+ if (findViewById(R.id.item_detail_container) != null) {
+ mTwoPane = true;
+ ((ItemListFragment) getSupportFragmentManager()
+ .findFragmentById(R.id.item_list))
+ .setActivateOnItemClick(true);
+ }
+ }
+
+ @Override
+ public void onItemSelected(String id) {
+ if (mTwoPane) {
+ Bundle arguments = new Bundle();
+ arguments.putString(ItemDetailFragment.ARG_ITEM_ID, id);
+ ItemDetailFragment fragment = new ItemDetailFragment();
+ fragment.setArguments(arguments);
+ getSupportFragmentManager().beginTransaction()
+ .replace(R.id.item_detail_container, fragment)
+ .commit();
+
+ } else {
+ Intent detailIntent = new Intent(this, ItemDetailActivity.class);
+ detailIntent.putExtra(ItemDetailFragment.ARG_ITEM_ID, id);
+ startActivity(detailIntent);
+ }
+ }
+}
View
96 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/ItemListFragment.java
@@ -0,0 +1,96 @@
+package com.sample.pubnubunittest.gui;
+
+
+import android.R;
+import android.app.Activity;
+import android.os.Bundle;
+import android.support.v4.app.ListFragment;
+import android.view.View;
+import android.widget.ArrayAdapter;
+import android.widget.ListView;
+
+public class ItemListFragment extends ListFragment {
+
+ private static final String STATE_ACTIVATED_POSITION = "activated_position";
+
+ private IemListCallbacks mCallbacks = sDummyCallbacks;
+ private int mActivatedPosition = ListView.INVALID_POSITION;
+
+ public interface IemListCallbacks {
+
+ public void onItemSelected(String id);
+ }
+
+ private static IemListCallbacks sDummyCallbacks = new IemListCallbacks() {
+ @Override
+ public void onItemSelected(String id) {
+ }
+ };
+
+ public ItemListFragment() {
+ }
+
+ @Override
+ public void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setListAdapter(new ArrayAdapter<MenuItemContent.MenuItem>(getActivity(),
+ R.layout.simple_list_item_activated_1,
+ R.id.text1,
+ MenuItemContent.ITEMS));
+ }
+
+ @Override
+ public void onViewCreated(View view, Bundle savedInstanceState) {
+ super.onViewCreated(view, savedInstanceState);
+ if (savedInstanceState != null && savedInstanceState
+ .containsKey(STATE_ACTIVATED_POSITION)) {
+ setActivatedPosition(savedInstanceState.getInt(STATE_ACTIVATED_POSITION));
+ }
+ }
+
+ @Override
+ public void onAttach(Activity activity) {
+ super.onAttach(activity);
+ if (!(activity instanceof IemListCallbacks)) {
+ throw new IllegalStateException("Activity must implement fragment's callbacks.");
+ }
+
+ mCallbacks = (IemListCallbacks) activity;
+ }
+
+ @Override
+ public void onDetach() {
+ super.onDetach();
+ mCallbacks = sDummyCallbacks;
+ }
+
+ @Override
+ public void onListItemClick(ListView listView, View view, int position, long id) {
+ super.onListItemClick(listView, view, position, id);
+ mCallbacks.onItemSelected(MenuItemContent.ITEMS.get(position).id);
+ }
+
+ @Override
+ public void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ if (mActivatedPosition != ListView.INVALID_POSITION) {
+ outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition);
+ }
+ }
+
+ public void setActivateOnItemClick(boolean activateOnItemClick) {
+ getListView().setChoiceMode(activateOnItemClick
+ ? ListView.CHOICE_MODE_SINGLE
+ : ListView.CHOICE_MODE_NONE);
+ }
+
+ public void setActivatedPosition(int position) {
+ if (position == ListView.INVALID_POSITION) {
+ getListView().setItemChecked(mActivatedPosition, false);
+ } else {
+ getListView().setItemChecked(position, true);
+ }
+
+ mActivatedPosition = position;
+ }
+}
View
38 android/PubnubUnitTest/src/com/sample/pubnubunittest/gui/MenuItemContent.java
@@ -0,0 +1,38 @@
+package com.sample.pubnubunittest.gui;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class MenuItemContent {
+
+ public static class MenuItem {
+
+ public String id;
+ public String content;
+
+ public MenuItem(String id, String content) {
+ this.id = id;
+ this.content = content;
+ }
+
+ @Override
+ public String toString() {
+ return content;
+ }
+ }
+
+ public static List<MenuItem> ITEMS = new ArrayList<MenuItem>();
+ public static Map<String, MenuItem> ITEM_MAP = new HashMap<String, MenuItem>();
+
+ static {
+ addItem(new MenuItem("1", "CL-155"));
+
+ }
+
+ private static void addItem(MenuItem item) {
+ ITEMS.add(item);
+ ITEM_MAP.put(item.id, item);
+ }
+}
View
18 android/PubnubUnitTest/src/com/sample/pubnubunittest/pubnub/Callback.java
@@ -0,0 +1,18 @@
+package com.sample.pubnubunittest.pubnub;
+
+
+
+public interface Callback {
+
+ public abstract boolean subscribeCallback(String channel, Object message);
+
+ public abstract boolean presenceCallback(String channel, Object message);
+
+ public abstract void errorCallback(String channel, Object message);
+
+ public abstract void connectCallback(String channel);
+
+ public abstract void reconnectCallback(String channel);
+
+ public abstract void disconnectCallback(String channel);
+}
View
849 android/PubnubUnitTest/src/com/sample/pubnubunittest/pubnub/Pubnub.java
@@ -0,0 +1,849 @@
+package com.sample.pubnubunittest.pubnub;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+import java.util.concurrent.FutureTask;
+import java.util.zip.GZIPInputStream;
+
+import org.apache.http.Header;
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpResponse;
+import org.apache.http.client.HttpClient;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpUriRequest;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.params.BasicHttpParams;
+import org.apache.http.params.HttpConnectionParams;
+import org.apache.http.params.HttpParams;
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import pubnub.PubnubCrypto;
+import android.util.Log;
+
+/**
+ * PubNub 3.3 Real-time Push Cloud API
+ *
+ * @author Stephen Blum
+ * @package pubnub
+ */
+public class Pubnub {
+ private String ORIGIN = "pubsub.pubnub.com";
+ private String PUBLISH_KEY = "";
+ private String SUBSCRIBE_KEY = "";
+ private String SECRET_KEY = "";
+ private String CIPHER_KEY = "";
+ private boolean SSL = false;
+ private String UUIDs = null;
+
+ private class ChannelStatus {
+ String channel;
+ boolean connected, first;
+ }
+
+ private List<ChannelStatus> subscriptions;
+
+ /**
+ * PubNub 3.2 with Presence
+ *
+ * Prepare PubNub State.
+ *
+ * @param String
+ * Publish Key.
+ * @param String
+ * Subscribe Key.
+ * @param String
+ * Secret Key.
+ * @param String
+ * Cipher Key.
+ * @param boolean SSL Enabled.
+ */
+ public Pubnub(String publish_key, String subscribe_key, String secret_key,
+ String cipher_key, boolean ssl_on) {
+ this.init(publish_key, subscribe_key, secret_key, cipher_key, ssl_on);
+ }
+
+ /**
+ * PubNub 3.0 Compatibility
+ *
+ * Prepare PubNub Class State.
+ *
+ * @param String
+ * Publish Key.
+ * @param String
+ * Subscribe Key.
+ * @param String
+ * Secret Key.
+ * @param boolean SSL Enabled.
+ */
+ public Pubnub(String publish_key, String subscribe_key, String secret_key,
+ boolean ssl_on) {
+ this.init(publish_key, subscribe_key, secret_key, "", ssl_on);
+ }
+
+ /**
+ * PubNub 2.0 Compatibility
+ *
+ * Prepare PubNub Class State.
+ *
+ * @param String
+ * Publish Key.
+ * @param String
+ * Subscribe Key.
+ */
+ public Pubnub(String publish_key, String subscribe_key) {
+ this.init(publish_key, subscribe_key, "", "", false);
+ }
+
+ /**
+ * PubNub 3.0 without SSL
+ *
+ * Prepare PubNub Class State.
+ *
+ * @param String
+ * Publish Key.
+ * @param String
+ * Subscribe Key.
+ * @param String
+ * Secret Key.
+ */
+ public Pubnub(String publish_key, String subscribe_key, String secret_key) {
+ this.init(publish_key, subscribe_key, secret_key, "", false);
+ }
+
+ /**
+ * Init
+ *
+ * Prepare PubNub Class State.
+ *
+ * @param String
+ * Publish Key.
+ * @param String
+ * Subscribe Key.
+ * @param String
+ * Secret Key.
+ * @param String
+ * Cipher Key.
+ * @param boolean SSL Enabled.
+ */
+ public void init(String publish_key, String subscribe_key,
+ String secret_key, String cipher_key, boolean ssl_on) {
+ this.PUBLISH_KEY = publish_key;
+ this.SUBSCRIBE_KEY = subscribe_key;
+ this.SECRET_KEY = secret_key;
+ this.CIPHER_KEY = cipher_key;
+ this.SSL = ssl_on;
+
+ // SSL On?
+ if (this.SSL) {
+ this.ORIGIN = "https://" + this.ORIGIN;
+ } else {
+ this.ORIGIN = "http://" + this.ORIGIN;
+ }
+ UUIDs = uuid();
+ }
+
+ /**
+ * Publish
+ *
+ * Send a message to a channel.
+ *
+ * @param String channel name.
+ * @param JSONObject message.
+ * @return JSONArray
+ */
+ public JSONArray publish(String channel, JSONObject message) {
+ HashMap<String, Object> args = new HashMap<String, Object>(2);
+ args.put("channel", channel);
+ args.put("message", message);
+ return publish(args);
+ }
+
+ /**
+ * Publish
+ *
+ * Send a message to a channel.
+ *
+ * @param HashMap
+ * <String, Object> containing channel name, message.
+ * @return JSONArray.
+ */
+ public JSONArray publish(HashMap<String, Object> args) {
+
+ String channel = (String) args.get("channel");
+ Object message = args.get("message");
+
+ if (message instanceof JSONObject) {
+ JSONObject obj = (JSONObject) message;
+ if (this.CIPHER_KEY.length() > 0) {
+ // Encrypt Message
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ message = pc.encrypt(obj);
+ } else {
+ message = obj;
+ }
+
+ } else if (message instanceof String) {
+ String obj = (String) message;
+ if (this.CIPHER_KEY.length() > 0) {
+ // Encrypt Message
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ try {
+ message = pc.encrypt(obj);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ } else {
+ message = obj;
+ }
+ message = "\"" + message + "\"";
+
+ } else if (message instanceof JSONArray) {
+ JSONArray obj = (JSONArray) message;
+
+ if (this.CIPHER_KEY.length() > 0) {
+ // Encrypt Message
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ message = pc.encryptJSONArray(obj);
+ } else {
+ message = obj;
+ }
+ }
+ System.out.println();
+
+ // Generate String to Sign
+ String signature = "0";
+
+ if (this.SECRET_KEY.length() > 0) {
+ StringBuilder string_to_sign = new StringBuilder();
+ string_to_sign.append(this.PUBLISH_KEY).append('/')
+ .append(this.SUBSCRIBE_KEY).append('/')
+ .append(this.SECRET_KEY).append('/').append(channel)
+ .append('/').append(message.toString());
+
+ // Sign Message
+ signature = PubnubCrypto.getHMacSHA256(this.SECRET_KEY,
+ string_to_sign.toString());
+ }
+
+ // Build URL
+ List<String> url = new ArrayList<String>();
+ url.add("publish");
+ url.add(this.PUBLISH_KEY);
+ url.add(this.SUBSCRIBE_KEY);
+ url.add(signature);
+ url.add(channel);
+ url.add("0");
+ url.add(message.toString());
+
+ // Return JSONArray
+ return _request(url);
+ }
+
+ /**
+ * Subscribe
+ *
+ * Listen for a message on a channel.
+ *
+ * @param String
+ * channel name.
+ * @param Callback
+ * function callback.
+ */
+ public void subscribe(String channel, Callback callback) {
+ HashMap<String, Object> args = new HashMap<String, Object>(2);
+ args.put("channel", channel);
+ args.put("callback", callback);
+ subscribe(args);
+ }
+
+ /**
+ * Subscribe
+ *
+ * Listen for a message on a channel.
+ *
+ * @param HashMap
+ * <String, Object> containing channel name, function callback.
+ */
+ public void subscribe(HashMap<String, Object> args) {
+ args.put("timetoken", "0");
+ this._subscribe(args);
+ }
+
+ /**
+ * Subscribe - Private Interface
+ *
+ * Patch provided by petereddy on GitHub
+ *
+ * @param HashMap
+ * <String, Object> containing channel name, function callback,
+ * timetoken.
+ */
+ private void _subscribe(HashMap<String, Object> args) {
+
+ String channel = (String) args.get("channel");
+ String timetoken = (String) args.get("timetoken");
+ Callback callback;
+
+ // Validate Arguments
+ if (args.get("callback") != null) {
+ callback = (Callback) args.get("callback");
+ } else {
+ System.out.println("Invalid Callback.");
+ return;
+ }
+
+ if (channel == null || channel.equals("")) {
+ callback.errorCallback(channel, "Invalid Channel.");
+ return;
+ }
+
+ // Ensure Single Connection
+ if (subscriptions != null && subscriptions.size() > 0) {
+ boolean channel_exist = false;
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel)) {
+ channel_exist = true;
+ break;
+ }
+ }
+ if (!channel_exist) {
+ ChannelStatus cs = new ChannelStatus();
+ cs.channel = channel;
+ cs.connected = true;
+ subscriptions.add(cs);
+ } else {
+ callback.errorCallback(channel, "Already Connected");
+ return;
+ }
+ } else {
+ // New Channel
+ ChannelStatus cs = new ChannelStatus();
+ cs.channel = channel;
+ cs.connected = true;
+ subscriptions = new ArrayList<Pubnub.ChannelStatus>();
+ subscriptions.add(cs);
+ }
+
+ while (true) {
+ try {
+ // Build URL
+ List<String> url = java.util.Arrays.asList("subscribe",
+ this.SUBSCRIBE_KEY, channel, "0", timetoken);
+
+ // Stop Connection?
+ boolean isDisconnected = false;
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel)) {
+ if (!it.connected) {
+ callback.disconnectCallback(channel);
+ isDisconnected = true;
+ subscriptions.remove(it);
+ break;
+ }
+ }
+ }
+ if (isDisconnected)
+ return;
+
+ // Wait for Message
+ JSONArray response = _request(url);
+
+ // Stop Connection?
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel)) {
+ if (!it.connected) {
+ callback.disconnectCallback(channel);
+ isDisconnected = true;
+ subscriptions.remove(it);
+ break;
+ }
+ }
+ }
+
+ if (isDisconnected)
+ return;
+
+ // Problem?
+ if (response == null || response.optInt(1) == 0) {
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel)) {
+ if (it.connected && it.first) {
+ subscriptions.remove(it);
+ callback.disconnectCallback(channel);
+ } else {
+ subscriptions.remove(it);
+ callback.errorCallback(channel,
+ "No Network Connection");
+ }
+ break;
+ }
+ }
+ // Ensure Connected (Call Time Function)
+ boolean isReconnected = false;
+ while (true) {
+ double time_token = this.time();
+ if (time_token == 0.0) {
+
+ Thread.sleep(5000);
+ } else {
+ // Reconnect Callback
+ callback.reconnectCallback(channel);
+ isReconnected = true;
+ break;
+ }
+ }
+ if (isReconnected) {
+ continue;
+ }
+
+ } else {
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel)) {
+ // Connect Callback
+ if (!it.first) {
+ it.first = true;
+ callback.connectCallback(channel);
+
+ break;
+ }
+ }
+ }
+ }
+
+ JSONArray messages = response.optJSONArray(0);
+
+ // Update TimeToken
+ if (response.optString(1).length() > 0)
+ timetoken = response.optString(1);
+
+ for (int i = 0; messages.length() > i; i++) {
+ JSONObject message = messages.optJSONObject(i);
+ if (message != null) {
+
+ if (this.CIPHER_KEY.length() > 0) {
+ // Decrypt Message
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ message = pc.decrypt(message);
+ }
+ if (callback != null)
+ callback.subscribeCallback(channel, message);
+ } else {
+
+ JSONArray arr = messages.optJSONArray(i);
+ if (arr != null) {
+ if (this.CIPHER_KEY.length() > 0) {
+ PubnubCrypto pc = new PubnubCrypto(
+ this.CIPHER_KEY);
+ arr = pc.decryptJSONArray(arr);
+ ;
+ }
+ if (callback != null)
+ callback.subscribeCallback(channel, arr);
+ } else {
+ String msgs = messages.getString(0);
+ if (this.CIPHER_KEY.length() > 0) {
+ PubnubCrypto pc = new PubnubCrypto(
+ this.CIPHER_KEY);
+ msgs = pc.decrypt(msgs);
+ }
+ if (callback != null)
+ callback.subscribeCallback(channel, msgs);
+ }
+ }
+ }
+ } catch (Exception e) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ie) {
+ }
+ }
+ }
+ }
+
+ /**
+ * History
+ *
+ * Load history from a channel.
+ *
+ * @param String
+ * channel name.
+ * @param int limit history count response.
+ * @return JSONArray of history.
+ */
+ public JSONArray history(String channel, int limit) {
+ HashMap<String, Object> args = new HashMap<String, Object>(2);
+ args.put("channel", channel);
+ args.put("limit", limit);
+ return history(args);
+ }
+
+ /**
+ * Detailed History
+ *
+ * Load Detailed history from a channel.
+ *
+ * @param HashMap
+ * <String, Object> containing channel name, with optional:
+ * 'start', 'end', 'reverse', 'count'.
+ * @return JSONArray of history.
+ */
+ public JSONArray detailedHistory(HashMap<String, Object> args) {
+
+ String channel = (String) args.get("channel");
+
+ if (channel == null || channel.equals("")) {
+
+ System.out.println("Missing Channel");
+ }
+
+ StringBuilder parameter = new StringBuilder("?");
+ int count = 100;
+
+ if (args.get("count") != null) {
+ count = (Integer) args.get("count");
+ }
+
+ parameter.append("count="+count);
+
+ if (args.get("reverse") != null) {
+ boolean reverse = (Boolean) args.get("reverse");
+ if (reverse)
+ parameter.append("&reverse=true");
+ else
+ parameter.append("&reverse=false");
+ }
+
+ if (args.get("start") != null) {
+ parameter.append("&start=").append((String) args.get("start"));
+ }
+
+ if (args.get("end") != null) {
+ parameter.append("&end=").append((String) args.get("end"));
+ }
+
+ List<String> url = new ArrayList<String>();
+ url.add("v2");
+ url.add("history");
+ url.add("sub-key");
+ url.add(this.SUBSCRIBE_KEY);
+ url.add("channel");
+ url.add(channel);
+ url.add(parameter.toString());
+ JSONArray responce = _request(url);
+
+ if (this.CIPHER_KEY.length() > 0) {
+
+ try {
+ JSONArray messageArray = responce.getJSONArray(0);
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ messageArray = pc.decryptJSONArray(messageArray);
+ responce.put(0, messageArray);
+ } catch (JSONException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ // Decrpyt Messages
+
+ return responce;
+ } else {
+ return _request(url);
+ }
+ }
+
+ /**
+ * History
+ *
+ * Load history from a channel.
+ *
+ * @param HashMap
+ * <String, Object> containing channel name, limit history count
+ * response.
+ * @return JSONArray of history.
+ */
+ public JSONArray history(HashMap<String, Object> args) {
+
+ String channel = (String) args.get("channel");
+ int limit = Integer.parseInt(args.get("limit").toString());
+
+ List<String> url = new ArrayList<String>();
+
+ url.add("history");
+ url.add(this.SUBSCRIBE_KEY);
+ url.add(channel);
+ url.add("0");
+ url.add(Integer.toString(limit));
+
+ if (this.CIPHER_KEY.length() > 0) {
+ // Decrpyt Messages
+ PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
+ return pc.decryptJSONArray(_request(url));
+ } else {
+ return _request(url);
+ }
+ }
+
+ /**
+ * Here Now
+ *
+ * Load current occupancy from a channel
+ *
+ * @param HashMap
+ * <String, Object> args with channel.
+ */
+ public JSONArray here_now(HashMap<String, Object> args) {
+ String channel = (String) args.get("channel");
+ // Validate Arguments
+
+ if (channel == null || channel.equals("")) {
+ JSONArray jsono = new JSONArray();
+ try {
+ jsono.put(0);
+ jsono.put("Missing Channel");
+ } catch (Exception jsone) {
+ }
+ return jsono;
+ }
+
+ // Build URL
+ List<String> url = new ArrayList<String>();
+ url.add("v2");
+ url.add("presence");
+ url.add("sub_key");
+ url.add(this.SUBSCRIBE_KEY);
+ url.add("channel");
+ url.add(channel);
+
+ // Return JSONArray
+ return _request(url);
+
+ }
+
+ /**
+ * Time
+ *
+ * Timestamp from PubNub Cloud.
+ *
+ * @return double timestamp.
+ */
+ public double time() {
+ List<String> url = new ArrayList<String>();
+
+ url.add("time");
+ url.add("0");
+
+ JSONArray response = _request(url);
+ return response.optDouble(0);
+ }
+
+ /**
+ * UUID
+ *
+ * 32 digit UUID generation at client side.
+ *
+ * @return String uuid.
+ */
+ public static String uuid() {
+ UUID uuid = UUID.randomUUID();
+ return uuid.toString();
+ }
+
+ /**
+ * Unsubscribe
+ *
+ * Unsubscribe/Disconnect to channel.
+ *
+ * @param HashMap
+ * <String, Object> containing channel name.
+ */
+ public void unsubscribe(HashMap<String, Object> args) {
+ String channel = (String) args.get("channel");
+ for (ChannelStatus it : subscriptions) {
+ if (it.channel.equals(channel) && it.connected) {
+ it.connected = false;
+ it.first = false;
+ break;
+ }
+ }
+ }
+
+ /**
+ * Request URL
+ *
+ * @param List
+ * <String> request of url directories.
+ * @return JSONArray from JSON response.
+ */
+ private JSONArray _request(List<String> url_components) {
+ String json = "";
+ StringBuilder url = new StringBuilder();
+ Iterator<String> url_iterator = url_components.iterator();
+ String _callFor = url_components.get(0);
+
+ if (_callFor.equalsIgnoreCase("v2")) {
+ _callFor = url_components.get(1);
+ }
+
+ url.append(this.ORIGIN);
+
+ // Generate URL with UTF-8 Encoding
+ while (url_iterator.hasNext()) {
+ try {
+ String url_bit = (String) url_iterator.next();
+ if(url_bit.startsWith("?"))
+ {
+ url.append(url_bit);
+ }else
+ {
+ url.append("/").append(_encodeToUTF8(url_bit));
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ JSONArray jsono = new JSONArray();
+ try {
+ jsono.put(0);
+ jsono.put("Failed UTF-8 Encoding URL.");
+ } catch (Exception jsone) {
+ }
+ return jsono;
+ }
+ }
+ if (_callFor.equalsIgnoreCase("subscribe")) {
+ url.append("/").append("?uuid=" + UUIDs);
+ }
+ try {
+
+ PubnubHttpRequest request = new PubnubHttpRequest(url.toString());
+ FutureTask<String> task = new FutureTask<String>(request);
+ Thread t = new Thread(task);
+ t.start();
+ try {
+ json = task.get();
+ } catch (Exception e) {
+ JSONArray jsono = new JSONArray();
+
+ try {
+ jsono.put(0);
+ jsono.put("Request failed due to missing Internet connection.");
+ } catch (Exception jsone) {
+ }
+
+ System.out.println(e.getMessage());
+
+ return jsono;
+ }
+
+ } catch (Exception e) {
+
+ JSONArray jsono = new JSONArray();
+
+ try {
+ jsono.put(0);
+ jsono.put("Failed JSONP HTTP Request.");
+ } catch (Exception jsone) {
+ }
+
+ System.out.println(e.getMessage());
+
+ return jsono;
+ }
+ if (_callFor.equalsIgnoreCase("presence")) {
+ try {
+ JSONArray arr = new JSONArray();
+
+ arr.put(new JSONObject(json));
+
+ json = arr.toString();
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+ // Parse JSON String
+ try {
+ return new JSONArray(json);
+ } catch (Exception e) {
+ JSONArray jsono = new JSONArray();
+
+ try {
+ jsono.put(0);
+ jsono.put("Failed JSON Parsing.");
+ } catch (Exception jsone) {
+ }
+
+ System.out.println(e.getMessage());
+
+ // Return Failure to Parse
+ return jsono;
+ }
+ }
+
+ private class PubnubHttpRequest implements Callable<String> {
+
+ String url;
+
+ public PubnubHttpRequest(String url) {
+ this.url = url;
+ }
+
+ @Override
+ public String call() throws Exception {
+ // Prepare request
+ String line = "", json = "";
+ HttpParams httpParams = new BasicHttpParams();
+ HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
+ HttpConnectionParams.setSoTimeout(httpParams, 310000);
+ HttpClient httpclient = new DefaultHttpClient(httpParams);
+ HttpUriRequest request = new HttpGet(url);
+ request.setHeader("V", "3.3");
+ request.setHeader("User-Agent", "Java-Android");
+ request.setHeader("Accept-Encoding", "gzip");
+
+ // Execute request
+ HttpResponse response;
+ response = httpclient.execute(request);
+
+ HttpEntity entity = response.getEntity();
+ if (entity != null) {
+
+ // A Simple JSON Response Read
+ InputStream instream = entity.getContent();
+ BufferedReader reader = null;
+
+ // Gzip decoding
+ Header contentEncoding = response
+ .getFirstHeader("Content-Encoding");
+ if (contentEncoding != null
+ && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
+ reader = new BufferedReader(new InputStreamReader(
+ new GZIPInputStream(instream)));
+ } else {
+ reader = new BufferedReader(new InputStreamReader(instream));
+ }
+
+ // Read JSON Message
+ while ((line = reader.readLine()) != null) {
+ json += line;
+ }
+ reader.close();
+ }
+
+ return json;
+ }
+ }
+
+ private String _encodeToUTF8(String s) throws UnsupportedEncodingException {
+ String enc = URLEncoder.encode(s, "UTF-8").replace("+", "%20");
+ return enc;
+ }
+}
View
275 android/PubnubUnitTest/src/com/sample/pubnubunittest/unittest/CL_155.java
@@ -0,0 +1,275 @@
+package com.sample.pubnubunittest.unittest;
+
+import java.math.BigDecimal;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import android.os.Bundle;
+import android.os.Handler;
+import android.os.Message;
+import android.util.Log;
+
+import com.sample.pubnubunittest.pubnub.Pubnub;
+
+/**
+ * Unit test for detailed history
+ *
+ *
+ */
+ public class CL_155 {
+
+ String publish_key = "demo";
+ String subscribe_key = "demo";
+ String secret_key = "demo";
+ boolean ssl_on = false;
+ Pubnub pubnub = new Pubnub(publish_key, subscribe_key, secret_key, ssl_on);
+ String crazy = " ~`!@#$%^&*(???)+=[]\\{}|;\':,./<>?abcd";
+ String channel;
+
+ int total_msg = 10;
+ ArrayList<HashMap<String, Object>> inputs = new ArrayList<HashMap<String, Object>>();
+ String starttime = null;
+ String endtime = null;
+ String midtime = null;
+
+
+ Handler mHandler= null;
+
+ public void RunUnitTest( Handler handler) {
+ mHandler=handler;
+ pubnub = new Pubnub(publish_key, subscribe_key, secret_key, ssl_on);
+ channel = getBigDecimal(pubnub.time());
+ Log.e("Message",
+ "Setting up context for Detailed History tests. Please wait ...");
+ PrintLog("Setting up context for Detailed History tests. Please wait ...");
+ starttime = getBigDecimal(pubnub.time());
+ PublishMessage(0, total_msg / 2, 0);
+ midtime = getBigDecimal(pubnub.time());
+ PublishMessage(0, total_msg / 2, total_msg / 2);
+ endtime = getBigDecimal(pubnub.time());
+ Log.e("Messahe",
+ "Context setup for Detailed History tests. Now running tests");
+ PrintLog("Context setup for Detailed History tests. Now running tests");
+ test_begin_to_end_count();
+ test_end_to_begin_count();
+ test_start_reverse_true();
+
+ test_start_reverse_false();
+ test_end_reverse_true();
+ test_end_reverse_false();
+ test_count_zero();
+ test_count();
+ }
+
+ private String getBigDecimal(double time) {
+
+ BigDecimal big = new BigDecimal(time);
+ return big.toString();
+ }
+
+ private void PrintLog(String text)
+ {
+ if(mHandler != null)
+ {
+ Message meg= new Message();
+ Bundle bundel= new Bundle();
+ bundel.putString("MESSAGE", text);
+ meg.setData(bundel);
+ mHandler.sendMessage(meg);
+ }
+ }
+ private void LogPass(boolean pass, String message) {
+ if (pass) {
+ PrintLog("PASS -" + message);
+ Log.e("Test", "PASS -" + message);
+ } else {
+ PrintLog("-FAILE -" + message);
+ Log.e("Test", "-FAILE -" + message);
+ }
+ }
+
+
+
+ private void PublishMessage(int start, int end, int offset) {
+ try {
+ Log.e("PublishMessage", "Publishing messages");
+ PrintLog("Publishing messages");
+ for (int i = start + offset; i < end + offset; i++) {
+
+ JSONObject message= new JSONObject();
+ message.put("message", i + " " + crazy);
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("message", message);
+ JSONArray responce = pubnub.publish(args);
+ if ((Integer) responce.get(0) == 1) {
+ String timestamp = (String) responce.get(2);
+ HashMap<String, Object> param = new HashMap<String, Object>();
+ param.put("timestamp", timestamp);
+ param.put("message",message);
+ inputs.add(param);
+ Log.e("Sent", "Message # " + i + " published");
+ PrintLog( "Message # " + i + " published");
+ }
+ }
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_begin_to_end_count() {
+ try {
+ int count = 5;
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("start", starttime);
+ args.put("end", endtime);
+ args.put("count", count);
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == count
+ && history.getString(history.length() - 1).equals(
+ inputs.get(count - 1).get("message").toString()),
+ "test_begin_to_end_count");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_end_to_begin_count() {
+ try {
+ int count = 5;
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("start", endtime);
+ args.put("end", starttime);
+ args.put("count", count);
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == count
+ && history.getString(history.length() - 1).equals(
+ inputs.get(total_msg - 1).get("message").toString()),
+ "test_end_to_begin_count");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_start_reverse_true() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("start", midtime);
+ args.put("reverse", Boolean.TRUE);
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == total_msg / 2
+ && history.getString(history.length() - 1).equals(
+ inputs.get(total_msg - 1).get("message").toString()),
+ "test_start_reverse_true");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_start_reverse_false() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("start", midtime);
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.getString(0).equals(
+ inputs.get(0).get("message").toString()),
+ "test_start_reverse_false");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_end_reverse_true() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("end", midtime);
+ args.put("reverse", Boolean.TRUE);
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.getString(0).equals(
+ inputs.get(0).get("message").toString()),
+ "test_end_reverse_true");
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ private void test_end_reverse_false() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("end", midtime);
+
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == total_msg / 2
+ && history.getString(history.length() - 1).equals(
+ inputs.get(total_msg - 1).get("message").toString()),"test_end_reverse_true");
+
+
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_count() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("count", 5);
+
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == 5,"test_count");
+
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+ private void test_count_zero() {
+ try {
+
+ HashMap<String, Object> args = new HashMap<String, Object>();
+ args.put("channel", channel);
+ args.put("count", 0);
+
+ JSONArray responce = pubnub.detailedHistory(args);
+ JSONArray history = responce.getJSONArray(0);
+
+ LogPass(history.length() == 0,"test_count_zero");
+
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+ }
+
+
+ }
+
Please sign in to comment.
Something went wrong with that request. Please try again.