diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/Constraints.java b/OSJ Forum/src/org/RickBarrette/osj/forum/Constraints.java index 984c8bf..b2a7efb 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/Constraints.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/Constraints.java @@ -20,7 +20,8 @@ package org.RickBarrette.osj.forum; /** - * This class will be used to house the constraints of this application + * This class will be used to house the constraints of this application + * * @author ricky barrette */ public class Constraints { @@ -28,8 +29,8 @@ public class Constraints { /** * Set this boolean to true to use the test server */ - public static final boolean TESTING = true; - + public static final boolean TESTING = true; + /** * Set this boolean to true to enable debug logging */ diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailActivity.java b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailActivity.java index 17ac6bd..38313ab 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailActivity.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailActivity.java @@ -50,6 +50,13 @@ public class ForumDetailActivity extends FragmentActivity implements OnItemSelec } } + @Override + public void onItemSelected(final Fragment listFragment, final String id) { + final Intent detailIntent = new Intent(this, TopicDetailActivity.class); + detailIntent.putExtra(TopicDetailFragment.ARG_ITEM_ID, id); + startActivity(detailIntent); + } + @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { @@ -59,11 +66,4 @@ public class ForumDetailActivity extends FragmentActivity implements OnItemSelec return super.onOptionsItemSelected(item); } - - @Override - public void onItemSelected(Fragment listFragment, String id) { - final Intent detailIntent = new Intent(this, TopicDetailActivity.class); - detailIntent.putExtra(TopicDetailFragment.ARG_ITEM_ID, id); - startActivity(detailIntent); - } } diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailFragment.java b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailFragment.java index 50988fd..01dd414 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailFragment.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumDetailFragment.java @@ -20,10 +20,10 @@ package org.RickBarrette.osj.forum; import org.RickBarrette.osj.forum.content.ForumContent; +import org.RickBarrette.osj.forum.content.ForumContent.ForumItem; import org.RickBarrette.osj.forum.content.OnItemSelectedListener; import org.RickBarrette.osj.forum.content.TopicAdapter; import org.RickBarrette.osj.forum.content.TopicContent; -import org.RickBarrette.osj.forum.content.ForumContent.ForumItem; import android.app.Activity; import android.os.Bundle; @@ -33,9 +33,9 @@ import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; - /** * This fragment will be used to display information about the forum + * * @author ricky barrette */ public class ForumDetailFragment extends ListFragment { @@ -52,10 +52,11 @@ public class ForumDetailFragment extends ListFragment { /** * (non-Javadoc) + * * @see android.support.v4.app.Fragment#onAttach(android.app.Activity) */ @Override - public void onAttach(Activity activity) { + public void onAttach(final Activity activity) { super.onAttach(activity); if (!(activity instanceof OnItemSelectedListener)) throw new IllegalStateException("Activity must implement fragment's callbacks."); @@ -69,13 +70,13 @@ public class ForumDetailFragment extends ListFragment { if (getArguments().containsKey(ARG_ITEM_ID)) mItem = ForumContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); - new Thread( new Runnable(){ + new Thread(new Runnable() { @Override - public void run(){ + public void run() { TopicContent.getTopics((String) mItem.content.get("forum_id"), getActivity()); - getActivity().runOnUiThread(new Runnable(){ + getActivity().runOnUiThread(new Runnable() { @Override - public void run(){ + public void run() { setListAdapter(new TopicAdapter(getActivity())); } }); @@ -85,14 +86,15 @@ public class ForumDetailFragment extends ListFragment { /** * (non-Javadoc) - * @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long) + * + * @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, + * android.view.View, int, long) */ @Override - public void onListItemClick(ListView l, View v, int position, long id) { + public void onListItemClick(final ListView l, final View v, final int position, final long id) { super.onListItemClick(l, v, position, id); mCallbacks.onItemSelected(this, TopicContent.ITEMS.get(position).id); } - @Override public void onSaveInstanceState(final Bundle outState) { diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListActivity.java b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListActivity.java index 6d6fd6c..13d0ab7 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListActivity.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListActivity.java @@ -53,7 +53,7 @@ public class ForumListActivity extends FragmentActivity implements OnItemSelecte } @Override - public boolean onCreateOptionsMenu(Menu menu) { + public boolean onCreateOptionsMenu(final Menu menu) { final MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main_menu, menu); return super.onCreateOptionsMenu(menu); @@ -61,34 +61,33 @@ public class ForumListActivity extends FragmentActivity implements OnItemSelecte @Override public void onItemSelected(final Fragment listFragment, final String id) { - if(listFragment instanceof ForumDetailFragment){ + if (listFragment instanceof ForumDetailFragment) { final Intent detailIntent = new Intent(this, TopicListActivity.class); detailIntent.putExtra(TopicListActivity.ARG_ITEM_ID, id); startActivity(detailIntent); - } else - if (mTwoPane) { - if(listFragment instanceof ForumListFragment){ - final Bundle arguments = new Bundle(); - arguments.putString(ForumDetailFragment.ARG_ITEM_ID, id); - final ForumDetailFragment fragment = new ForumDetailFragment(); - fragment.setArguments(arguments); - getSupportFragmentManager().beginTransaction().replace(R.id.forum_detail_container, fragment).commit(); - } - - } else { - final Intent detailIntent = new Intent(this, ForumDetailActivity.class); - detailIntent.putExtra(ForumDetailFragment.ARG_ITEM_ID, id); - startActivity(detailIntent); - } + } else if (mTwoPane) { + if (listFragment instanceof ForumListFragment) { + final Bundle arguments = new Bundle(); + arguments.putString(ForumDetailFragment.ARG_ITEM_ID, id); + final ForumDetailFragment fragment = new ForumDetailFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction().replace(R.id.forum_detail_container, fragment).commit(); + } + + } else { + final Intent detailIntent = new Intent(this, ForumDetailActivity.class); + detailIntent.putExtra(ForumDetailFragment.ARG_ITEM_ID, id); + startActivity(detailIntent); + } } @Override - public boolean onOptionsItemSelected(MenuItem item) { - switch(item.getItemId()){ - case R.id.legal: - startActivity(new Intent(this, LegalActivity.class)); - return true; + public boolean onOptionsItemSelected(final MenuItem item) { + switch (item.getItemId()) { + case R.id.legal: + startActivity(new Intent(this, LegalActivity.class)); + return true; } return super.onOptionsItemSelected(item); - } + } } \ No newline at end of file diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListFragment.java b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListFragment.java index 232dfd8..42a2962 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListFragment.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/ForumListFragment.java @@ -32,7 +32,6 @@ import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; - /** * * @author ricky barrette @@ -66,14 +65,14 @@ public class ForumListFragment extends ListFragment { public void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); - if(ForumContent.ITEMS.size() == 0) + if (ForumContent.ITEMS.size() == 0) new Thread(new Runnable() { @Override public void run() { ForumContent.getForum(getActivity()); - getActivity().runOnUiThread(new Runnable(){ + getActivity().runOnUiThread(new Runnable() { @Override - public void run(){ + public void run() { setListAdapter(new ForumAdapter(getActivity())); } }); diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/LegalActivity.java b/OSJ Forum/src/org/RickBarrette/osj/forum/LegalActivity.java index aa1755b..b49ecd1 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/LegalActivity.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/LegalActivity.java @@ -25,15 +25,16 @@ import android.webkit.WebView; /** * This is a super simple web activity to display legal information to the user + * * @author ricky barrette */ public class LegalActivity extends Activity { @Override - protected void onCreate(Bundle savedInstanceState) { + protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.leagal_activity); - WebView wv = (WebView) findViewById(R.id.webview); + final WebView wv = (WebView) findViewById(R.id.webview); wv.loadUrl("file:///android_asset/legal.html"); } diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/Log.java b/OSJ Forum/src/org/RickBarrette/osj/forum/Log.java index e046a08..b5b3fde 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/Log.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/Log.java @@ -21,145 +21,158 @@ package org.RickBarrette.osj.forum; /** * A convince class for logging with log level constraints + * * @author ricky barrette */ public class Log { /** * Send a DEBUG log message + * * @param tag * @param log * @author ricky barrette */ - public static void d(String tag, String log){ - if(Constraints.DEBUG) + public static void d(final String tag, final String log) { + if (Constraints.DEBUG) android.util.Log.d(tag, log); } - + /** * Send a DEBUG log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void d(String tag, String log, Throwable e){ - if(Constraints.DEBUG) + public static void d(final String tag, final String log, final Throwable e) { + if (Constraints.DEBUG) android.util.Log.d(tag, log, e); } - + /** * Send a ERROR log message + * * @param tag * @param log * @author ricky barrette */ - public static void e(String tag, String log){ - if(Constraints.ERROR) + public static void e(final String tag, final String log) { + if (Constraints.ERROR) android.util.Log.e(tag, log); } - + /** * Send a ERROR log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void e(String tag, String log, Throwable e){ - if(Constraints.ERROR) + public static void e(final String tag, final String log, final Throwable e) { + if (Constraints.ERROR) android.util.Log.e(tag, log, e); } - + /** * Send a INFO log message + * * @param tag * @param log * @author ricky barrette */ - public static void i(String tag, String log){ - if(Constraints.INFO) + public static void i(final String tag, final String log) { + if (Constraints.INFO) android.util.Log.i(tag, log); } - + /** * Send a INFO log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void i(String tag, String log, Throwable e){ - if(Constraints.INFO) + public static void i(final String tag, final String log, final Throwable e) { + if (Constraints.INFO) android.util.Log.i(tag, log, e); } - + /** * Send a VERBOSE log message + * * @param tag * @param log * @author ricky barrette */ - public static void v(String tag, String log){ - if(Constraints.VERBOSE) + public static void v(final String tag, final String log) { + if (Constraints.VERBOSE) android.util.Log.v(tag, log); } - + /** * Send a VERBOSE log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void v(String tag, String log, Throwable e){ - if(Constraints.VERBOSE) + public static void v(final String tag, final String log, final Throwable e) { + if (Constraints.VERBOSE) android.util.Log.v(tag, log, e); } - + /** * Send a WARNING log message + * * @param tag * @param log * @author ricky barrette */ - public static void w(String tag, String log){ - if(Constraints.WARNING) + public static void w(final String tag, final String log) { + if (Constraints.WARNING) android.util.Log.w(tag, log); } - + /** * Send a WARNING log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void w(String tag, String log, Throwable e){ - if(Constraints.WARNING) + public static void w(final String tag, final String log, final Throwable e) { + if (Constraints.WARNING) android.util.Log.w(tag, log, e); } - + /** * Send a WTF log message + * * @param tag * @param log * @author ricky barrette */ - public static void wtf(String tag, String log){ - if(Constraints.WTF) + public static void wtf(final String tag, final String log) { + if (Constraints.WTF) android.util.Log.wtf(tag, log); } - + /** * Send a WTF log message and log the exception. + * * @param tag * @param log * @param e * @author ricky barrette */ - public static void wtf(String tag, String log, Throwable e){ - if(Constraints.WTF) + public static void wtf(final String tag, final String log, final Throwable e) { + if (Constraints.WTF) android.util.Log.wtf(tag, log, e); } } \ No newline at end of file diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailActivity.java b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailActivity.java index e5155b1..0d1f226 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailActivity.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailActivity.java @@ -28,7 +28,7 @@ import android.support.v4.app.FragmentActivity; import android.support.v4.app.NavUtils; import android.view.MenuItem; -public class TopicDetailActivity extends FragmentActivity implements OnItemSelectedListener{ +public class TopicDetailActivity extends FragmentActivity implements OnItemSelectedListener { @Override protected void onCreate(final Bundle savedInstanceState) { @@ -46,6 +46,12 @@ public class TopicDetailActivity extends FragmentActivity implements OnItemSelec } } + @Override + public void onItemSelected(final Fragment listFragment, final String id) { + // TODO Auto-generated method stub + + } + @Override public boolean onOptionsItemSelected(final MenuItem item) { if (item.getItemId() == android.R.id.home) { @@ -55,10 +61,4 @@ public class TopicDetailActivity extends FragmentActivity implements OnItemSelec return super.onOptionsItemSelected(item); } - - @Override - public void onItemSelected(Fragment listFragment, String id) { - // TODO Auto-generated method stub - - } } diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailFragment.java b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailFragment.java index 291798c..3d82c02 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailFragment.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicDetailFragment.java @@ -33,7 +33,6 @@ import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; - public class TopicDetailFragment extends ListFragment { public static final String ARG_ITEM_ID = "item_id"; @@ -48,10 +47,11 @@ public class TopicDetailFragment extends ListFragment { /** * (non-Javadoc) + * * @see android.support.v4.app.Fragment#onAttach(android.app.Activity) */ @Override - public void onAttach(Activity activity) { + public void onAttach(final Activity activity) { super.onAttach(activity); if (!(activity instanceof OnItemSelectedListener)) throw new IllegalStateException("Activity must implement fragment's callbacks."); @@ -64,17 +64,17 @@ public class TopicDetailFragment extends ListFragment { super.onCreate(savedInstanceState); if (getArguments().containsKey(ARG_ITEM_ID)) mItem = TopicContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID)); - - if(mItem == null) + + if (mItem == null) throw new NullPointerException(); - new Thread( new Runnable(){ + new Thread(new Runnable() { @Override - public void run(){ + public void run() { ThreadContent.getThread((String) mItem.content.get("topic_id"), 0, 0, getActivity()); - getActivity().runOnUiThread(new Runnable(){ + getActivity().runOnUiThread(new Runnable() { @Override - public void run(){ + public void run() { setListAdapter(new ThreadAdapter(getActivity())); } }); @@ -84,14 +84,15 @@ public class TopicDetailFragment extends ListFragment { /** * (non-Javadoc) - * @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long) + * + * @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, + * android.view.View, int, long) */ @Override - public void onListItemClick(ListView l, View v, int position, long id) { + public void onListItemClick(final ListView l, final View v, final int position, final long id) { super.onListItemClick(l, v, position, id); mCallbacks.onItemSelected(this, TopicContent.ITEMS.get(position).id); } - @Override public void onSaveInstanceState(final Bundle outState) { diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListActivity.java b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListActivity.java index e9afc98..6e87adf 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListActivity.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListActivity.java @@ -45,7 +45,7 @@ public class TopicListActivity extends FragmentActivity implements OnItemSelecte ((TopicListFragment) getSupportFragmentManager().findFragmentById(R.id.topic_list)).setActivateOnItemClick(true); final Bundle arguments = new Bundle(); - arguments.putString(TopicDetailFragment.ARG_ITEM_ID, this.getIntent().getExtras().getString(ARG_ITEM_ID)); + arguments.putString(TopicDetailFragment.ARG_ITEM_ID, getIntent().getExtras().getString(ARG_ITEM_ID)); final TopicDetailFragment fragment = new TopicDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction().replace(R.id.topic_detail_container, fragment).commit(); @@ -54,14 +54,14 @@ public class TopicListActivity extends FragmentActivity implements OnItemSelecte @Override public void onItemSelected(final Fragment listFragment, final String id) { - if(listFragment instanceof TopicListFragment) + if (listFragment instanceof TopicListFragment) if (mTwoPane) { final Bundle arguments = new Bundle(); arguments.putString(TopicDetailFragment.ARG_ITEM_ID, id); final TopicDetailFragment fragment = new TopicDetailFragment(); fragment.setArguments(arguments); getSupportFragmentManager().beginTransaction().replace(R.id.topic_detail_container, fragment).commit(); - + } else { final Intent detailIntent = new Intent(this, TopicDetailActivity.class); detailIntent.putExtra(TopicDetailFragment.ARG_ITEM_ID, id); diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListFragment.java b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListFragment.java index 46372da..abf20f7 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListFragment.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/TopicListFragment.java @@ -32,7 +32,6 @@ import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ListView; - public class TopicListFragment extends ListFragment { private static final String STATE_ACTIVATED_POSITION = "activated_position"; @@ -53,7 +52,7 @@ public class TopicListFragment extends ListFragment { public void onAttach(final Activity activity) { super.onAttach(activity); if (!(activity instanceof OnItemSelectedListener)) - + throw new IllegalStateException("Activity must implement fragment's callbacks."); mCallbacks = (OnItemSelectedListener) activity; diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumAdapter.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumAdapter.java index 841b011..7703494 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumAdapter.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumAdapter.java @@ -31,27 +31,30 @@ import android.widget.TextView; /** * This adapter will be used to populate a list view with forum entries + * * @author ricky barrette */ public class ForumAdapter extends BaseAdapter { - + class ViewHolder { TextView title; TextView description; } - private LayoutInflater mInflater; + private final LayoutInflater mInflater; /** * Creates a new ForumAdapter + * * @author ricky barrette */ public ForumAdapter(final Context context) { mInflater = LayoutInflater.from(context); } - /** + /** * (non-Javadoc) + * * @see android.widget.Adapter#getCount() */ @Override @@ -61,28 +64,32 @@ public class ForumAdapter extends BaseAdapter { /** * (non-Javadoc) + * * @see android.widget.Adapter#getItem(int) */ @Override - public ForumItem getItem(int position) { + public ForumItem getItem(final int position) { return ForumContent.ITEMS.get(position); } /** * (non-Javadoc) + * * @see android.widget.Adapter#getItemId(int) */ @Override - public long getItemId(int position) { + public long getItemId(final int position) { return position; } /** * (non-Javadoc) - * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) + * + * @see android.widget.Adapter#getView(int, android.view.View, + * android.view.ViewGroup) */ @Override - public View getView(int position, View convertView, ViewGroup parent) { + public View getView(final int position, View convertView, final ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; @@ -108,7 +115,6 @@ public class ForumAdapter extends BaseAdapter { // and the ImageView. holder = (ViewHolder) convertView.getTag(); - /* * Bind the data efficiently with the holder. Remember that you should * always call setChecked() after calling setOnCheckedChangedListener. diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumContent.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumContent.java index a67aca8..12b55b4 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumContent.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ForumContent.java @@ -30,15 +30,16 @@ import org.xmlrpc.android.XMLRPCException; import android.content.Context; - /** * This class is used to maintain an instance of a forum's content data + * * @author ricky barrette */ public class ForumContent { /** - * This Forum Object + * This Forum Object + * * @author ricky barrette */ public static class ForumItem { @@ -49,6 +50,7 @@ public class ForumContent { /** * Creates a new Forum Item + * * @param id * @param content * @author ricky barrette @@ -56,20 +58,21 @@ public class ForumContent { public ForumItem(final String id, final HashMap content) { this.id = id; this.content = content; - - for(Object key: content.keySet()) + + for (final Object key : content.keySet()) Log.v(TAG, key.toString()); } /** * This gets all the categories and sub-forums + * * @return array of HashMap * @author ricky barrette */ - public Object[] getChildren(){ - return (Object[]) this.content.get("child"); + public Object[] getChildren() { + return (Object[]) content.get("child"); } - + /** * Returns the name of this forum object */ @@ -85,6 +88,7 @@ public class ForumContent { /** * Adds a new Forum Item to the list + * * @param item * @author ricky barrette */ @@ -92,30 +96,30 @@ public class ForumContent { ITEMS.add(item); ITEM_MAP.put(item.id, item); } - + /** * Downloads the forum from the Internet + * * @param context * @author ricky barrette */ - public static void getForum(Context context){ + public static void getForum(final Context context) { ITEMS.clear(); ITEM_MAP.clear(); - + final XMLRPCClient client = XMLRPCClient.getClient(context); - + Object[] result = null; try { result = (Object[]) client.call("get_forum", true); - } catch (XMLRPCException e) { + } catch (final XMLRPCException e) { e.printStackTrace(); } - - if(result!= null){ - for(int i = 0; i < result.length; i++){ - HashMap contentHash = (HashMap) result[i]; + + if (result != null) + for (int i = 0; i < result.length; i++) { + final HashMap contentHash = (HashMap) result[i]; addItem(new ForumItem(Integer.valueOf(i).toString(), contentHash)); } - } } } \ No newline at end of file diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/OnItemSelectedListener.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/OnItemSelectedListener.java index 7a2606a..826ce46 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/OnItemSelectedListener.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/OnItemSelectedListener.java @@ -23,13 +23,16 @@ import android.support.v4.app.Fragment; /** * This is a simple on item selcted callback for list fragments + * * @author ricky barrette */ public interface OnItemSelectedListener { /** * Called when a list item from a list fragment is selected + * * @param listFragment - * @param id of selected item + * @param id + * of selected item * @author ricky barrette */ public void onItemSelected(final Fragment listFragment, final String id); diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/SubForumAdapter.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/SubForumAdapter.java index e42164a..00b8e05 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/SubForumAdapter.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/SubForumAdapter.java @@ -32,33 +32,35 @@ import android.widget.TextView; /** * This adapter will be used to display sub-forums to the user + * * @author ricky barrette */ public class SubForumAdapter extends BaseAdapter { - + class ViewHolder { TextView title; } - private LayoutInflater mInflater; - private Object[] mSubForums; + private final LayoutInflater mInflater; + private final Object[] mSubForums; /** * * @author ricky barrette */ - public SubForumAdapter(Context context, int position) { + public SubForumAdapter(final Context context, final int position) { mInflater = LayoutInflater.from(context); mSubForums = ForumContent.ITEMS.get(position).getChildren(); } /** * (non-Javadoc) + * * @see android.widget.Adapter#getCount() */ @Override public int getCount() { - if(mSubForums != null) + if (mSubForums != null) return mSubForums.length; else return 0; @@ -66,28 +68,32 @@ public class SubForumAdapter extends BaseAdapter { /** * (non-Javadoc) + * * @see android.widget.Adapter#getItem(int) */ @Override - public HashMap getItem(int position) { - return (HashMap) mSubForums[position]; + public HashMap getItem(final int position) { + return (HashMap) mSubForums[position]; } /** * (non-Javadoc) + * * @see android.widget.Adapter#getItemId(int) */ @Override - public long getItemId(int position) { + public long getItemId(final int position) { return position; } /** * (non-Javadoc) - * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) + * + * @see android.widget.Adapter#getView(int, android.view.View, + * android.view.ViewGroup) */ @Override - public View getView(int position, View convertView, ViewGroup parent) { + public View getView(final int position, View convertView, final ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; @@ -112,7 +118,6 @@ public class SubForumAdapter extends BaseAdapter { // and the ImageView. holder = (ViewHolder) convertView.getTag(); - /* * Bind the data efficiently with the holder. Remember that you should * always call setChecked() after calling setOnCheckedChangedListener. diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadAdapter.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadAdapter.java index 9228ee4..495cdef 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadAdapter.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadAdapter.java @@ -33,10 +33,11 @@ import android.widget.TextView; /** * This adapter will be used to populte a list view with post from a thread + * * @author ricky barrette */ public class ThreadAdapter extends BaseAdapter { - + class ViewHolder { TextView title; TextView user; @@ -44,13 +45,14 @@ public class ThreadAdapter extends BaseAdapter { QuickContactBadge badage; } - private LayoutInflater mInflater; + private final LayoutInflater mInflater; /** * Creates a new ThreadAdapter + * * @author ricky barrette */ - public ThreadAdapter(Context context) { + public ThreadAdapter(final Context context) { mInflater = LayoutInflater.from(context); } @@ -70,8 +72,8 @@ public class ThreadAdapter extends BaseAdapter { * @see android.widget.Adapter#getItem(int) */ @Override - public HashMap getItem(int position) { - return (HashMap) ThreadContent.ITEMS.get(position).content; + public HashMap getItem(final int position) { + return ThreadContent.ITEMS.get(position).content; } /* @@ -80,7 +82,7 @@ public class ThreadAdapter extends BaseAdapter { * @see android.widget.Adapter#getItemId(int) */ @Override - public long getItemId(int position) { + public long getItemId(final int position) { return position; } @@ -91,7 +93,7 @@ public class ThreadAdapter extends BaseAdapter { * android.view.ViewGroup) */ @Override - public View getView(int position, View convertView, ViewGroup parent) { + public View getView(final int position, View convertView, final ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadContent.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadContent.java index e1ee94f..cbb4954 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadContent.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/ThreadContent.java @@ -30,24 +30,26 @@ import org.xmlrpc.android.XMLRPCException; import android.content.Context; - /** * This class is used to maintain an instance of a thread's data content + * * @author ricky barrette */ public class ThreadContent { /** - * This Forum Object + * This Forum Object + * * @author ricky barrette */ public static class ThreadItem { private static final String TAG = "ThreadItem"; public String id; public HashMap content; - + /** * Creates a new Topic Item + * * @param id * @param content * @author ricky barrette @@ -55,8 +57,8 @@ public class ThreadContent { public ThreadItem(final String id, final HashMap content) { this.id = id; this.content = content; - - for(Object key: content.keySet()) + + for (final Object key : content.keySet()) Log.v(TAG, key.toString()); } } @@ -66,6 +68,7 @@ public class ThreadContent { /** * Adds a new Forum Item to the list + * * @param item * @author ricky barrette */ @@ -73,34 +76,34 @@ public class ThreadContent { ITEMS.add(item); ITEM_MAP.put(item.id, item); } - + /** * This downloads a thread for a specific topic + * * @param topicId * @param startNumber * @param lastNumber * @param context * @author ricky barrette */ - public static void getThread(String topicId, int startNumber, int lastNumber, final Context context){ + public static void getThread(final String topicId, final int startNumber, final int lastNumber, final Context context) { final XMLRPCClient client = XMLRPCClient.getClient(context); - + ITEMS.clear(); ITEM_MAP.clear(); - + Object[] result = null; try { - result = (Object[]) ((HashMap) client.call("get_thread", topicId, startNumber, lastNumber)).get("posts"); - } catch (XMLRPCException e) { + result = (Object[]) ((HashMap) client.call("get_thread", topicId, startNumber, lastNumber)).get("posts"); + } catch (final XMLRPCException e) { e.printStackTrace(); } - - if(result!= null){ - for(int i = 0; i < result.length; i++){ - HashMap contentHash = (HashMap) result[i]; + + if (result != null) + for (int i = 0; i < result.length; i++) { + final HashMap contentHash = (HashMap) result[i]; addItem(new ThreadItem(Integer.valueOf(i).toString(), contentHash)); } - } } } diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicAdapter.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicAdapter.java index 392ba97..b5b057d 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicAdapter.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicAdapter.java @@ -33,10 +33,11 @@ import android.widget.TextView; /** * This adapter will be used to display topics to the user + * * @author ricky barrette */ public class TopicAdapter extends BaseAdapter { - + class ViewHolder { TextView title; TextView lastestPost; @@ -45,7 +46,7 @@ public class TopicAdapter extends BaseAdapter { QuickContactBadge badage; } - private LayoutInflater mInflater; + private final LayoutInflater mInflater; /** * @@ -57,6 +58,7 @@ public class TopicAdapter extends BaseAdapter { /** * (non-Javadoc) + * * @see android.widget.Adapter#getCount() */ @Override @@ -66,28 +68,32 @@ public class TopicAdapter extends BaseAdapter { /** * (non-Javadoc) + * * @see android.widget.Adapter#getItem(int) */ @Override - public HashMap getItem(int position) { - return (HashMap) TopicContent.ITEMS.get(position).content; + public HashMap getItem(final int position) { + return TopicContent.ITEMS.get(position).content; } /** * (non-Javadoc) + * * @see android.widget.Adapter#getItemId(int) */ @Override - public long getItemId(int position) { + public long getItemId(final int position) { return position; } /** * (non-Javadoc) - * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup) + * + * @see android.widget.Adapter#getView(int, android.view.View, + * android.view.ViewGroup) */ @Override - public View getView(int position, View convertView, ViewGroup parent) { + public View getView(final int position, View convertView, final ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. ViewHolder holder; @@ -109,14 +115,13 @@ public class TopicAdapter extends BaseAdapter { holder.user = (TextView) convertView.findViewById(R.id.textView3); holder.newPosts = (TextView) convertView.findViewById(R.id.textView4); holder.badage = (QuickContactBadge) convertView.findViewById(R.id.quickContactBadge1); - + convertView.setTag(holder); } else // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); - /* * Bind the data efficiently with the holder. Remember that you should * always call setChecked() after calling setOnCheckedChangedListener. @@ -125,8 +130,8 @@ public class TopicAdapter extends BaseAdapter { holder.title.setText(new String((byte[]) getItem(position).get("topic_title"))); holder.user.setText(new String((byte[]) getItem(position).get("topic_author_name"))); holder.lastestPost.setText(new String((byte[]) getItem(position).get("short_content"))); - holder.newPosts.setVisibility(((Boolean) getItem(position).get("new_post") ? View.VISIBLE : View.GONE)); - + holder.newPosts.setVisibility((Boolean) getItem(position).get("new_post") ? View.VISIBLE : View.GONE); + return convertView; } diff --git a/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicContent.java b/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicContent.java index 9a46d4a..cee7160 100644 --- a/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicContent.java +++ b/OSJ Forum/src/org/RickBarrette/osj/forum/content/TopicContent.java @@ -30,24 +30,26 @@ import org.xmlrpc.android.XMLRPCException; import android.content.Context; - /** * This class is used to maintain an instance of a topic's content data + * * @author ricky barrette */ public class TopicContent { - + /** - * This Forum Object + * This Forum Object + * * @author ricky barrette */ public static class TopicItem { private static final String TAG = "TopicItem"; public String id; public HashMap content; - + /** * Creates a new Topic Item + * * @param id * @param content * @author ricky barrette @@ -55,8 +57,8 @@ public class TopicContent { public TopicItem(final String id, final HashMap content) { this.id = id; this.content = content; - - for(Object key: content.keySet()) + + for (final Object key : content.keySet()) Log.v(TAG, key.toString()); } } @@ -66,6 +68,7 @@ public class TopicContent { /** * Adds a new Forum Item to the list + * * @param item * @author ricky barrette */ @@ -73,31 +76,31 @@ public class TopicContent { ITEMS.add(item); ITEM_MAP.put(item.id, item); } - + /** * This gets all the topics for the current forum item + * * @param context * @return * @author ricky barrette */ - public static void getTopics(String forumId, final Context context){ + public static void getTopics(final String forumId, final Context context) { final XMLRPCClient client = XMLRPCClient.getClient(context); - + ITEMS.clear(); ITEM_MAP.clear(); - + Object[] result = null; try { - result = (Object[]) ((HashMap) client.call("get_topic", forumId, 0, 0)).get("topics"); - } catch (XMLRPCException e) { + result = (Object[]) ((HashMap) client.call("get_topic", forumId, 0, 0)).get("topics"); + } catch (final XMLRPCException e) { e.printStackTrace(); } - - if(result!= null){ - for(int i = 0; i < result.length; i++){ - HashMap contentHash = (HashMap) result[i]; + + if (result != null) + for (int i = 0; i < result.length; i++) { + final HashMap contentHash = (HashMap) result[i]; addItem(new TopicItem(Integer.valueOf(i).toString(), contentHash)); } - } } } diff --git a/OSJ Forum/src/org/xmlrpc/android/Base64Coder.java b/OSJ Forum/src/org/xmlrpc/android/Base64Coder.java index f9a4807..373264e 100644 --- a/OSJ Forum/src/org/xmlrpc/android/Base64Coder.java +++ b/OSJ Forum/src/org/xmlrpc/android/Base64Coder.java @@ -31,15 +31,12 @@ class Base64Coder { private static char[] map1 = new char[64]; static { int i = 0; - for (char c = 'A'; c <= 'Z'; c++) { + for (char c = 'A'; c <= 'Z'; c++) map1[i++] = c; - } - for (char c = 'a'; c <= 'z'; c++) { + for (char c = 'a'; c <= 'z'; c++) map1[i++] = c; - } - for (char c = '0'; c <= '9'; c++) { + for (char c = '0'; c <= '9'; c++) map1[i++] = c; - } map1[i++] = '+'; map1[i++] = '/'; } @@ -47,24 +44,81 @@ class Base64Coder { // Mapping table from Base64 characters to 6-bit nibbles. private static byte[] map2 = new byte[128]; static { - for (int i = 0; i < map2.length; i++) { + for (int i = 0; i < map2.length; i++) map2[i] = -1; - } - for (int i = 0; i < 64; i++) { + for (int i = 0; i < 64; i++) map2[map1[i]] = (byte) i; - } } /** - * Encodes a string into Base64 format. No blanks or line breaks are - * inserted. + * Decodes a byte array from Base64 format. No blanks or line breaks are + * allowed within the Base64 encoded data. + * + * @param in + * a character array containing the Base64 encoded data. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException + * if the input is not valid Base64 encoded data. + */ + static byte[] decode(final char[] in) { + int iLen = in.length; + if (iLen % 4 != 0) + throw new IllegalArgumentException("Length of Base64 encoded input string is not a multiple of 4."); + while (iLen > 0 && in[iLen - 1] == '=') + iLen--; + final int oLen = iLen * 3 / 4; + final byte[] out = new byte[oLen]; + int ip = 0; + int op = 0; + while (ip < iLen) { + final int i0 = in[ip++]; + final int i1 = in[ip++]; + final int i2 = ip < iLen ? in[ip++] : 'A'; + final int i3 = ip < iLen ? in[ip++] : 'A'; + if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + final int b0 = map2[i0]; + final int b1 = map2[i1]; + final int b2 = map2[i2]; + final int b3 = map2[i3]; + if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) + throw new IllegalArgumentException("Illegal character in Base64 encoded data."); + final int o0 = b0 << 2 | b1 >>> 4; + final int o1 = (b1 & 0xf) << 4 | b2 >>> 2; + final int o2 = (b2 & 3) << 6 | b3; + out[op++] = (byte) o0; + if (op < oLen) + out[op++] = (byte) o1; + if (op < oLen) + out[op++] = (byte) o2; + } + return out; + } + + /** + * Decodes a byte array from Base64 format. * * @param s - * a String to be encoded. - * @return A String with the Base64 encoded data. + * a Base64 String to be decoded. + * @return An array containing the decoded data bytes. + * @throws IllegalArgumentException + * if the input is not valid Base64 encoded data. */ - static String encodeString(String s) { - return new String(encode(s.getBytes())); + static byte[] decode(final String s) { + return decode(s.toCharArray()); + } + + /** + * Decodes a string from Base64 format. + * + * @param s + * a Base64 String to be decoded. + * @return A String containing the decoded data. + * @throws IllegalArgumentException + * if the input is not valid Base64 encoded data. + */ + static String decodeString(final String s) { + return new String(decode(s)); } /** @@ -75,7 +129,7 @@ class Base64Coder { * an array containing the data bytes to be encoded. * @return A character array with the Base64 encoded data. */ - static char[] encode(byte[] in) { + static char[] encode(final byte[] in) { return encode(in, in.length); } @@ -89,20 +143,21 @@ class Base64Coder { * number of bytes to process in in. * @return A character array with the Base64 encoded data. */ - static char[] encode(byte[] in, int iLen) { - int oDataLen = (iLen * 4 + 2) / 3; // output length without padding - int oLen = ((iLen + 2) / 3) * 4; // output length including padding - char[] out = new char[oLen]; + static char[] encode(final byte[] in, final int iLen) { + final int oDataLen = (iLen * 4 + 2) / 3; // output length without + // padding + final int oLen = (iLen + 2) / 3 * 4; // output length including padding + final char[] out = new char[oLen]; int ip = 0; int op = 0; while (ip < iLen) { - int i0 = in[ip++] & 0xff; - int i1 = ip < iLen ? in[ip++] & 0xff : 0; - int i2 = ip < iLen ? in[ip++] & 0xff : 0; - int o0 = i0 >>> 2; - int o1 = ((i0 & 3) << 4) | (i1 >>> 4); - int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6); - int o3 = i2 & 0x3F; + final int i0 = in[ip++] & 0xff; + final int i1 = ip < iLen ? in[ip++] & 0xff : 0; + final int i2 = ip < iLen ? in[ip++] & 0xff : 0; + final int o0 = i0 >>> 2; + final int o1 = (i0 & 3) << 4 | i1 >>> 4; + final int o2 = (i1 & 0xf) << 2 | i2 >>> 6; + final int o3 = i2 & 0x3F; out[op++] = map1[o0]; out[op++] = map1[o1]; out[op] = op < oDataLen ? map1[o2] : '='; @@ -114,83 +169,15 @@ class Base64Coder { } /** - * Decodes a string from Base64 format. + * Encodes a string into Base64 format. No blanks or line breaks are + * inserted. * * @param s - * a Base64 String to be decoded. - * @return A String containing the decoded data. - * @throws IllegalArgumentException - * if the input is not valid Base64 encoded data. + * a String to be encoded. + * @return A String with the Base64 encoded data. */ - static String decodeString(String s) { - return new String(decode(s)); - } - - /** - * Decodes a byte array from Base64 format. - * - * @param s - * a Base64 String to be decoded. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * if the input is not valid Base64 encoded data. - */ - static byte[] decode(String s) { - return decode(s.toCharArray()); - } - - /** - * Decodes a byte array from Base64 format. No blanks or line breaks are - * allowed within the Base64 encoded data. - * - * @param in - * a character array containing the Base64 encoded data. - * @return An array containing the decoded data bytes. - * @throws IllegalArgumentException - * if the input is not valid Base64 encoded data. - */ - static byte[] decode(char[] in) { - int iLen = in.length; - if (iLen % 4 != 0) { - throw new IllegalArgumentException( - "Length of Base64 encoded input string is not a multiple of 4."); - } - while (iLen > 0 && in[iLen - 1] == '=') { - iLen--; - } - int oLen = (iLen * 3) / 4; - byte[] out = new byte[oLen]; - int ip = 0; - int op = 0; - while (ip < iLen) { - int i0 = in[ip++]; - int i1 = in[ip++]; - int i2 = ip < iLen ? in[ip++] : 'A'; - int i3 = ip < iLen ? in[ip++] : 'A'; - if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127) { - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); - } - int b0 = map2[i0]; - int b1 = map2[i1]; - int b2 = map2[i2]; - int b3 = map2[i3]; - if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0) { - throw new IllegalArgumentException( - "Illegal character in Base64 encoded data."); - } - int o0 = (b0 << 2) | (b1 >>> 4); - int o1 = ((b1 & 0xf) << 4) | (b2 >>> 2); - int o2 = ((b2 & 3) << 6) | b3; - out[op++] = (byte) o0; - if (op < oLen) { - out[op++] = (byte) o1; - } - if (op < oLen) { - out[op++] = (byte) o2; - } - } - return out; + static String encodeString(final String s) { + return new String(encode(s.getBytes())); } // Dummy constructor. diff --git a/OSJ Forum/src/org/xmlrpc/android/IXMLRPCSerializer.java b/OSJ Forum/src/org/xmlrpc/android/IXMLRPCSerializer.java index f651e46..429a00f 100644 --- a/OSJ Forum/src/org/xmlrpc/android/IXMLRPCSerializer.java +++ b/OSJ Forum/src/org/xmlrpc/android/IXMLRPCSerializer.java @@ -11,7 +11,7 @@ public interface IXMLRPCSerializer { String TAG_MEMBER = "member"; String TAG_VALUE = "value"; String TAG_DATA = "data"; - + String TYPE_INT = "int"; String TYPE_I4 = "i4"; String TYPE_I8 = "i8"; @@ -24,9 +24,10 @@ public interface IXMLRPCSerializer { String TYPE_STRUCT = "struct"; // This added by mattias.ellback as part of issue #19 String TYPE_NULL = "nil"; - + String DATETIME_FORMAT = "yyyyMMdd'T'HH:mm:ss"; - void serialize(XmlSerializer serializer, Object object) throws IOException; Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException; + + void serialize(XmlSerializer serializer, Object object) throws IOException; } diff --git a/OSJ Forum/src/org/xmlrpc/android/MethodCall.java b/OSJ Forum/src/org/xmlrpc/android/MethodCall.java index d573d5c..67641eb 100644 --- a/OSJ Forum/src/org/xmlrpc/android/MethodCall.java +++ b/OSJ Forum/src/org/xmlrpc/android/MethodCall.java @@ -7,14 +7,24 @@ public class MethodCall { private static final int TOPIC = 1; String methodName; ArrayList params = new ArrayList(); - - public String getMethodName() { return methodName; } - void setMethodName(String methodName) { this.methodName = methodName; } - public ArrayList getParams() { return params; } - void setParams(ArrayList params) { this.params = params; } + public String getMethodName() { + return methodName; + } + + public ArrayList getParams() { + return params; + } public String getTopic() { - return (String)params.get(TOPIC); + return (String) params.get(TOPIC); + } + + void setMethodName(final String methodName) { + this.methodName = methodName; + } + + void setParams(final ArrayList params) { + this.params = params; } } diff --git a/OSJ Forum/src/org/xmlrpc/android/XMLRPCClient.java b/OSJ Forum/src/org/xmlrpc/android/XMLRPCClient.java index 0c397a4..ad8b4f8 100644 --- a/OSJ Forum/src/org/xmlrpc/android/XMLRPCClient.java +++ b/OSJ Forum/src/org/xmlrpc/android/XMLRPCClient.java @@ -37,258 +37,375 @@ import android.content.Context; * XMLRPCClient allows to call remote XMLRPC method. * *

- * The following table shows how XML-RPC types are mapped to java call parameters/response values. + * The following table shows how XML-RPC types are mapped to java call + * parameters/response values. *

* *

* - * + * + * + * + * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * - * + * + * + * * * *
XML-RPC TypeCall ParametersCall Response
XML-RPC TypeCall ParametersCall Response
int, i4byte
Byte
short
Short
int
Integer
int
Integer
int, i4byte
+ * Byte
+ * short
+ * Short
+ * int
+ * Integer
int
+ * Integer
i8long
Long
long
Long
i8long
+ * Long
long
+ * Long
doublefloat
Float
double
Double
double
Double
doublefloat
+ * Float
+ * double
+ * Double
double
+ * Double
stringStringStringstringStringString
booleanboolean
Boolean
boolean
Boolean
booleanboolean
+ * Boolean
boolean
+ * Boolean
dateTime.iso8601java.util.Date
java.util.Calendar
java.util.DatedateTime.iso8601java.util.Date
+ * java.util.Calendar
java.util.Date
base64byte[]byte[]base64byte[]byte[]
arrayjava.util.List<Object>
Object[]
Object[]arrayjava.util.List<Object>
+ * Object[]
Object[]
structjava.util.Map<String, Object>java.util.Map<String, Object>structjava.util.Map<String, Object>java.util.Map<String, Object>
*

*

- * You can also pass as a parameter any object implementing XMLRPCSerializable interface. In this - * case your object overrides getSerializable() telling how to serialize to XMLRPC protocol + * You can also pass as a parameter any object implementing XMLRPCSerializable + * interface. In this case your object overrides getSerializable() telling how + * to serialize to XMLRPC protocol *

*/ public class XMLRPCClient extends XMLRPCCommon { - private HttpClient client; - private HttpPost postMethod; - private HttpParams httpParams; - // These variables used in the code inspired by erickok in issue #6 + /** + * Creates an XML RPC Client + * + * @param Context + * @return XMLRPCClient + * @author ricky barrette + */ + public static XMLRPCClient getClient(final Context context) { + if (Constraints.TESTING) + return new XMLRPCClient(context.getString(R.string.test_server), context.getString(R.string.test_username), context.getString(R.string.test_password)); + else + return new XMLRPCClient(context.getString(R.string.osj_server), context.getString(R.string.test_username), context.getString(R.string.test_password)); + } + + private final HttpClient client; + private final HttpPost postMethod; + private final HttpParams httpParams; + // These variables used in the code inspired by erickok in issue #6 private boolean httpPreAuth = false; private String username = ""; + private String password = ""; - + /** - * XMLRPCClient constructor. Creates new instance based on server URI - * (Code contributed by sgayda2 from issue #17, and by erickok from ticket #10) + * Convenience constructor. Creates new instance based on server String + * address * - * @param XMLRPC server URI + * @param XMLRPC + * server address */ - public XMLRPCClient(URI uri) { - SchemeRegistry registry = new SchemeRegistry(); + public XMLRPCClient(final String url) { + this(URI.create(url)); + } + + /** + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server address + * @param HttpClient + * to use + */ + public XMLRPCClient(final String url, final HttpClient client) { + this(URI.create(url), client); + } + + /** + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server address + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password + */ + public XMLRPCClient(final String url, final String username, final String password) { + this(URI.create(url), username, password); + } + + /** + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server address + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password + * @param HttpClient + * to use + */ + public XMLRPCClient(final String url, final String username, final String password, final HttpClient client) { + this(URI.create(url), username, password, client); + } + + /** + * XMLRPCClient constructor. Creates new instance based on server URI (Code + * contributed by sgayda2 from issue #17, and by erickok from ticket #10) + * + * @param XMLRPC + * server URI + */ + public XMLRPCClient(final URI uri) { + final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", new PlainSocketFactory(), 80)); registry.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); - + postMethod = new HttpPost(uri); postMethod.addHeader("Content-Type", "text/xml"); - + // WARNING - // I had to disable "Expect: 100-Continue" header since I had - // two second delay between sending http POST request and POST body + // I had to disable "Expect: 100-Continue" header since I had + // two second delay between sending http POST request and POST body httpParams = postMethod.getParams(); HttpProtocolParams.setUseExpectContinue(httpParams, false); - this.client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); + client = new DefaultHttpClient(new ThreadSafeClientConnManager(httpParams, registry), httpParams); } - + /** - * XMLRPCClient constructor. Creates new instance based on server URI - * (Code contributed by sgayda2 from issue #17) + * XMLRPCClient constructor. Creates new instance based on server URI (Code + * contributed by sgayda2 from issue #17) * - * @param XMLRPC server URI - * @param HttpClient to use + * @param XMLRPC + * server URI + * @param HttpClient + * to use */ - - public XMLRPCClient(URI uri, HttpClient client) { + + public XMLRPCClient(final URI uri, final HttpClient client) { postMethod = new HttpPost(uri); postMethod.addHeader("Content-Type", "text/xml"); - + // WARNING - // I had to disable "Expect: 100-Continue" header since I had - // two second delay between sending http POST request and POST body + // I had to disable "Expect: 100-Continue" header since I had + // two second delay between sending http POST request and POST body httpParams = postMethod.getParams(); HttpProtocolParams.setUseExpectContinue(httpParams, false); this.client = client; } /** - * Amends user agent - * (Code contributed by mortenholdflod from issue #28) + * Convenience constructor. Creates new instance based on server String + * address * - * @param userAgent defining the new User Agent string + * @param XMLRPC + * server address + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password */ - public void setUserAgent(String userAgent) { - postMethod.removeHeaders("User-Agent"); - postMethod.addHeader("User-Agent", userAgent); - } - - /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - */ - public XMLRPCClient(String url) { - this(URI.create(url)); + public XMLRPCClient(final URI uri, final String username, final String password) { + this(uri); + + ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), + new UsernamePasswordCredentials(username, password)); } /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - * @param HttpClient to use + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server address + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password + * @param HttpClient + * to use */ - public XMLRPCClient(String url, HttpClient client) { - this(URI.create(url), client); + public XMLRPCClient(final URI uri, final String username, final String password, final HttpClient client) { + this(uri, client); + + ((DefaultHttpClient) this.client).getCredentialsProvider().setCredentials(new AuthScope(uri.getHost(), uri.getPort(), AuthScope.ANY_REALM), + new UsernamePasswordCredentials(username, password)); } - /** - * Convenience XMLRPCClient constructor. Creates new instance based on server URL - * @param XMLRPC server URL + * Convenience XMLRPCClient constructor. Creates new instance based on + * server URL + * + * @param XMLRPC + * server URL */ - public XMLRPCClient(URL url) { + public XMLRPCClient(final URL url) { this(URI.create(url.toExternalForm())); } /** - * Convenience XMLRPCClient constructor. Creates new instance based on server URL - * @param XMLRPC server URL - * @param HttpClient to use + * Convenience XMLRPCClient constructor. Creates new instance based on + * server URL + * + * @param XMLRPC + * server URL + * @param HttpClient + * to use */ - public XMLRPCClient(URL url, HttpClient client) { + public XMLRPCClient(final URL url, final HttpClient client) { this(URI.create(url.toExternalForm()), client); } - - /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password - */ - public XMLRPCClient(URI uri, String username, String password) { - this(uri); - - ((DefaultHttpClient) client).getCredentialsProvider().setCredentials( - new AuthScope(uri.getHost(), uri.getPort(),AuthScope.ANY_REALM), - new UsernamePasswordCredentials(username, password)); - } /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password - * @param HttpClient to use - */ - public XMLRPCClient(URI uri, String username, String password, HttpClient client) { - this(uri, client); - - ((DefaultHttpClient) this.client).getCredentialsProvider().setCredentials( - new AuthScope(uri.getHost(), uri.getPort(),AuthScope.ANY_REALM), - new UsernamePasswordCredentials(username, password)); - } - - /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server url + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password */ - public XMLRPCClient(String url, String username, String password) { - this(URI.create(url), username, password); - } - - /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server address - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password - * @param HttpClient to use - */ - public XMLRPCClient(String url, String username, String password, HttpClient client) { - this(URI.create(url), username, password, client); - } - - /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server url - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password - */ - public XMLRPCClient(URL url, String username, String password) { + public XMLRPCClient(final URL url, final String username, final String password) { this(URI.create(url.toExternalForm()), username, password); } /** - * Convenience constructor. Creates new instance based on server String address - * @param XMLRPC server url - * @param HTTP Server - Basic Authentication - Username - * @param HTTP Server - Basic Authentication - Password - * @param HttpClient to use + * Convenience constructor. Creates new instance based on server String + * address + * + * @param XMLRPC + * server url + * @param HTTP + * Server - Basic Authentication - Username + * @param HTTP + * Server - Basic Authentication - Password + * @param HttpClient + * to use */ - public XMLRPCClient(URL url, String username, String password, HttpClient client) { + public XMLRPCClient(final URL url, final String username, final String password, final HttpClient client) { this(URI.create(url.toExternalForm()), username, password, client); } /** - * Sets basic authentication on web request using plain credentials - * @param username The plain text username - * @param password The plain text password - * @param doPreemptiveAuth Select here whether to authenticate without it being requested first by the server. + * Convenience method call with no parameters + * + * @param method + * name of method to call + * @return deserialized method return value + * @throws XMLRPCException */ - public void setBasicAuthentication(String username, String password, boolean doPreemptiveAuth) { - // This code required to trigger the patch created by erickok in issue #6 - if(doPreemptiveAuth = true) { - this.httpPreAuth = doPreemptiveAuth; - this.username = username; - this.password = password; - } else { - ((DefaultHttpClient) client).getCredentialsProvider().setCredentials(new AuthScope(postMethod.getURI().getHost(), postMethod.getURI().getPort(), AuthScope.ANY_REALM), new UsernamePasswordCredentials(username, password)); - } + public Object call(final String method) throws XMLRPCException { + return callEx(method, null); } /** - * Convenience Constructor: Sets basic authentication on web request using plain credentials - * @param username The plain text username - * @param password The plain text password - */ - public void setBasicAuthentication(String username, String password) { - setBasicAuthentication(username, password, false); - } - - /** - * Call method with optional parameters. This is general method. - * If you want to call your method with 0-8 parameters, you can use more - * convenience call() methods + * Convenience method call. This method replace countless other convenience + * methods * - * @param method name of method to call - * @param params parameters to pass to method (may be null if method has no parameters) + * @param method + * name of method to call + * @param params + * method's parameters + * @return deserialized method return value + * @throws XMLRPCException + * @author ricky barrette + */ + public Object call(final String method, final Object... params) throws XMLRPCException { + return callEx(method, params); + } + + /** + * Convenience method call with a vectorized parameter (Code contributed by + * jahbromo from issue #14) + * + * @param method + * name of method to call + * @param paramsv + * vector of method's parameter + * @return deserialized method return value + * @throws XMLRPCException + */ + + public Object call(final String method, final Vector paramsv) throws XMLRPCException { + final Object[] params = new Object[paramsv.size()]; + for (int i = 0; i < paramsv.size(); i++) + params[i] = paramsv.elementAt(i); + return callEx(method, params); + } + + /** + * Call method with optional parameters. This is general method. If you want + * to call your method with 0-8 parameters, you can use more convenience + * call() methods + * + * @param method + * name of method to call + * @param params + * parameters to pass to method (may be null if method has no + * parameters) * @return deserialized method return value * @throws XMLRPCException */ @SuppressWarnings("unchecked") - public Object callEx(String method, Object[] params) throws XMLRPCException { + public Object callEx(final String method, final Object[] params) throws XMLRPCException { try { // prepare POST body - String body = methodCall(method, params); + final String body = methodCall(method, params); // set POST body HttpEntity entity = new StringEntity(body); @@ -296,87 +413,89 @@ public class XMLRPCClient extends XMLRPCCommon { // This code slightly tweaked from the code by erickok in issue #6 // Force preemptive authentication - // This makes sure there is an 'Authentication: ' header being send before trying and failing and retrying + // This makes sure there is an 'Authentication: ' header being send + // before trying and failing and retrying // by the basic authentication mechanism of DefaultHttpClient - if(this.httpPreAuth == true) { - String auth = this.username + ":" + this.password; + if (httpPreAuth == true) { + final String auth = username + ":" + password; postMethod.addHeader("Authorization", "Basic " + Base64Coder.encode(auth.getBytes()).toString()); } - - //Log.d(Tag.LOG, "ros HTTP POST"); + + // Log.d(Tag.LOG, "ros HTTP POST"); // execute HTTP POST request - HttpResponse response = client.execute(postMethod); - //Log.d(Tag.LOG, "ros HTTP POSTed"); + final HttpResponse response = client.execute(postMethod); + // Log.d(Tag.LOG, "ros HTTP POSTed"); // check status code - int statusCode = response.getStatusLine().getStatusCode(); - //Log.d(Tag.LOG, "ros status code:" + statusCode); - if (statusCode != HttpStatus.SC_OK) { - throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK, statusCode); - } + final int statusCode = response.getStatusLine().getStatusCode(); + // Log.d(Tag.LOG, "ros status code:" + statusCode); + if (statusCode != HttpStatus.SC_OK) + throw new XMLRPCException("HTTP status code: " + statusCode + " != " + HttpStatus.SC_OK, statusCode); // parse response stuff // // setup pull parser - XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); + final XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); entity = response.getEntity(); - Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent())); -// for testing purposes only -// reader = new StringReader("\n\n\n"); + final Reader reader = new InputStreamReader(new BufferedInputStream(entity.getContent())); + // for testing purposes only + // reader = new + // StringReader("\n\n\n"); pullParser.setInput(reader); - + // lets start pulling... pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_RESPONSE); - - pullParser.nextTag(); // either Tag.PARAMS () or Tag.FAULT () - String tag = pullParser.getName(); + + pullParser.nextTag(); // either Tag.PARAMS () or Tag.FAULT + // () + final String tag = pullParser.getName(); if (tag.equals(Tag.PARAMS)) { // normal response pullParser.nextTag(); // Tag.PARAM () pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM); pullParser.nextTag(); // Tag.VALUE () - // no parser.require() here since its called in XMLRPCSerializer.deserialize() below - + // no parser.require() here since its called in + // XMLRPCSerializer.deserialize() below + // deserialize result - Object obj = iXMLRPCSerializer.deserialize(pullParser); + final Object obj = iXMLRPCSerializer.deserialize(pullParser); entity.consumeContent(); return obj; - } else - if (tag.equals(Tag.FAULT)) { + } else if (tag.equals(Tag.FAULT)) { // fault response pullParser.nextTag(); // Tag.VALUE () - // no parser.require() here since its called in XMLRPCSerializer.deserialize() below + // no parser.require() here since its called in + // XMLRPCSerializer.deserialize() below // deserialize fault result - Map map = (Map) iXMLRPCSerializer.deserialize(pullParser); - String faultString = (String) map.get(Tag.FAULT_STRING); - int faultCode = (Integer) map.get(Tag.FAULT_CODE); + final Map map = (Map) iXMLRPCSerializer.deserialize(pullParser); + final String faultString = (String) map.get(Tag.FAULT_STRING); + final int faultCode = (Integer) map.get(Tag.FAULT_CODE); entity.consumeContent(); throw new XMLRPCFault(faultString, faultCode); } else { entity.consumeContent(); throw new XMLRPCException("Bad tag <" + tag + "> in XMLRPC response - neither nor "); } - } catch (XMLRPCException e) { + } catch (final XMLRPCException e) { // catch & propagate XMLRPCException/XMLRPCFault throw e; - } catch (Exception e) { + } catch (final Exception e) { e.printStackTrace(); // wrap any other Exception(s) around XMLRPCException throw new XMLRPCException(e); } } - - private String methodCall(String method, Object[] params) - throws IllegalArgumentException, IllegalStateException, IOException { - StringWriter bodyWriter = new StringWriter(); + + private String methodCall(final String method, final Object[] params) throws IllegalArgumentException, IllegalStateException, IOException { + final StringWriter bodyWriter = new StringWriter(); serializer.setOutput(bodyWriter); serializer.startDocument(null, null); serializer.startTag(null, Tag.METHOD_CALL); // set method name serializer.startTag(null, Tag.METHOD_NAME).text(method).endTag(null, Tag.METHOD_NAME); - + serializeParams(params); serializer.endTag(null, Tag.METHOD_CALL); @@ -386,55 +505,50 @@ public class XMLRPCClient extends XMLRPCCommon { } /** - * Convenience method call with no parameters + * Convenience Constructor: Sets basic authentication on web request using + * plain credentials * - * @param method name of method to call - * @return deserialized method return value - * @throws XMLRPCException + * @param username + * The plain text username + * @param password + * The plain text password */ - public Object call(String method) throws XMLRPCException { - return callEx(method, null); - } - - /** - * Convenience method call with a vectorized parameter - * (Code contributed by jahbromo from issue #14) - * @param method name of method to call - * @param paramsv vector of method's parameter - * @return deserialized method return value - * @throws XMLRPCException - */ - - public Object call(String method, Vector paramsv) throws XMLRPCException { - Object[] params = new Object [paramsv.size()]; - for (int i=0; i, return empty string + return ""; + + Object obj; + boolean hasType = true; + String typeNodeName = null; + try { + parser.nextTag(); + typeNodeName = parser.getName(); + if (typeNodeName.equals(TAG_VALUE) && parser.getEventType() == XmlPullParser.END_TAG) + // empty , return empty string + return ""; + + } catch (final XmlPullParserException e) { + hasType = false; + } + if (hasType) { + // This code submitted by mattias.ellback in issue #19 + if (typeNodeName.equals(TYPE_NULL)) { + parser.nextTag(); + obj = null; + } else if (typeNodeName.equals(TYPE_INT) || typeNodeName.equals(TYPE_I4)) { + final String value = parser.nextText(); + obj = Integer.parseInt(value); + } else if (typeNodeName.equals(TYPE_I8)) { + final String value = parser.nextText(); + obj = Long.parseLong(value); + } else if (typeNodeName.equals(TYPE_DOUBLE)) { + final String value = parser.nextText(); + obj = Double.parseDouble(value); + } else if (typeNodeName.equals(TYPE_BOOLEAN)) { + final String value = parser.nextText(); + obj = value.equals("1") ? Boolean.TRUE : Boolean.FALSE; + } else if (typeNodeName.equals(TYPE_STRING)) + obj = parser.nextText(); + else if (typeNodeName.equals(TYPE_DATE_TIME_ISO8601)) { + final String value = parser.nextText(); + try { + obj = dateFormat.parseObject(value); + } catch (final ParseException e) { + throw new IOException("Cannot deserialize dateTime " + value); + } + } else if (typeNodeName.equals(TYPE_BASE64)) { + final String value = parser.nextText(); + final BufferedReader reader = new BufferedReader(new StringReader(value)); + String line; + final StringBuffer sb = new StringBuffer(); + while ((line = reader.readLine()) != null) + sb.append(line); + obj = Base64Coder.decode(sb.toString()); + } else if (typeNodeName.equals(TYPE_ARRAY)) { + parser.nextTag(); // TAG_DATA () + parser.require(XmlPullParser.START_TAG, null, TAG_DATA); + + parser.nextTag(); + final List list = new ArrayList(); + while (parser.getName().equals(TAG_VALUE)) { + list.add(deserialize(parser)); + parser.nextTag(); + } + parser.require(XmlPullParser.END_TAG, null, TAG_DATA); + parser.nextTag(); // TAG_ARRAY () + parser.require(XmlPullParser.END_TAG, null, TYPE_ARRAY); + obj = list.toArray(); + } else if (typeNodeName.equals(TYPE_STRUCT)) { + parser.nextTag(); + final Map map = new HashMap(); + while (parser.getName().equals(TAG_MEMBER)) { + String memberName = null; + Object memberValue = null; + while (true) { + parser.nextTag(); + final String name = parser.getName(); + if (name.equals(TAG_NAME)) + memberName = parser.nextText(); + else if (name.equals(TAG_VALUE)) + memberValue = deserialize(parser); + else + break; + } + if (memberName != null && memberValue != null) + map.put(memberName, memberValue); + parser.require(XmlPullParser.END_TAG, null, TAG_MEMBER); + parser.nextTag(); + } + parser.require(XmlPullParser.END_TAG, null, TYPE_STRUCT); + obj = map; + } else + throw new IOException("Cannot deserialize " + parser.getName()); + } else + // TYPE_STRING () is not required + obj = parser.getText(); + parser.nextTag(); // TAG_VALUE () + parser.require(XmlPullParser.END_TAG, null, TAG_VALUE); + return obj; + } + + @Override @SuppressWarnings("unchecked") - public void serialize(XmlSerializer serializer, Object object) throws IOException { + public void serialize(final XmlSerializer serializer, final Object object) throws IOException { // This code supplied by mattias.ellback as part of issue #19 - if (object == null){ - serializer.startTag(null, TYPE_NULL).endTag(null, TYPE_NULL); - } else + if (object == null) + serializer.startTag(null, TYPE_NULL).endTag(null, TYPE_NULL); + else // check for scalar types: - if (object instanceof Integer || object instanceof Short || object instanceof Byte) { + if (object instanceof Integer || object instanceof Short || object instanceof Byte) serializer.startTag(null, TYPE_I4).text(object.toString()).endTag(null, TYPE_I4); - } else - if (object instanceof Long) { + else if (object instanceof Long) serializer.startTag(null, TYPE_I8).text(object.toString()).endTag(null, TYPE_I8); - } else - if (object instanceof Double || object instanceof Float) { + else if (object instanceof Double || object instanceof Float) serializer.startTag(null, TYPE_DOUBLE).text(object.toString()).endTag(null, TYPE_DOUBLE); - } else - if (object instanceof Boolean) { - Boolean bool = (Boolean) object; - String boolStr = bool.booleanValue() ? "1" : "0"; + else if (object instanceof Boolean) { + final Boolean bool = (Boolean) object; + final String boolStr = bool.booleanValue() ? "1" : "0"; serializer.startTag(null, TYPE_BOOLEAN).text(boolStr).endTag(null, TYPE_BOOLEAN); - } else - if (object instanceof String) { + } else if (object instanceof String) serializer.startTag(null, TYPE_STRING).text(object.toString()).endTag(null, TYPE_STRING); - } else - if (object instanceof Date || object instanceof Calendar) { - String dateStr = dateFormat.format(object); + else if (object instanceof Date || object instanceof Calendar) { + final String dateStr = dateFormat.format(object); serializer.startTag(null, TYPE_DATE_TIME_ISO8601).text(dateStr).endTag(null, TYPE_DATE_TIME_ISO8601); - } else - if (object instanceof byte[] ){ - String value = new String(Base64Coder.encode((byte[])object)); + } else if (object instanceof byte[]) { + final String value = new String(Base64Coder.encode((byte[]) object)); serializer.startTag(null, TYPE_BASE64).text(value).endTag(null, TYPE_BASE64); - } else - if (object instanceof List) { + } else if (object instanceof List) { serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA); - List list = (List) object; - Iterator iter = list.iterator(); + final List list = (List) object; + final Iterator iter = list.iterator(); while (iter.hasNext()) { - Object o = iter.next(); + final Object o = iter.next(); serializer.startTag(null, TAG_VALUE); serialize(serializer, o); serializer.endTag(null, TAG_VALUE); } serializer.endTag(null, TAG_DATA).endTag(null, TYPE_ARRAY); - } else - if (object instanceof Object[]) { + } else if (object instanceof Object[]) { serializer.startTag(null, TYPE_ARRAY).startTag(null, TAG_DATA); - Object[] objects = (Object[]) object; - for (int i=0; i map = (Map) object; - Iterator> iter = map.entrySet().iterator(); + final Map map = (Map) object; + final Iterator> iter = map.entrySet().iterator(); while (iter.hasNext()) { - Entry entry = iter.next(); - String key = entry.getKey(); - Object value = entry.getValue(); + final Entry entry = iter.next(); + final String key = entry.getKey(); + final Object value = entry.getValue(); serializer.startTag(null, TAG_MEMBER); serializer.startTag(null, TAG_NAME).text(key).endTag(null, TAG_NAME); @@ -95,132 +188,10 @@ class XMLRPCSerializer implements IXMLRPCSerializer { serializer.endTag(null, TAG_MEMBER); } serializer.endTag(null, TYPE_STRUCT); - } else - if (object instanceof XMLRPCSerializable) { - XMLRPCSerializable serializable = (XMLRPCSerializable) object; + } else if (object instanceof XMLRPCSerializable) { + final XMLRPCSerializable serializable = (XMLRPCSerializable) object; serialize(serializer, serializable.getSerializable()); - } else { + } else throw new IOException("Cannot serialize " + object); - } - } - - public Object deserialize(XmlPullParser parser) throws XmlPullParserException, IOException { - parser.require(XmlPullParser.START_TAG, null, TAG_VALUE); - - if (parser.isEmptyElementTag()) { - // degenerated , return empty string - return ""; - } - - Object obj; - boolean hasType = true; - String typeNodeName = null; - try { - parser.nextTag(); - typeNodeName = parser.getName(); - if (typeNodeName.equals(TAG_VALUE) && parser.getEventType() == XmlPullParser.END_TAG) { - // empty , return empty string - return ""; - } - - - } catch (XmlPullParserException e) { - hasType = false; - } - if (hasType) { - // This code submitted by mattias.ellback in issue #19 - if (typeNodeName.equals(TYPE_NULL)){ - parser.nextTag(); - obj = null; - } - else - if (typeNodeName.equals(TYPE_INT) || typeNodeName.equals(TYPE_I4)) { - String value = parser.nextText(); - obj = Integer.parseInt(value); - } else - if (typeNodeName.equals(TYPE_I8)) { - String value = parser.nextText(); - obj = Long.parseLong(value); - } else - if (typeNodeName.equals(TYPE_DOUBLE)) { - String value = parser.nextText(); - obj = Double.parseDouble(value); - } else - if (typeNodeName.equals(TYPE_BOOLEAN)) { - String value = parser.nextText(); - obj = value.equals("1") ? Boolean.TRUE : Boolean.FALSE; - } else - if (typeNodeName.equals(TYPE_STRING)) { - obj = parser.nextText(); - } else - if (typeNodeName.equals(TYPE_DATE_TIME_ISO8601)) { - String value = parser.nextText(); - try { - obj = dateFormat.parseObject(value); - } catch (ParseException e) { - throw new IOException("Cannot deserialize dateTime " + value); - } - } else - if (typeNodeName.equals(TYPE_BASE64)) { - String value = parser.nextText(); - BufferedReader reader = new BufferedReader(new StringReader(value)); - String line; - StringBuffer sb = new StringBuffer(); - while ((line = reader.readLine()) != null) { - sb.append(line); - } - obj = Base64Coder.decode(sb.toString()); - } else - if (typeNodeName.equals(TYPE_ARRAY)) { - parser.nextTag(); // TAG_DATA () - parser.require(XmlPullParser.START_TAG, null, TAG_DATA); - - parser.nextTag(); - List list = new ArrayList(); - while (parser.getName().equals(TAG_VALUE)) { - list.add(deserialize(parser)); - parser.nextTag(); - } - parser.require(XmlPullParser.END_TAG, null, TAG_DATA); - parser.nextTag(); // TAG_ARRAY () - parser.require(XmlPullParser.END_TAG, null, TYPE_ARRAY); - obj = list.toArray(); - } else - if (typeNodeName.equals(TYPE_STRUCT)) { - parser.nextTag(); - Map map = new HashMap(); - while (parser.getName().equals(TAG_MEMBER)) { - String memberName = null; - Object memberValue = null; - while (true) { - parser.nextTag(); - String name = parser.getName(); - if (name.equals(TAG_NAME)) { - memberName = parser.nextText(); - } else - if (name.equals(TAG_VALUE)) { - memberValue = deserialize(parser); - } else { - break; - } - } - if (memberName != null && memberValue != null) { - map.put(memberName, memberValue); - } - parser.require(XmlPullParser.END_TAG, null, TAG_MEMBER); - parser.nextTag(); - } - parser.require(XmlPullParser.END_TAG, null, TYPE_STRUCT); - obj = map; - } else { - throw new IOException("Cannot deserialize " + parser.getName()); - } - } else { - // TYPE_STRING () is not required - obj = parser.getText(); - } - parser.nextTag(); // TAG_VALUE () - parser.require(XmlPullParser.END_TAG, null, TAG_VALUE); - return obj; } } diff --git a/OSJ Forum/src/org/xmlrpc/android/XMLRPCServer.java b/OSJ Forum/src/org/xmlrpc/android/XMLRPCServer.java index 3b4ff75..ac94dc3 100644 --- a/OSJ Forum/src/org/xmlrpc/android/XMLRPCServer.java +++ b/OSJ Forum/src/org/xmlrpc/android/XMLRPCServer.java @@ -16,26 +16,35 @@ import android.util.Log; public class XMLRPCServer extends XMLRPCCommon { - private static final String CRLF = "\r\n"; - private static final String RESPONSE = - "HTTP/1.1 200 OK" + CRLF + - "Connection: close" + CRLF + - "Content-Type: text/xml" + CRLF + - "Content-Length: "; + private static final String CRLF = "\r\n"; + private static final String RESPONSE = "HTTP/1.1 200 OK" + CRLF + "Connection: close" + CRLF + "Content-Type: text/xml" + CRLF + "Content-Length: "; private static final String NEWLINES = CRLF + CRLF; - private XMLRPCSerializer iXMLRPCSerializer; + private final XMLRPCSerializer iXMLRPCSerializer; public XMLRPCServer() { iXMLRPCSerializer = new XMLRPCSerializer(); } - public MethodCall readMethodCall(Socket socket) throws IOException, XmlPullParserException - { - MethodCall methodCall = new MethodCall(); - InputStream inputStream = socket.getInputStream(); + private String methodResponse(final Object value) throws IllegalArgumentException, IllegalStateException, IOException { + final StringWriter bodyWriter = new StringWriter(); + serializer.setOutput(bodyWriter); + serializer.startDocument(null, null); + serializer.startTag(null, Tag.METHOD_RESPONSE); + + serializeParams(value); + + serializer.endTag(null, Tag.METHOD_RESPONSE); + serializer.endDocument(); + + return bodyWriter.toString(); + } + + public MethodCall readMethodCall(final Socket socket) throws IOException, XmlPullParserException { + final MethodCall methodCall = new MethodCall(); + final InputStream inputStream = socket.getInputStream(); + + final XmlPullParser pullParser = xmlPullParserFromSocket(inputStream); - XmlPullParser pullParser = xmlPullParserFromSocket(inputStream); - pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.METHOD_CALL); pullParser.nextTag(); @@ -46,13 +55,14 @@ public class XMLRPCServer extends XMLRPCCommon { pullParser.nextTag(); pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAMS); pullParser.nextTag(); // possible optional or - - while (pullParser.getName().equals(Tag.PARAM)) { // - //Log.d(Tag.LOG, "type=" + pullParser.getEventType() + ", tag=" + pullParser.getName()); + + while (pullParser.getName().equals(Tag.PARAM)) { // + // Log.d(Tag.LOG, "type=" + pullParser.getEventType() + ", tag=" + + // pullParser.getName()); pullParser.require(XmlPullParser.START_TAG, null, Tag.PARAM); pullParser.nextTag(); // - Object param = iXMLRPCSerializer.deserialize(pullParser); + final Object param = iXMLRPCSerializer.deserialize(pullParser); methodCall.params.add(param); // add to return value pullParser.nextTag(); @@ -62,40 +72,27 @@ public class XMLRPCServer extends XMLRPCCommon { return methodCall; } - - XmlPullParser xmlPullParserFromSocket(InputStream socketInputStream) throws IOException, XmlPullParserException { - String line; - BufferedReader br = new BufferedReader(new InputStreamReader(socketInputStream)); - while ((line = br.readLine()) != null && line.length() > 0); // eat the HTTP POST headers - - XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); - pullParser.setInput(br); - return pullParser; - } - public void respond(Socket socket, Object value) throws IOException { + public void respond(final Socket socket, final Object value) throws IOException { - String content = methodResponse(value); - String response = RESPONSE + (content.length()) + NEWLINES + content; - OutputStream outputStream = socket.getOutputStream(); + final String content = methodResponse(value); + final String response = RESPONSE + content.length() + NEWLINES + content; + final OutputStream outputStream = socket.getOutputStream(); outputStream.write(response.getBytes()); outputStream.flush(); outputStream.close(); socket.close(); Log.d(Tag.LOG, "response:" + response); } - - private String methodResponse(Object value) throws IllegalArgumentException, IllegalStateException, IOException { - StringWriter bodyWriter = new StringWriter(); - serializer.setOutput(bodyWriter); - serializer.startDocument(null, null); - serializer.startTag(null, Tag.METHOD_RESPONSE); - - serializeParams(value); - serializer.endTag(null, Tag.METHOD_RESPONSE); - serializer.endDocument(); - - return bodyWriter.toString(); + XmlPullParser xmlPullParserFromSocket(final InputStream socketInputStream) throws IOException, XmlPullParserException { + String line; + final BufferedReader br = new BufferedReader(new InputStreamReader(socketInputStream)); + while ((line = br.readLine()) != null && line.length() > 0) + ; // eat the HTTP POST headers + + final XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); + pullParser.setInput(br); + return pullParser; } } \ No newline at end of file