Java tutorial
/* * Copyright (C) 2010 David Schfer, Mario Fleischmann * * This file is part of DeHaBeWe. * * DeHaBeWe is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DeHaBeWe is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DeHaBeWe. If not, see <http://www.gnu.org/licenses/>. */ /* * Copyright (c) 2010, Lauren Darcey and Shane Conder * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used * to endorse or promote products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * <ORGANIZATION> = Mamlambo */ /* * ******* WARNING WARNING WARNING ************ * * As stated above, this code is supplied AS-IS. Any damage, loss of data, or other harm * is not our liability. You use this code at your own risk. * * You've been warned. * * Since this code has to be run on a handset, you may break your handset. We have not tested it on *your* handset. * * You've been warned. * * This code is subject to change. In fact, it has changed. Android SDK 2.1 -> 2.2 update changed it. * * Please see the article at http://bit.ly/c2kYWk for more information. * */ package de.unclenet.dehabewe; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.ProtocolVersion; import org.apache.http.RequestLine; import org.apache.http.params.HttpParams; import com.google.api.client.googleapis.GoogleHeaders; import com.google.api.client.googleapis.GoogleTransport; import com.google.api.client.http.HttpHeaders; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpResponseException; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.InputStreamContent; import com.google.api.client.xml.atom.AtomParser; import com.google.gdata.client.calendar.CalendarService; import com.google.gdata.data.PlainTextConstruct; import com.google.gdata.data.calendar.CalendarEntry; import com.google.gdata.data.calendar.CalendarFeed; import com.google.gdata.data.calendar.ColorProperty; import com.google.gdata.data.calendar.HiddenProperty; import com.google.gdata.data.calendar.TimeZoneProperty; import com.google.gdata.data.extensions.Where; import com.google.gdata.util.ServiceException; import com.google.common.collect.*; import android.accounts.Account; import android.accounts.AccountManager; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.widget.ArrayAdapter; import de.unclenet.dehabewe.rapla.CalendarTools; import de.unclenet.dehabewe.rapla.MyCalendar; /** * This Activity accomplishes the sync between Rapla and Android Calendar by * directly accessing the ContentProvider on the phone * * @author Mario Fleischmann, David Schfer * */ public class CalendarActivity extends Activity { public CalendarActivity() { transport = GoogleTransport.create(); GoogleHeaders headers = (GoogleHeaders) transport.defaultHeaders; headers.setApplicationName("DeHaBeWe-Androidapp/1.0"); headers.gdataVersion = "2"; } private static final String DEBUG_TAG = "CalendarActivity"; private String PREF = "MyPrefs"; private String user; private String file; private List<MyCalendar> myList; private static final int DIALOG_ACCOUNTS = 0; private String authToken; private static final String AUTH_TOKEN_TYPE = "cl"; private static final int REQUEST_AUTHENTICATE = 0; private static HttpTransport transport; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.calendar_sync); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); user = prefs.getString("User", ""); file = prefs.getString("File", ""); CalendarTools calTool = new CalendarTools(); File dir = getFilesDir(); myList = calTool.getCalendar(user, file, dir); gotAccount(false); } @Override protected Dialog onCreateDialog(int id) { switch (id) { case DIALOG_ACCOUNTS: AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle("Select a Google account"); final AccountManager manager = AccountManager.get(this); final Account[] accounts = manager.getAccountsByType("com.google"); final int size = accounts.length; String[] names = new String[size]; for (int i = 0; i < size; i++) { names[i] = accounts[i].name; } builder.setItems(names, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { gotAccount(manager, accounts[which]); } }); return builder.create(); } return null; } private void gotAccount(boolean tokenExpired) { SharedPreferences settings = getSharedPreferences(PREF, 0); String accountName = settings.getString("accountName", null); if (accountName != null) { AccountManager manager = AccountManager.get(this); Account[] accounts = manager.getAccountsByType("com.google"); int size = accounts.length; for (int i = 0; i < size; i++) { Account account = accounts[i]; if (accountName.equals(account.name)) { if (tokenExpired) { manager.invalidateAuthToken("com.google", this.authToken); } gotAccount(manager, account); return; } } } showDialog(DIALOG_ACCOUNTS); } private void gotAccount(final AccountManager manager, final Account account) { SharedPreferences settings = getSharedPreferences(PREF, 0); SharedPreferences.Editor editor = settings.edit(); editor.putString("accountName", account.name); editor.commit(); new Thread() { @Override public void run() { try { final Bundle bundle = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null) .getResult(); runOnUiThread(new Runnable() { public void run() { try { if (bundle.containsKey(AccountManager.KEY_INTENT)) { Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT); int flags = intent.getFlags(); flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK; intent.setFlags(flags); startActivityForResult(intent, REQUEST_AUTHENTICATE); } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) { authenticatedClientLogin(bundle.getString(AccountManager.KEY_AUTHTOKEN)); } } catch (Exception e) { handleException(e); } } }); } catch (Exception e) { handleException(e); } } }.start(); } private void handleException(Exception e) { e.printStackTrace(); SharedPreferences settings = getSharedPreferences(PREF, 0); boolean log = settings.getBoolean("logging", false); if (e instanceof HttpResponseException) { HttpResponse response = ((HttpResponseException) e).response; int statusCode = response.statusCode; try { response.ignore(); } catch (IOException e1) { e1.printStackTrace(); } if (statusCode == 401 || statusCode == 403) { gotAccount(true); return; } if (log) { try { Log.e(DEBUG_TAG, response.parseAsString()); } catch (IOException parseException) { parseException.printStackTrace(); } } } if (log) { Log.e(DEBUG_TAG, e.getMessage(), e); } } @SuppressWarnings("deprecation") private void authenticatedClientLogin(String authToken) throws IOException, ServiceException { this.authToken = authToken; Log.i(DEBUG_TAG, "authToken: " + this.authToken); HttpHeaders bla = transport.defaultHeaders; Log.i(DEBUG_TAG, "" + bla); ((GoogleHeaders) transport.defaultHeaders).setGoogleLogin(authToken); authenticated(); } private void authenticated() throws IOException, ServiceException { System.out.println("foo"); CalendarService myService = new CalendarService("dehabewe"); URL feedUrl = new URL("https://www.google.com/calendar/feeds/default/allcalendars/full"); CalendarFeed resultFeed = myService.getFeed(feedUrl, CalendarFeed.class); System.out.println("Your calendars:"); System.out.println(); for (int i = 0; i < resultFeed.getEntries().size(); i++) { CalendarEntry entry = resultFeed.getEntries().get(i); System.out.println("\t" + entry.getTitle().getPlainText()); } } }