public class JcertifApplication extends Application{

	//public static final String BASE_URL="http://jcertif-backend.msomda.cloudbees.net";
	public static final String BASE_URL="http://jcertif.backend.vm-host.net";

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	@Override
	public void onLowMemory() {
		// TODO Auto-generated method stub
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		// TODO Auto-generated method stub
		super.onTerminate();
	}

    public Boolean isApplicationConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        return networkInfo != null && networkInfo.isConnected();
    }


	
} public class MainActivity extends SherlockFragmentActivity implements LoginFragment.OnSignedInListener,
		RefentielDataLodedListener, PullToRefreshAttacher.OnRefreshListener {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	private String[] mMenuTitles;
	private UserProvider userProvider;
	public static Participant user;

	private PullToRefreshAttacher mPullToRefreshAttacher;

	// preference twitter pour le stockage des cles du user
	private static SharedPreferences mSharedPreferences;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
		// getWindow().requestFeature((int)
		// com.actionbarsherlock.view.Window.FEATURE_ACTION_BAR_OVERLAY);
		setContentView(R.layout.activity_main);

		// enable ActionBar app icon to behave as action to toggle nav drawer
		getSupportActionBar().setDisplayUseLogoEnabled(true);
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		getSupportActionBar().setHomeButtonEnabled(true);

        mPullToRefreshAttacher = PullToRefreshAttacher.get(this);

		mTitle = mDrawerTitle = getTitle();
		mMenuTitles = getResources().getStringArray(R.array.menu_array);
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		// set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
		// set up the drawer's list view with items and click listener
		mDrawerList.setAdapter(new DrawerListAdapter(getLoggedInUser()));
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		mDrawerLayout, /* DrawerLayout object */
		R.drawable.ic_navigation_drawer, /*
										 * nav drawer image to replace 'Up'
										 * caret
										 */
		R.string.drawer_open, /* "open drawer" description for accessibility */
		R.string.drawer_close /* "close drawer" description for accessibility */
		) {
			public void onDrawerClosed(View view) {
				getSupportActionBar().setTitle(mTitle);
				supportInvalidateOptionsMenu(); // creates call to
												// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getSupportActionBar().setTitle(mDrawerTitle);

			}
		};
		mDrawerLayout.setDrawerListener(mDrawerToggle);

		mSharedPreferences = getApplicationContext().getSharedPreferences(Config.PREFERENCE_JCERTIF_TWITTER, 0);

		if (savedInstanceState == null) {
			init();
		}
		if (firstLaunch()) {
			selectItem(8);
		}

		// setupUpdateService();

	}

	public PullToRefreshAttacher getmPullToRefreshAttacher() {
		return mPullToRefreshAttacher;
	}

	@Override
	public void onBackPressed() {

		if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
			mDrawerLayout.closeDrawer(Gravity.LEFT);
		} else {
			super.onBackPressed();
		}

	}

	void init() {
		selectItem(0);
		mDrawerLayout.setVisibility(View.VISIBLE);
		mDrawerLayout.openDrawer(Gravity.LEFT);
	}

	private boolean firstLaunch() {
		return new CategorieProvider(this).getLabels().length == 0;
	}

	private Participant getLoggedInUser() {
		if (user == null) {
			userProvider = new UserProvider(this);
			List<Participant> list = userProvider.getAll(Participant.class);
			if (list != null && !list.isEmpty()) {
				user = list.get(0);
			}
			userProvider.close();
		}
		return user;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
				mDrawerLayout.closeDrawer(mDrawerList);
			} else {
				mDrawerLayout.openDrawer(mDrawerList);
			}

		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// getSupportMenuInflater().inflate(R.menu.main, menu);
		return super.onCreateOptionsMenu(menu);
	}

	/* The click listner for ListView in the navigation drawer */
	private class DrawerItemClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
			view.setSelected(true);
			selectItem(position);
		}
	}

	private void selectItem(int position) {
		// update the main content by replacing fragments
		Fragment fragment = null;

		switch (position) {
		case 0:
			if (getLoggedInUser() == null) {
				fragment = new LoginFragment();
				// Apres authentification via le navigateur par defaut, deuxieme
				// phase de
				// la connexion vers twitter
				Bundle bundle = new Bundle();
				if (!mSharedPreferences.getBoolean(Config.PREF_KEY_TWITTER_LOGIN, false)) {
					Uri uri = getIntent().getData();
					if (uri != null && uri.toString().startsWith(Config.TWITTER_CALLBACK_URL)) {
						// oAuth verifier
						final String verifier = uri.getQueryParameter(Config.URL_TWITTER_OAUTH_VERIFIER);
						bundle.putString("params", verifier);
					}
				}

				fragment.setArguments(bundle);
			} else {
				fragment = new ProfileFragment();
			}
			break;
		case 1:
			fragment = new SessionParentFragment();
			break;
		case 2:
			fragment = new SpeakerParentFragment();
			break;
		case 3:
			fragment = new MapEventFragment();
			break;

		case 4:
			// fragment = new AboutFragment();
			startActivity(new Intent(MainActivity.this, AboutFragmentActivity.class));
			break;
		case 8:
			fragment = new InitialisationFragment();
			((InitialisationFragment) fragment).setListener(this);
			// mDrawerLayout.setVisibility(View.INVISIBLE);
			break;
		default:
			break;
		}

		FragmentManager fragmentManager = getSupportFragmentManager();
		if (fragment == null) {
			return;
		}

		fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

		mDrawerList.setItemChecked(position, true);
		mDrawerLayout.closeDrawer(mDrawerList);

	}

	@Override
	public void setTitle(CharSequence title) {
		mTitle = title;
		getSupportActionBar().setTitle(mTitle);
	}

	/**
	 * When using the ActionBarDrawerToggle, you must call it during
	 * onPostCreate() and onConfigurationChanged()...
	 */

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggls
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

    class DrawerListAdapter extends BaseAdapter {

        private static final int TYPE_PROFILE = 0;
        private static final int TYPE_ITEM = 1;
        private LayoutInflater mInflater;

        private Participant user;

        public int getCount() {
            return mMenuTitles.length + 1;
        }

        public DrawerListAdapter(Participant user) {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            this.user = user;
        }

        @Override
        public Object getItem(int position) {
            if (position == 0) {
                return 0;
            } else
                return mMenuTitles[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int type = getItemViewType(position);
            if (convertView == null) {
                holder = new ViewHolder();
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            switch (type) {
                case TYPE_ITEM:
                    convertView = convertView == null?mInflater.inflate(R.layout.drawer_list_item, null):convertView;
                    holder.textView = (TextView) convertView.findViewById(R.id.tv_drawer_item);

                    holder.imgView = (ImageView) convertView.findViewById(R.id.img_drawer);
                    holder=setTypeItemHolderValues(holder,position);

                    break;
                case TYPE_PROFILE:
                    convertView = convertView == null?mInflater.inflate(R.layout.item_profile, null):convertView;
                    holder.textView = (TextView) convertView.findViewById(R.id.tv_username);
                    holder.imgView = (ImageView) convertView.findViewById(R.id.img_profile);
                    holder=setTypeProfilHolderValues(holder,user);
                    break;
            }
            convertView.setTag(holder);

            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return (position == 0) ? TYPE_PROFILE : TYPE_ITEM;
        }

        @Override
        public int getViewTypeCount() {
            return 2;
        }

        public class ViewHolder {
            public TextView textView;
            public ImageView imgView;
        }

        /**
         *
         * @param holder
         * @param itemPosition
         * @return
         */
        private ViewHolder setTypeItemHolderValues(ViewHolder holder,int itemPosition){
            switch (itemPosition) {
                case 1:
                    holder.imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_list));
                    break;
                case 2:
                    holder.imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_user));
                    break;

                case 3:
                    holder.imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_map));
                    break;

                case 4:
                    holder.imgView.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_help));
                    break;
                default:
                    break;
            }
            holder.textView.setText(mMenuTitles[itemPosition - 1]);
            return holder;
        }

        /**
         *
         * @param holder
         * @param user
         * @return
         */
        private ViewHolder setTypeProfilHolderValues(ViewHolder holder,Participant user){

            if (user == null) {
                holder.textView.setText("Please Login");
            } else {
                holder.textView.setText(user.getFirstname() + " " + user.getLastname());
                Picasso.with(MainActivity.this).load(user.getPhoto()).placeholder(R.drawable.ic_action_profile)
                        .into(holder.imgView);
            }

            return holder;
        }

    }


    @Override
	public void onSignedIn(Participant user, ProgressDialog dlg) {

		mDrawerList.setAdapter(new DrawerListAdapter(user));
		setLogedInUser(user);
		selectItem(0);
		mDrawerLayout.openDrawer(Gravity.LEFT);

		dlg.dismiss();
	}

	private void setLogedInUser(Participant user) {
		MainActivity.user = user;
		userProvider = new UserProvider(this);
		userProvider.store(user);
		userProvider.close();
	}

	@Override
	public void OnRefDataLoaded() {
		init();
	}

	void setupUpdateService() {
		Calendar calendar = Calendar.getInstance();
		// 9 AM
		calendar.set(Calendar.HOUR_OF_DAY, 16);
		calendar.set(Calendar.MINUTE, 42);
		calendar.set(Calendar.SECOND, 0);
		Intent intent = new Intent(this, UpdaterBroadcast.class);

		PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, 0);

		AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
		am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
	}

	@Override
	public void onRefreshStarted(View view) {

	}
} public class CategorieProvider extends JCertifDb4oHelper<Category>{

	public CategorieProvider(Context ctx) {
		super(ctx);
	}

	public String[] getLabels() {
				
		List<Category> cats=getAll(Category.class);
		ArrayList<String> mlist= new ArrayList<String>();
		for(int i=0; i<cats.size();i++){
			Category ci=cats.get(i);
			mlist.add(ci.getLabel());
		}
		String[] labels=new String[mlist.size()];
		labels= mlist.toArray(labels);
		
		return labels;
	}
	
} public class ContributorProvider extends JCertifDb4oHelper<Contributor>{

	public ContributorProvider(Context ctx) {
		super(ctx);
		
	}

} public class SessionProvider extends JCertifDb4oHelper<Session> {

	public SessionProvider(Context ctx) {
		super(ctx);
	}

	public List<Session> getSessionsByCategory(final String categorie) {
		List<Session> list = new ArrayList<Session>();
		list = db().query(new Predicate<Session>() {
			@Override
			public boolean match(Session test) {
				return Arrays.asList(test.getCategory()).contains(categorie);
			}
		});
		return list;

	}

	public List<Session> getAllSessionOfSpeaker(final String speakerId) {
		List<Session> list = new ArrayList<Session>();
		List<Session>	test = getAll(Session.class);
		
		for(Session s: test){
			if(Arrays.asList(s.getSpeakers()).contains(speakerId)){
				list.add(s);
			}
		}
		return list;
	}
	

} public class SpeakerProvider extends JCertifDb4oHelper<Speaker> {

	public SpeakerProvider(Context ctx) {
		super(ctx);
	}

	
	public Speaker getByEmail(final String email) {
		List<Speaker> list =getAll(Speaker.class);
		if (!list.isEmpty())
		for(Speaker s: list){
			if(s.getEmail().equals(email)){
				return s;
			}
		}
			return new Speaker();
	}




	
} public class SponsorLevelProvider extends JCertifDb4oHelper<SponsorLevel> {

	public SponsorLevelProvider(Context ctx) {
		super(ctx);
	}

} public class SponsorProvider extends JCertifDb4oHelper<Sponsor> {

	public SponsorProvider(Context ctx) {
		super(ctx);
		
	}

} public class Category extends JCertifObject{

	private String label;

	public Category(String label) {
		super();
		this.label = label;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}
	
	
} public class Contributor {

	private int id;
	private String login;
	private String avatar_url;
	private String gravatar_id;
	private String url;
	private String html_url;
	private String followers_url;
	private String following_url;
	private String gists_url;
	private String starred_url;
	private String subscriptions_url;
	private String organizations_url;
	private String repos_url;
	private String events_url;
	private String received_events_url;
	private String type;
	private int contributions;
	
	
	public Contributor() {
		super();
	}


	public Contributor(int id, String login, String avatar_url,
			String gravatar_id, String url, String html_url,
			String followers_url, String following_url, String gists_url,
			String starred_url, String subscriptions_url,
			String organizations_url, String repos_url, String events_url,
			String received_events_url, String type, int contributions) {
		super();
		this.id = id;
		this.login = login;
		this.avatar_url = avatar_url;
		this.gravatar_id = gravatar_id;
		this.url = url;
		this.html_url = html_url;
		this.followers_url = followers_url;
		this.following_url = following_url;
		this.gists_url = gists_url;
		this.starred_url = starred_url;
		this.subscriptions_url = subscriptions_url;
		this.organizations_url = organizations_url;
		this.repos_url = repos_url;
		this.events_url = events_url;
		this.received_events_url = received_events_url;
		this.type = type;
		this.contributions = contributions;
	}


	public int getId() {
		return id;
	}


	public void setId(int id) {
		this.id = id;
	}


	public String getLogin() {
		return login;
	}


	public void setLogin(String login) {
		this.login = login;
	}


	public String getAvatar_url() {
		return avatar_url;
	}


	public void setAvatar_url(String avatar_url) {
		this.avatar_url = avatar_url;
	}


	public String getGravatar_id() {
		return gravatar_id;
	}


	public void setGravatar_id(String gravatar_id) {
		this.gravatar_id = gravatar_id;
	}


	public String getUrl() {
		return url;
	}


	public void setUrl(String url) {
		this.url = url;
	}


	public String getHtml_url() {
		return html_url;
	}


	public void setHtml_url(String html_url) {
		this.html_url = html_url;
	}


	public String getFollowers_url() {
		return followers_url;
	}


	public void setFollowers_url(String followers_url) {
		this.followers_url = followers_url;
	}


	public String getFollowing_url() {
		return following_url;
	}


	public void setFollowing_url(String following_url) {
		this.following_url = following_url;
	}


	public String getGists_url() {
		return gists_url;
	}


	public void setGists_url(String gists_url) {
		this.gists_url = gists_url;
	}


	public String getStarred_url() {
		return starred_url;
	}


	public void setStarred_url(String starred_url) {
		this.starred_url = starred_url;
	}


	public String getSubscriptions_url() {
		return subscriptions_url;
	}


	public void setSubscriptions_url(String subscriptions_url) {
		this.subscriptions_url = subscriptions_url;
	}


	public String getOrganizations_url() {
		return organizations_url;
	}


	public void setOrganizations_url(String organizations_url) {
		this.organizations_url = organizations_url;
	}


	public String getRepos_url() {
		return repos_url;
	}


	public void setRepos_url(String repos_url) {
		this.repos_url = repos_url;
	}


	public String getEvents_url() {
		return events_url;
	}


	public void setEvents_url(String events_url) {
		this.events_url = events_url;
	}


	public String getReceived_events_url() {
		return received_events_url;
	}


	public void setReceived_events_url(String received_events_url) {
		this.received_events_url = received_events_url;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}


	public int getContributions() {
		return contributions;
	}


	public void setContributions(int contributions) {
		this.contributions = contributions;
	}
	
	
	
} public class Session extends JCertifObject{

	
	private long id;
	private String title;
	private String summary;
	private String description;
	private String status;
	private String keyword;
	private String[] category;
    private Date start;
	private Date end;
	private String[] speakers;
	private int room;
	
	
	
	public Session() {
		super();
	}

    public Session(int id, String title, String summary, String description, String status, String keyword, String[] category,Date start, Date end, String[] speakers, int salle, int version, boolean deleted) {
        super(version, deleted);
        this.id = id;
        this.title = title;
        this.summary = summary;
        this.description = description;
        this.status = status;
        this.keyword = keyword;
        this.category = category;
        this.start=start;
        this.end = end;
        this.speakers = speakers;
        this.room = salle;
    }

	public Session(int id, String title, String summary, String description,
			String status, String keyword, String[] category,Date start, Date end,
			String[] speakers, int salle, String version) {
		super();
		this.id = id;
		this.title = title;
		this.summary = summary;
		this.description = description;
		this.status = status;
		this.keyword = keyword;
		this.category = category;
                this.start=start;
		this.end = end;
		this.speakers = speakers;
		this.room = salle;
		
	}




	public long getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public String getSummary() {
		return summary;
	}

	public void setSummary(String summary) {
		this.summary = summary;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}

	public String getKeyword() {
		return keyword;
	}

	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}

	public String[] getCategory() {
		return category;
	}

	public void setCategory(String[] category) {
		this.category = category;
	}

	public Date getEnd() {
		return end;
	}

	public void setEnd(Date end) {
		this.end = end;
	}

	public String[] getSpeakers() {
		return speakers;
	}

	public void setSpeakers(String[] speakers) {
		this.speakers = speakers;
	}

	public int getSalle() {
		return room;
	}

	public void setSalle(int salle) {
		this.room = salle;
	}

    public Date getStart() {
        return start;
    }

    public void setStart(Date start) {
        this.start = start;
    }

	
	
	
	
} public class Speaker extends Member {

} public class Sponsor extends Member {

	
    private String name;
    private String logo;	
    private String level;	
    private String about;
    
	public Sponsor(String name, String logo, String level, String about) {
		super();
		this.name = name;
		this.logo = logo;
		this.level = level;
		this.about = about;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getLogo() {
		return logo;
	}
	public void setLogo(String logo) {
		this.logo = logo;
	}
	public String getLevel() {
		return level;
	}
	public void setLevel(String level) {
		this.level = level;
	}
	public String getAbout() {
		return about;
	}
	public void setAbout(String about) {
		this.about = about;
	}
    
    
    
} public class SponsorLevel extends JCertifObject {

	private String label;

	public SponsorLevel(String label) {
		super();
		this.label = label;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}
	
	
} public class RESTService extends IntentService {

	private static final String TAG = RESTService.class.getName();

	public static final int GET = 0x1;
	public static final int POST = 0x2;
	public static final int PUT = 0x3;
	public static final int DELETE = 0x4;

	public static final String EXTRA_HTTP_VERB = "com.jcertif.android.EXTRA_HTTP_VERB";
	public static final String EXTRA_PARAMS = "com.jcertif.android.EXTRA_PARAMS";
	public static final String EXTRA_RESULT_RECEIVER = "com.jcertif.android.EXTRA_RESULT_RECEIVER";

	public static final String REST_RESULT = "com.jcertif.android.REST_RESULT";
	public static final String KEY_JSON_PLAYLOAD = "com.jcertif.android.JSON_PLAYLOAD";
	public static final String KEY_URI_SENT = "com.jcertif.android.URI_SENT";

	public RESTService() {
		super(TAG);
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// When an intent is received by this Service, this method
		// is called on a new thread.

		Uri action = intent.getData();
		Bundle extras = intent.getExtras();

		if (extras == null || action == null
				|| !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
			// Extras contain our ResultReceiver and data is our REST action.
			Log.e(TAG, "You did not pass extras or data with the Intent.");
			return;
		}

		// We default to GET if no verb was specified.
		int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
		Bundle params = extras.getParcelable(EXTRA_PARAMS);
		ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

		try {
			// Here we define our base request object which we will
			// send to our REST service via HttpClient.
			HttpRequestBase request = null;

			// Let's build our request based on the HTTP verb we were
			// given.
			switch (verb) {
			case GET: {
				request = new HttpGet();
				attachUriWithQuery(request, action, params);
			}
				break;

			case DELETE: {
				request = new HttpDelete();
				attachUriWithQuery(request, action, params);
			}
				break;

			case POST: {
				request = new HttpPost();
				request.setURI(new URI(action.toString()));

				request.setHeader("Content-Type", "application/json");
				HttpPost postRequest = (HttpPost) request;

				if (params != null) {
					StringEntity formEntity = new StringEntity(
							params.getString(KEY_JSON_PLAYLOAD));
					postRequest.setEntity(formEntity);
				}
			}
				break;

			case PUT: {
				request = new HttpPut();
				request.setURI(new URI(action.toString()));

				// Attach form entity if necessary.
				HttpPut putRequest = (HttpPut) request;

				if (params != null) {
					StringEntity formEntity = new StringEntity(
							params.getString(KEY_JSON_PLAYLOAD));
					putRequest.setEntity(formEntity);
				}
			}
				break;
			}

			if (request != null) {
				HttpClient client = new DefaultHttpClient();

				// Let's send some useful debug information so we can monitor
				// things
				// in LogCat.
				Log.d(TAG, "Executing request: " + verbToString(verb) + ": "
						+ action.toString());

				// Finally, we send our request using HTTP. This is the
				// synchronous
				// long operation that we need to run on this thread.
				HttpResponse response = client.execute(request);

				HttpEntity responseEntity = response.getEntity();
				StatusLine responseStatus = response.getStatusLine();
				int statusCode = responseStatus != null ? responseStatus
						.getStatusCode() : 0;

				// Our ResultReceiver allows us to communicate back the results
				// to the caller. This
				// class has a method named send() that can send back a code and
				// a Bundle
				// of data. ResultReceiver and IntentService abstract away all
				// the IPC code
				// we would need to write to normally make this work.
				if (responseEntity != null) {
					Bundle resultData = new Bundle();
					resultData.putString(REST_RESULT,
							EntityUtils.toString(responseEntity));
					resultData.putString(KEY_URI_SENT,
							action.toString());
					receiver.send(statusCode, resultData);
				} else {
					receiver.send(statusCode, null);
				}
			}
		} catch (URISyntaxException e) {
			Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": "
					+ action.toString(), e);
			receiver.send(0, null);
		} catch (UnsupportedEncodingException e) {
			Log.e(TAG,
					"A UrlEncodedFormEntity was created with an unsupported encoding.",
					e);
			receiver.send(0, null);
		} catch (ClientProtocolException e) {
			Log.e(TAG, "There was a problem when sending the request.", e);
			receiver.send(0, null);
		} catch (IOException e) {
			Log.e(TAG, "There was a problem when sending the request.", e);
			receiver.send(0, null);
		}
	}

	private static void attachUriWithQuery(HttpRequestBase request, Uri uri,
			Bundle params) {
		try {
			if (params == null) {
				// No params were given or they have already been
				// attached to the Uri.
				request.setURI(new URI(uri.toString()));
			} else {
				Uri.Builder uriBuilder = uri.buildUpon();

				// Loop through our params and append them to the Uri.
				for (BasicNameValuePair param : paramsToList(params)) {
					uriBuilder.appendQueryParameter(param.getName(),
							param.getValue());
				}

				uri = uriBuilder.build();
				request.setURI(new URI(uri.toString()));
			}
		} catch (URISyntaxException e) {
			Log.e(TAG, "URI syntax was incorrect: " + uri.toString(), e);
		}
	}

	private static String verbToString(int verb) {
		switch (verb) {
		case GET:
			return "GET";

		case POST:
			return "POST";

		case PUT:
			return "PUT";

		case DELETE:
			return "DELETE";
		}

		return "";
	}

	private static List<BasicNameValuePair> paramsToList(Bundle params) {
		ArrayList<BasicNameValuePair> formList = new ArrayList<BasicNameValuePair>(
				params.size());

		for (String key : params.keySet()) {
			Object value = params.get(key);

			if (value != null)
				formList.add(new BasicNameValuePair(key, value.toString()));
		}

		return formList;
	}

}
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.jcertif.android.JcertifApplication;
import com.jcertif.android.MainActivity;
import com.jcertif.android.R;
import com.jcertif.android.dao.CategorieProvider;
import com.jcertif.android.dao.ContributorProvider;
import com.jcertif.android.dao.SessionProvider;
import com.jcertif.android.dao.SpeakerProvider;
import com.jcertif.android.dao.SponsorLevelProvider;
import com.jcertif.android.dao.SponsorProvider;
import com.jcertif.android.model.Category;
import com.jcertif.android.model.Contributor;
import com.jcertif.android.model.Session;
import com.jcertif.android.model.Speaker;
import com.jcertif.android.model.Sponsor;
import com.jcertif.android.model.SponsorLevel;
import com.jcertif.android.service.RESTService;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
/*
 * Copyright 2013 JCertifLab.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jcertif.android.fragments;




/**
 * 
 * @author Patrick Bashizi (bashizip@gmail.com)
 * @author Komi Serge Innocent <komi.innocent@gmail.com>
 * 
 */
public class InitialisationFragment extends RESTResponderFragment {

	private ProgressBar pb_init;
	private TextView tv_init;

	private final String SPONSOR_LEVEL_URI = JcertifApplication.BASE_URL
			+ "/ref/sponsorlevel/list";

	private final String CATEGORIES__URI = JcertifApplication.BASE_URL
			+ "/ref/category/list";
	private static final String SPEAKER_LIST_URI = JcertifApplication.BASE_URL
			+ "/speaker/list";
    private final String [] URI_LIST={SPEAKER_LIST_URI,CATEGORIES__URI,SPONSOR_LEVEL_URI,
            ContributorFragment.GITHUB_CONTRIBUTOR_API_URL,SessionListFragment.SESSIONS_LIST_URI};
    private final int HTTP_OK_STATUS=200;



	private RefentielDataLodedListener listener;
	CategorieProvider catProvider;
	SponsorLevelProvider spProvider;
	SpeakerProvider spekerProvider;
    SponsorProvider sponsorProvider;