code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.utils; import java.io.File; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.DialogInterface.OnCancelListener; import android.net.Uri; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.DocumentDetailsActivity; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.asynctask.AbstractDownloadTask; import de.fmaul.android.cmis.asynctask.ItemPropertiesDisplayTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.FavoriteDAO; import de.fmaul.android.cmis.database.SearchDAO; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; public class ActionUtils { public static void openDocument(final Activity contextActivity, final CmisItemLazy item) { try { File content = getItemFile(contextActivity, contextActivity.getIntent().getStringExtra("workspace"), item); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ viewFileInAssociatedApp(contextActivity, content, item.getMimeType()); } else { confirmDownload(contextActivity, item, true); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void openWithDocument(final Activity contextActivity, final CmisItemLazy item) { try { File content = getItemFile(contextActivity, contextActivity.getIntent().getStringExtra("workspace"), item); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ openWith(contextActivity, content); } else { confirmDownload(contextActivity, item, false); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } private static void openWith(final Activity contextActivity, final File tempFile){ CharSequence[] cs = MimetypeUtils.getOpenWithRowsLabel(contextActivity); AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setTitle(R.string.open_with_title); builder.setSingleChoiceItems(cs, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { viewFileInAssociatedApp(contextActivity, tempFile, MimetypeUtils.getDefaultMimeType().get(which)); dialog.dismiss(); } }); builder.setNegativeButton(contextActivity.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } private static void startDownload(final Activity contextActivity, final CmisItemLazy item, final boolean openAutomatic){ new AbstractDownloadTask(getRepository(contextActivity), contextActivity) { @Override public void onDownloadFinished(File contentFile) { if (contentFile != null && contentFile.exists()) { if (openAutomatic){ viewFileInAssociatedApp(contextActivity, contentFile, item.getMimeType()); } else { openWith(contextActivity, contentFile); } } else { displayMessage(contextActivity, R.string.error_file_does_not_exists); } } }.execute(item); } private static void confirmDownloadBackground(final Activity contextActivity, final CmisItemLazy item) { if (getPrefs(contextActivity).isConfirmDownload() && Integer.parseInt(item.getSize()) > convertSizeToKb(getPrefs(contextActivity).getDownloadFileSize())) { AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setMessage( contextActivity.getText(R.string.confirm_donwload) + " " + convertAndFormatSize(contextActivity, item.getSize()) + " " + contextActivity.getText(R.string.confirm_donwload2) ) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { NotificationUtils.downloadNotification(contextActivity); startDownloadBackground(contextActivity, item); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { startDownloadBackground(contextActivity, item); } } private static void startDownloadBackground(final Activity contextActivity, final CmisItemLazy item){ new AbstractDownloadTask(getRepository(contextActivity), contextActivity, true) { @Override public void onDownloadFinished(File contentFile) { if (contentFile != null && contentFile.exists()) { NotificationUtils.downloadNotification(contextActivity, contentFile, item.getMimeType()); } else { NotificationUtils.cancelDownloadNotification(contextActivity); //displayMessage(contextActivity, R.string.error_file_does_not_exists); } } }.execute(item); } private static void confirmDownload(final Activity contextActivity, final CmisItemLazy item, final boolean notification) { if (getPrefs(contextActivity).isConfirmDownload() && Integer.parseInt(item.getSize()) > convertSizeToKb(getPrefs(contextActivity).getDownloadFileSize())) { AlertDialog.Builder builder = new AlertDialog.Builder(contextActivity); builder.setMessage( contextActivity.getText(R.string.confirm_donwload) + " " + convertAndFormatSize(contextActivity, item.getSize()) + " " + contextActivity.getText(R.string.confirm_donwload2) ) .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { startDownload(contextActivity, item, true); } }) .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } else { startDownload(contextActivity, item, true); } } public static void displayMessage(Activity contextActivity, int messageId) { Toast.makeText(contextActivity, messageId, Toast.LENGTH_LONG).show(); } public static void displayMessage(Activity contextActivity, String messageId) { Toast.makeText(contextActivity, messageId, Toast.LENGTH_LONG).show(); } public static void viewFileInAssociatedApp(final Activity contextActivity, final File tempFile, String mimeType) { Intent viewIntent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(tempFile); //viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setDataAndType(data, mimeType.toLowerCase()); try { contextActivity.startActivity(viewIntent); } catch (ActivityNotFoundException e) { //Toast.makeText(contextActivity, R.string.application_not_available, Toast.LENGTH_SHORT).show(); openWith(contextActivity, tempFile); } } public static void saveAs(final Activity contextActivity, final String workspace, final CmisItemLazy item){ try { File content = item.getContentDownload(contextActivity.getApplication(), ((CmisApp) contextActivity.getApplication()).getPrefs().getDownloadFolder()); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())){ viewFileInAssociatedApp(contextActivity, content, item.getMimeType()); } else { File cacheContent = item.getContent(contextActivity.getApplication(), workspace); if (cacheContent != null && cacheContent.length() > 0 && cacheContent.length() == Long.parseLong(item.getSize())){ //TODO AsyncTask ProgressDialog pg = ProgressDialog.show(contextActivity, "", contextActivity.getText(R.string.loading), true, true); StorageUtils.copy(cacheContent, content); pg.dismiss(); viewFileInAssociatedApp(contextActivity, cacheContent, item.getMimeType()); } else { confirmDownloadBackground(contextActivity, item); } } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void shareDocument(final Activity activity, final String workspace, final CmisItemLazy item) { try { File content = getItemFile(activity, workspace, item); if (item.getMimeType().length() == 0){ shareFileInAssociatedApp(activity, content, item); //} else if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { // shareFileInAssociatedApp(contextActivity, content, item); } else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(activity.getText(R.string.share_question)).setCancelable(true) .setPositiveButton(activity.getText(R.string.share_link), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { shareFileInAssociatedApp(activity, null, item); } }).setNegativeButton(activity.getText(R.string.share_content), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { try { File content = getItemFile(activity, workspace, item); if (content != null) { shareFileInAssociatedApp(activity, content, item); } else { new AbstractDownloadTask(getRepository(activity), activity) { @Override public void onDownloadFinished(File contentFile) { shareFileInAssociatedApp(activity, contentFile, item); } }.execute(item); } } catch (StorageException e) { displayMessage(activity, R.string.generic_error); } } }); AlertDialog alert = builder.create(); alert.show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); } } private static void shareFileInAssociatedApp(Activity contextActivity, File contentFile, CmisItemLazy item) { shareFileInAssociatedApp(contextActivity, contentFile, item, item.getMimeType()); } private static void shareFileInAssociatedApp(Activity contextActivity, File contentFile, CmisItemLazy item, String mimetype) { Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_SUBJECT, item.getTitle()); if (contentFile != null && contentFile.exists()){ i.putExtra(Intent.EXTRA_TEXT, item.getContentUrl()); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(contentFile)); i.setType(mimetype); } else { i.putExtra(Intent.EXTRA_TEXT, item.getSelfUrl()); i.setType("text/plain"); } contextActivity.startActivity(Intent.createChooser(i, contextActivity.getText(R.string.share))); } private static File getItemFile(final Activity contextActivity, final String workspace, final CmisItemLazy item) throws StorageException{ File content = item.getContent(contextActivity.getApplication(), workspace); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { return content; } content = item.getContentDownload(contextActivity.getApplication(), ((CmisApp) contextActivity.getApplication()).getPrefs().getDownloadFolder()); if (content != null && content.length() > 0 && content.length() == Long.parseLong(item.getSize())) { return content; } return null; } public static void createFavorite(Activity activity, Server server, CmisItemLazy item){ Database database = null; try { database = Database.create(activity); FavoriteDAO favDao = new FavoriteDAO(database.open()); long result = 1L; if (favDao.isPresentByURL(item.getSelfUrl()) == false){ String mimetype = ""; if (item.getMimeType() == null || item.getMimeType().length() == 0){ mimetype = item.getBaseType(); } else { mimetype = item.getMimeType(); } result = favDao.insert(item.getTitle(), item.getSelfUrl(), server.getId(), mimetype); if (result == -1){ Toast.makeText(activity, R.string.favorite_create_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.favorite_create, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, R.string.favorite_present, Toast.LENGTH_LONG).show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); for (int i = 0; i < e.getStackTrace().length; i++) { Log.d("CmisRepository", e.getStackTrace()[i].toString()); } } finally { if (database != null){ database.close(); } } } public static void createSaveSearch(Activity activity, Server server, String name, String url){ Database database = null; try { database = Database.create(activity); SearchDAO searchDao = new SearchDAO(database.open()); long result = 1L; if (searchDao.isPresentByURL(url) == false){ Log.d("CmisRepository", name + " - " + url + " - " + server.getId()); result = searchDao.insert(name, url, server.getId()); if (result == -1){ Toast.makeText(activity, R.string.saved_search_create_error, Toast.LENGTH_LONG).show(); } else { Toast.makeText(activity, R.string.saved_search_create, Toast.LENGTH_LONG).show(); } } else { Toast.makeText(activity, R.string.saved_search_present, Toast.LENGTH_LONG).show(); } } catch (Exception e) { displayMessage(activity, R.string.generic_error); for (int i = 0; i < e.getStackTrace().length; i++) { Log.d("CmisRepository", e.getStackTrace()[i].toString()); } } finally { if (database != null){ database.close(); } } } public static void displayDocumentDetails(Activity activity, CmisItem doc) { displayDocumentDetails(activity, getRepository(activity).getServer(), doc); } public static void displayDocumentDetails(Activity activity, Server server, CmisItem doc) { try { ((CmisApp) activity.getApplication()).setCmisPropertyFilter(null); Intent intent =getDocumentDetailsIntent(activity, server, doc); activity.startActivity(intent); } catch (Exception e) { displayMessage(activity, R.string.generic_error); } } public static Intent getDocumentDetailsIntent(Activity activity, Server server, CmisItem doc) { try { Intent intent = new Intent(activity, DocumentDetailsActivity.class); ArrayList<CmisProperty> propList = new ArrayList<CmisProperty>(doc.getProperties().values()); intent.putParcelableArrayListExtra("properties", propList); intent.putExtra("workspace", server.getWorkspace()); intent.putExtra("objectTypeId", doc.getProperties().get("cmis:objectTypeId").getValue()); intent.putExtra("baseTypeId", doc.getProperties().get("cmis:baseTypeId").getValue()); intent.putExtra("item", new CmisItemLazy(doc)); return intent; } catch (Exception e) { return null; } } private static int convertSizeToKb(String size){ return Integer.parseInt(size) * 1024; } public static String convertAndFormatSize(Activity activity, String size) { int sizeInByte = Integer.parseInt(size); return convertAndFormatSize(activity, sizeInByte); } public static String convertAndFormatSize(Activity activity, int sizeInByte) { if (sizeInByte < 1024) { return String.valueOf(sizeInByte) + " " + activity.getText(R.string.file_size_bytes); } else { int sizeInKB = sizeInByte / 1024; if (sizeInKB < 1024) { return String.valueOf(sizeInKB) + " " + activity.getText(R.string.file_size_kilobytes); } else { int sizeInMB = sizeInKB / 1024; if (sizeInMB < 1024) { return String.valueOf(sizeInMB) + " " + activity.getText(R.string.file_size_megabytes); } else { return String.valueOf(sizeInMB / 1024) + " " + activity.getText(R.string.file_size_gigabytes); } } } } public static void openNewListViewActivity(Activity activity, CmisItem item) { openNewListViewActivity(activity, new CmisItemLazy(item)); } public static void openNewListViewActivity(Activity activity, CmisItemLazy item) { Intent intent = new Intent(activity, ListCmisFeedActivity.class); if (item != null){ intent.putExtra("item", item); } else { intent.putExtra("title", getRepository(activity).getServer().getName()); } activity.startActivity(intent); } public static void openDocument(final Activity contextActivity, final File content) { try { if (content != null && content.length() > 0 ){ viewFileInAssociatedApp(contextActivity, content, MimetypeUtils.getMimetype(contextActivity, content)); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void openWithDocument(final Activity contextActivity, final File content) { try { if (content != null && content.length() > 0){ openWith(contextActivity, content); } } catch (Exception e) { displayMessage(contextActivity, e.getMessage()); } } public static void shareFileInAssociatedApp(Activity contextActivity, File contentFile) { Intent i = new Intent(Intent.ACTION_SEND); i.putExtra(Intent.EXTRA_SUBJECT, contentFile.getName()); i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(contentFile)); i.setType(MimetypeUtils.getMimetype(contextActivity, contentFile)); contextActivity.startActivity(Intent.createChooser(i, contextActivity.getText(R.string.share))); } public static void initPrefs(Activity activity) { SharedPreferences sharePrefs = PreferenceManager.getDefaultSharedPreferences(activity); ArrayList<Boolean> quickActionsServer = new ArrayList<Boolean>(6); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_open).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_info).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_edit).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_favorite).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_search).toString(), true)); quickActionsServer.add(sharePrefs.getBoolean(activity.getText(R.string.action_server_pref_delete).toString(), true)); ((CmisApp) activity.getApplication()).setPrefs( new Prefs( Integer.parseInt(sharePrefs.getString("default_view", "1")), sharePrefs.getString(activity.getText(R.string.cmis_dlfolder).toString(), "/sdcard/Download"), sharePrefs.getBoolean(activity.getText(R.string.cmis_scan).toString(), true), sharePrefs.getBoolean(activity.getText(R.string.cmis_download).toString(), true), sharePrefs.getString(activity.getText(R.string.cmis_download_size).toString(), "100"), quickActionsServer ) ); } private static CmisRepository getRepository(Activity activity) { return ((CmisApp) activity.getApplication()).getRepository(); } private static Prefs getPrefs(Activity activity) { return ((CmisApp) activity.getApplication()).getPrefs(); } }
Java
package de.fmaul.android.cmis.utils; import java.io.File; import android.app.Activity; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.widget.RemoteViews; import de.fmaul.android.cmis.DownloadProgressActivity; import de.fmaul.android.cmis.HomeActivity; import de.fmaul.android.cmis.R; public class NotificationUtils { public static final int DOWNLOAD_ID = 3313; public static void downloadNotification(Activity activity, File contentFile, String mimetype){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.notif_download_finish), System.currentTimeMillis()); notification.flags = Notification.FLAG_AUTO_CANCEL; Intent viewIntent = new Intent(Intent.ACTION_VIEW); Uri data = Uri.fromFile(contentFile); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setDataAndType(data, mimetype.toLowerCase()); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.notif_download_title).toString(); String texteNotification = activity.getText(R.string.notif_download_texte) + contentFile.getName(); notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } public static void downloadNotification(Activity activity){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.download_progress), System.currentTimeMillis()); Intent viewIntent = new Intent(activity, DownloadProgressActivity.class); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.download_progress).toString(); String texteNotification = activity.getText(R.string.notif_open).toString(); notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } public static void cancelDownloadNotification(Activity contextActivity){ NotificationManager notificationManager = (NotificationManager) contextActivity.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(DOWNLOAD_ID); } public static void updateDownloadNotification(Activity activity, String message){ NotificationManager notificationManager = (NotificationManager) activity.getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new Notification(R.drawable.cmisexplorer, activity.getText(R.string.download_progress), System.currentTimeMillis()); Intent viewIntent = new Intent(activity, DownloadProgressActivity.class); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); PendingIntent pendingIntent = PendingIntent.getActivity(activity, 0, viewIntent, 0); String titreNotification = activity.getText(R.string.download_progress).toString(); String texteNotification = message; notification.setLatestEventInfo(activity, titreNotification, texteNotification, pendingIntent); notificationManager.notify(DOWNLOAD_ID, notification); } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.utils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import de.fmaul.android.cmis.repo.CmisProperty; public class ListUtils { public static List<Map<String, ?>> buildListOfNameValueMaps(List<CmisProperty> propList) { List<Map<String, ?>> list = new ArrayList<Map<String, ?>>(); for (CmisProperty cmisProperty : propList) { list.add(createPair(cmisProperty.getDisplayName(), cmisProperty.getValue())); } return list; } public static Map<String, ?> createPair(String name, String value) { HashMap<String, String> hashMap = new HashMap<String, String>(); hashMap.put("name", name); hashMap.put("value", value); return hashMap; } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import java.util.List; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.FeedDisplayTask; import de.fmaul.android.cmis.asynctask.FeedItemDisplayTask; import de.fmaul.android.cmis.asynctask.ServerInitTask; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; import de.fmaul.android.cmis.utils.IntentIntegrator; import de.fmaul.android.cmis.utils.IntentResult; import de.fmaul.android.cmis.utils.StorageUtils; import de.fmaul.android.cmis.utils.UIUtils; public class ListCmisFeedActivity extends ListActivity { private static final String TAG = "ListCmisFeedActivity"; private List<String> workspaces; private CharSequence[] cs; private Context context = this; private ListActivity activity = this; private OnSharedPreferenceChangeListener listener; private CmisItemLazy item; private CmisItemLazy itemParent; private CmisItemCollection items; private GridView gridview; private ListView listView; private Prefs prefs; private ArrayList<CmisItemLazy> currentStack = new ArrayList<CmisItemLazy>(); private ListCmisFeedActivitySave save; private boolean firstStart = false; protected static final int REQUEST_CODE_FAVORITE = 1; /** * Contains the current connection information and methods to access the * CMIS repository. */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (activityIsCalledWithSearchAction()){ Intent intent = new Intent(this, SearchActivity.class); intent.putExtras(getIntent()); Server s = getRepository().getServer(); intent.putExtra("server", s); intent.putExtra("title", s.getName()); this.finish(); startActivity(intent); } else { initWindow(); initActionIcon(); Bundle extra = this.getIntent().getExtras(); if (extra != null && extra.getBoolean("isFirstStart")) { firstStart = true; } //Restart if (getLastNonConfigurationInstance() != null ){ save = (ListCmisFeedActivitySave) getLastNonConfigurationInstance(); this.item = save.getItem(); this.itemParent = save.getItemParent(); this.items = save.getItems(); this.currentStack = save.getCurrentStack(); firstStart = false; new FeedDisplayTask(this, getRepository(), null, item, items).execute(); } if (initRepository() == false){ processSearchOrDisplayIntent(); } //Filter Management listener = new SharedPreferences.OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { if (prefs.getBoolean(activity.getString(R.string.cmis_repo_params), false)){ getRepository().generateParams(activity); } } }; PreferenceManager.getDefaultSharedPreferences(context).registerOnSharedPreferenceChangeListener(listener); //Set Default Breadcrumbs ((TextView) activity.findViewById(R.id.path)).setText("/"); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK){ this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public Object onRetainNonConfigurationInstance() { if (item == null){ item = getRepository().getRootItem(); itemParent = item; currentStack.add(item); } return new ListCmisFeedActivitySave(item, itemParent, getItems(), currentStack); } @Override protected void onDestroy() { if (activityIsCalledWithSearchAction() == false){ setSaveContext(null); } super.onDestroy(); } private void initActionIcon() { Button home = (Button) findViewById(R.id.home); Button up = (Button) findViewById(R.id.up); Button back = (Button) findViewById(R.id.back); Button next = (Button) findViewById(R.id.next); Button refresh = (Button) findViewById(R.id.refresh); Button filter = (Button) findViewById(R.id.preference); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(activity, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); up.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { goUP(false); } }); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { getRepository().generateParams(activity, false); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } }); next.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (item == null) { item = getRepository().getRootItem(); } getRepository().generateParams(activity, true); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } }); filter.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(activity, CmisFilterActivity.class)); } }); refresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { refresh(); } }); } private boolean initRepository() { boolean init = true; try { if (getRepository() == null) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { // Case if we change repository. if (firstStart) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } public void processSearchOrDisplayIntent() { if (getRepository() != null) { //if (activityIsCalledWithSearchAction()) { // doSearchWithIntent(getIntent()); //} else { // Start this activity from favorite Bundle extras = getIntent().getExtras(); if (extras != null) { if (extras.get("item") != null) { item = (CmisItemLazy) extras.get("item"); } } new FeedDisplayTask(this, getRepository(), item).execute(item.getDownLink()); //} } else { Toast.makeText(this, getText(R.string.error_repo_connexion), 5); } } /** * The type of the query is passed by the SearchManager through a bundle in * the search intent. * * @param intent * @return */ /*private QueryType getQueryTypeFromIntent(Intent intent) { Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { String queryType = appData.getString(QueryType.class.getName()); return QueryType.valueOf(queryType); } return QueryType.FULLTEXT; }*/ /** * Tests if this activity is called with a Search intent. * * @return */ private boolean activityIsCalledWithSearchAction() { final String queryAction = getIntent().getAction(); return Intent.ACTION_SEARCH.equals(queryAction); } /** * Initialize the window and the activity. */ private void initWindow() { setRequestedOrientation(getResources().getConfiguration().orientation); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.feed_list_main); gridview = (GridView) activity.findViewById(R.id.gridview); listView = activity.getListView(); prefs = ((CmisApp) activity.getApplication()).getPrefs(); gridview.setOnItemClickListener(new CmisDocSelectedListener()); gridview.setTextFilterEnabled(true); gridview.setClickable(true); gridview.setOnCreateContextMenuListener(this); listView.setTextFilterEnabled(true); listView.setItemsCanFocus(true); listView.setClickable(true); listView.setOnItemClickListener(new CmisDocSelectedListener()); listView.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); UIUtils.createContextMenu(activity, menu, menuInfo); } @Override public boolean onContextItemSelected(MenuItem menuItem) { return UIUtils.onContextItemSelected(this, menuItem, prefs); } protected void reload(String workspace) { Intent intent = new Intent(this, ListCmisFeedActivity.class); intent.putExtra("EXIT", true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra("isFirstStart", true); Server s = getRepository().getServer(); if (workspace != null){ s.setWorkspace(workspace); } intent.putExtra("server", s); intent.putExtra("title",s.getName()); this.finish(); startActivity(intent); } private void refresh() { if (item == null){ item = getRepository().getRootItem(); } getRepository().generateParams(activity, false); try { if (StorageUtils.deleteFeedFile(getApplication(), getRepository().getServer().getWorkspace(), item.getDownLink())){ new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), item).execute(item.getDownLink()); } else { displayError(R.string.application_not_available); } } catch (Exception e) { e.printStackTrace(); } } protected void restart(String workspace) { reload(workspace); } protected void restart() { reload(null); } private void displayError(int messageId) { Toast.makeText(this, messageId, Toast.LENGTH_SHORT).show(); } /** * Listener that is called whenever a user clicks on a file or folder in the * list. */ private class CmisDocSelectedListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CmisItem doc = (CmisItem) parent.getItemAtPosition(position); if (activityIsCalledWithSearchAction()){ if (doc.hasChildren()) { ActionUtils.openNewListViewActivity(activity, doc); } else { ActionUtils.displayDocumentDetails(activity, getRepository().getServer(), doc); } } else { if (doc.hasChildren()) { if (getRepository().isPaging()) { getRepository().setSkipCount(0); getRepository().generateParams(activity); } if (item == null || currentStack.size() == 0) { item = getRepository().getRootItem(); currentStack.add(item); } currentStack.add(doc); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), doc).execute(doc.getDownLink()); itemParent = item; item = doc; } else { ActionUtils.displayDocumentDetails(ListCmisFeedActivity.this, doc); } } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.add(Menu.NONE, 1, 0, R.string.menu_item_add_favorite); item.setIcon(R.drawable.favorite); createRepoMenu(menu); UIUtils.createSearchMenu(menu); createToolsMenu(menu); item = menu.add(Menu.NONE, 3, 0, R.string.menu_item_about); item.setIcon(R.drawable.cmisexplorer); item = menu.add(Menu.NONE, 11, 0, R.string.menu_item_view); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ item.setIcon(R.drawable.viewlisting); } else { item.setIcon(R.drawable.viewicons); } return true; } private void createRepoMenu(Menu menu) { SubMenu settingsMenu = menu.addSubMenu(R.string.menu_item_settings); settingsMenu.setIcon(R.drawable.repository); settingsMenu.setHeaderIcon(android.R.drawable.ic_menu_info_details); settingsMenu.add(Menu.NONE, 7, 0, R.string.menu_item_settings_reload); settingsMenu.add(Menu.NONE, 8, 0, R.string.menu_item_settings_repo); settingsMenu.add(Menu.NONE, 9, 0, R.string.menu_item_settings_ws); } private void createToolsMenu(Menu menu) { SubMenu toolsMenu = menu.addSubMenu(R.string.menu_item_tools); toolsMenu.setIcon(R.drawable.tools); toolsMenu.setHeaderIcon(android.R.drawable.ic_menu_info_details); if (getCmisPrefs().isEnableScan()){ toolsMenu.add(Menu.NONE, 10, 0, R.string.menu_item_scanner); } toolsMenu.add(Menu.NONE, 12, 0, R.string.menu_item_download_manager); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: Intent intent = new Intent(this, FavoriteActivity.class); intent.putExtra("server", getRepository().getServer()); startActivity(intent); return true; case 3: startActivity(new Intent(this, AboutActivity.class)); return true; case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intents = new Intent(this, SavedSearchActivity.class); intents.putExtra("server", getRepository().getServer()); startActivity(intents); return true; case 7: restart(); return true; case 8: startActivity(new Intent(this, ServerActivity.class)); return true; case 9: chooseWorkspace(); return true; case 10: IntentIntegrator.initiateScan(this); return true; case 11: if(prefs.getDataView() == Prefs.GRIDVIEW){ prefs.setDataView(Prefs.LISTVIEW); } else { prefs.setDataView(Prefs.GRIDVIEW); } refresh(); return true; case 12: startActivity(new Intent(this, DownloadProgressActivity.class)); return true; } return false; } private void chooseWorkspace(){ try { Server server = getRepository().getServer(); workspaces = FeedUtils.getRootFeedsFromRepo(server.getUrl(), server.getUsername(), server.getPassword()); cs = workspaces.toArray(new CharSequence[workspaces.size()]); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.cmis_repo_choose_workspace); builder.setSingleChoiceItems(cs, workspaces.indexOf(server.getWorkspace()) ,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { dialog.dismiss(); restart(cs[item].toString()); } }); AlertDialog alert = builder.create(); alert.show(); } catch (Exception e) { Toast.makeText(ListCmisFeedActivity.this, R.string.error_repo_connexion, Toast.LENGTH_LONG).show(); } } public void onActivityResult(int requestCode, int resultCode, Intent intent) { /* super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case REQUEST_CODE_FAVORITE: if (resultCode == RESULT_OK && intent != null) { } break; }*/ IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (scanResult != null && scanResult.getContents() != null) if (scanResult.getContents().length() > 0 && scanResult.getContents().contains("http://")) { if ( scanResult.getContents().contains(getRepository().getHostname())){ new FeedItemDisplayTask(activity, getRepository().getServer(), scanResult.getContents()).execute(); } else { ActionUtils.displayMessage(this, R.string.scan_error_repo); } }else { ActionUtils.displayMessage(this, R.string.scan_error_url); } } public void goUP(boolean isBack){ if (activityIsCalledWithSearchAction()){ itemParent = null; currentStack.clear(); } if (item != null && item.getPath() != null && item.getPath().equals("/") == false){ if (getRepository().isPaging()) { getRepository().setSkipCount(0); getRepository().generateParams(activity); } if (itemParent != null) { currentStack.remove(item); item = currentStack.get(currentStack.size()-1); new FeedDisplayTask(ListCmisFeedActivity.this, getRepository(), itemParent).execute(itemParent.getDownLink()); if (currentStack.size()-2 > 0){ itemParent = currentStack.get(currentStack.size()-2); } else { itemParent = currentStack.get(0); } } else { new FeedItemDisplayTask(activity, getRepository().getServer(), item.getParentUrl(), FeedItemDisplayTask.DISPLAY_FOLDER).execute(); } } else if (isBack) { Intent intent = new Intent(activity, ServerActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } } /* * (non-Javadoc) * * @see android.app.Activity#onSearchRequested() */ public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); startSearch("", false, appData, false); return true; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } void setRepository(CmisRepository repo) { ((CmisApp) getApplication()).setRepository(repo); } CmisItemCollection getItems() { return ((CmisApp) getApplication()).getItems(); } void setItems(CmisItemCollection items) { ((CmisApp) getApplication()).setItems(items); } Prefs getCmisPrefs() { return ((CmisApp) getApplication()).getPrefs(); } public CmisItemLazy getItem() { return item; } public void setItem(CmisItemLazy item) { this.item = item; } public ListCmisFeedActivitySave getSaveContext(){ return ((CmisApp) getApplication()).getSavedContextItems(); } public void setSaveContext(ListCmisFeedActivitySave save){ ((CmisApp) getApplication()).setSavedContextItems(save); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.ArrayList; public class Prefs { public static final int LISTVIEW = 1; public static final int GRIDVIEW = 2; private int dataView; private String downloadFolder; private boolean enableScan; private boolean confirmDownload; private String downloadFileSize; private ArrayList<Boolean> quickActionServer; public Prefs(int dataView) { super(); this.dataView = dataView; } public Prefs( int dataView, String downloadFolder, boolean enableScan, boolean confirmDownload, String downloadFileSize, ArrayList<Boolean> quickActionServer) { super(); this.dataView = dataView; this.downloadFolder = downloadFolder; this.enableScan = enableScan; this.confirmDownload = confirmDownload; this.downloadFileSize = downloadFileSize; this.quickActionServer = quickActionServer; } public int getDataView() { return dataView; } public void setDataView(int dataView) { this.dataView = dataView; } public void setDownloadFolder(String downloadFolder) { this.downloadFolder = downloadFolder; } public String getDownloadFolder() { return downloadFolder; } public void setEnableScan(boolean enableScan) { this.enableScan = enableScan; } public boolean isEnableScan() { return enableScan; } public void setConfirmDownload(boolean confirmDownload) { this.confirmDownload = confirmDownload; } public boolean isConfirmDownload() { return confirmDownload; } public void setDownloadFileSize(String downloadFileSize) { this.downloadFileSize = downloadFileSize; } public String getDownloadFileSize() { return downloadFileSize; } public void setQuickActionServer(ArrayList<Boolean> quickActionServer) { this.quickActionServer = quickActionServer; } public ArrayList<Boolean> getQuickActionServer() { return quickActionServer; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.app.Activity; import android.os.Bundle; import android.view.Window; import de.fmaul.android.cmis.asynctask.ServerInfoDisplayTask; public class ServerInfoGeneralActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); new ServerInfoDisplayTask(this).execute(); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis.asynctask; import android.app.ListActivity; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.CmisItemCollectionAdapter; import de.fmaul.android.cmis.GridAdapter; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class SearchDisplayTask extends AsyncTask<String, Void, CmisItemCollection> { private static final String TAG = "SearchDisplayTask"; private final ListActivity activity; private final CmisRepository repository; private final String queryString; private View layout; private CmisItemCollection items; private ListView layoutListing; private GridView layoutGrid; private Boolean errorOnExit = false; public SearchDisplayTask(ListActivity activity, CmisRepository repository, String queryString) { this(activity, repository, queryString, null); } public SearchDisplayTask(ListActivity activity, CmisRepository repository, String queryString, CmisItemCollection items) { super(); this.activity = activity; this.repository = repository; this.queryString = queryString; this.items = items; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); //Hide Data during Animation layoutListing = activity.getListView(); layoutListing.setVisibility(View.GONE); activity.findViewById(R.id.empty).setVisibility(View.GONE); //Setting TITLE activity.getWindow().setTitle(repository.getServer().getName() + " > " + activity.getString(R.string.search_progress)); //Setting Breadcrumb ((TextView) activity.findViewById(R.id.path)).setText(">"); //Loading Animation layout = activity.findViewById(R.id.animation); layout.setVisibility(View.VISIBLE); View objet = activity.findViewById(R.id.transfert); Animation animation = AnimationUtils.loadAnimation(activity, R.anim.download); objet.startAnimation(animation); } @Override protected CmisItemCollection doInBackground(String... params) { try { if (items != null){ return items; } else { String feed = params[0]; return repository.getCollectionFromFeed(feed); } } catch (FeedLoadException fle) { Log.d(TAG, fle.getMessage()); errorOnExit = true; return CmisItemCollection.emptyCollection(); } catch (StorageException e) { Log.d(TAG, e.getMessage()); errorOnExit = true; return CmisItemCollection.emptyCollection(); } } @Override protected void onPostExecute(CmisItemCollection itemCollection) { itemCollection.setTitle(queryString); if (errorOnExit){ ActionUtils.displayMessage(activity, R.string.generic_error); } ((CmisApp) activity.getApplication()).setItems(itemCollection); Prefs prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ GridView gridview = (GridView) activity.findViewById(R.id.gridview); gridview.setAdapter(new GridAdapter(activity, R.layout.feed_grid_row, itemCollection)); } else { layoutListing.setAdapter(new CmisItemCollectionAdapter(activity, R.layout.feed_list_row, itemCollection)); } //Setting TITLE activity.getWindow().setTitle(repository.getServer().getName() + " > " + activity.getString(R.string.menu_item_search)); //Setting BreadCrumb ((TextView) activity.findViewById(R.id.path)).setText( itemCollection.getItems().size() + " " + activity.getString(R.string.search_results_for) + " " + queryString); //Show Data & Hide Animation prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ layoutGrid.setVisibility(View.VISIBLE); } else { layoutListing.setVisibility(View.VISIBLE); } layout.setVisibility(View.GONE); activity.setProgressBarIndeterminateVisibility(false); if (itemCollection.getItems().size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } //Allow screen rotation activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis.asynctask; import android.app.ListActivity; import android.content.pm.ActivityInfo; import android.os.AsyncTask; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.GridView; import android.widget.ListView; import android.widget.TextView; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.CmisItemCollectionAdapter; import de.fmaul.android.cmis.GridAdapter; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class FeedDisplayTask extends AsyncTask<String, Void, CmisItemCollection> { private static final String TAG = "FeedDisplayTask"; private final ListActivity activity; private final CmisRepository repository; private final String title; private String feedParams = ""; private View layout; private CmisItemLazy item; private CmisItemCollection items; private ListView layoutListing; private GridView layoutGrid; public FeedDisplayTask(ListActivity activity, CmisRepository repository, String title) { this(activity, repository, title, null, null); } public FeedDisplayTask(ListActivity activity, CmisRepository repository, CmisItemLazy item) { this(activity, repository, item.getTitle(), item, null); } public FeedDisplayTask(ListActivity activity, CmisRepository repository, String title, CmisItemLazy item, CmisItemCollection items) { super(); this.activity = activity; this.repository = repository; this.title = title; this.item = item; this.items = items; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); if (items == null && repository != null && repository.getUseFeedParams()){ feedParams = repository.getFeedParams(); } //Hide Data during Animation layoutGrid = (GridView) activity.findViewById(R.id.gridview); layoutListing = activity.getListView(); layoutListing.setVisibility(View.GONE); layoutGrid.setVisibility(View.GONE); activity.findViewById(R.id.empty).setVisibility(View.GONE); //Loading Animation layout = activity.findViewById(R.id.animation); layout.setVisibility(View.VISIBLE); View objet = activity.findViewById(R.id.transfert); Animation animation = AnimationUtils.loadAnimation(activity, R.anim.download); objet.startAnimation(animation); } @Override protected CmisItemCollection doInBackground(String... params) { try { if (items != null){ return items; } else { String feed = params[0]; if (feed == null || feed.length() == 0) { return repository.getRootCollection(feedParams); } else { return repository.getCollectionFromFeed(feed + feedParams); } } } catch (FeedLoadException fle) { Log.d(TAG, fle.getMessage()); //ActionUtils.displayMessage(activity, R.string.generic_error); return CmisItemCollection.emptyCollection(); } catch (StorageException e) { Log.d(TAG, e.getMessage()); //ActionUtils.displayMessage(activity, R.string.generic_error); return CmisItemCollection.emptyCollection(); } } @Override protected void onPostExecute(CmisItemCollection itemCollection) { if (items == null){ if (title != null){ itemCollection.setTitle(title); } else { itemCollection.setTitle(item.getTitle()); } } ((CmisApp) activity.getApplication()).setItems(itemCollection); Prefs prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ GridView gridview = (GridView) activity.findViewById(R.id.gridview); gridview.setAdapter(new GridAdapter(activity, R.layout.feed_grid_row, itemCollection)); } else { layoutListing.setAdapter(new CmisItemCollectionAdapter(activity, R.layout.feed_list_row, itemCollection)); } //No Case Button back = ((Button) activity.findViewById(R.id.back)); Button next = ((Button) activity.findViewById(R.id.next)); String title_paging = ""; if (repository.isPaging() == false){ Log.d(TAG, "PAGING : NO"); back.setVisibility(View.GONE); next.setVisibility(View.GONE); } else { //First Case if (repository.getSkipCount() == 0 && (repository.getSkipCount() + repository.getMaxItems()) >= repository.getNumItems()){ Log.d(TAG, "PAGING : UNIQUE"); back.setVisibility(View.GONE); next.setVisibility(View.GONE); } else if (repository.getSkipCount() == 0 && (repository.getSkipCount() + repository.getMaxItems()) < repository.getNumItems()){ Log.d(TAG, "PAGING : FIRST"); int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; title_paging = " [1/" + nb_page + "]"; next.setVisibility(View.VISIBLE); back.setVisibility(View.GONE); } else if (repository.getSkipCount() != 0 && (repository.getSkipCount() + repository.getMaxItems()) >= repository.getNumItems()){ int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; title_paging = " [" + nb_page + "/" + nb_page + "]"; Log.d(TAG, "PAGING : END"); next.setVisibility(View.GONE); back.setVisibility(View.VISIBLE); } else { int nb_page = repository.getNumItems() > 0 ? ((int) Math.ceil((double) repository.getNumItems()/ (double) repository.getMaxItems())) : 0; int currentPage = repository.getSkipCount() > 0 ? ((int) Math.floor((double) repository.getSkipCount()/ (double) repository.getMaxItems())) + 1 : 0; title_paging = " [" + currentPage + "/" + nb_page + "]"; Log.d(TAG, "PAGING : MIDDLE"); back.setVisibility(View.VISIBLE); next.setVisibility(View.VISIBLE); } } //Setting TITLE activity.getWindow().setTitle(itemCollection.getTitle() + title_paging); //Setting BreadCrumb if (item != null && item.getPath() != null){ ((TextView) activity.findViewById(R.id.path)).setText(item.getPath()); } else { ((TextView) activity.findViewById(R.id.path)).setText("/"); } //Show Data & Hide Animation prefs = ((CmisApp) activity.getApplication()).getPrefs(); if(prefs != null && prefs.getDataView() == Prefs.GRIDVIEW){ layoutGrid.setVisibility(View.VISIBLE); } else { layoutListing.setVisibility(View.VISIBLE); } layout.setVisibility(View.GONE); activity.setProgressBarIndeterminateVisibility(false); if (itemCollection.getItems().size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } //Allow screen rotation activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }
Java
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.app.Activity; import android.os.AsyncTask; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.ListUtils; public class ServerInfoDisplayTask extends AsyncTask<String, Void, SimpleAdapter> { private final Activity activity; public ServerInfoDisplayTask(Activity activity) { super(); this.activity = activity; } @Override protected void onPreExecute() { activity.setProgressBarIndeterminateVisibility(true); } @Override protected SimpleAdapter doInBackground(String... params) { try { ArrayList<CmisProperty> propList = activity.getIntent().getParcelableArrayListExtra(activity.getIntent().getStringExtra("context")); List<Map<String, ?>> list = ListUtils.buildListOfNameValueMaps(propList); SimpleAdapter props = new SimpleAdapter(activity, list, R.layout.document_details_row, new String[] { "name", "value" }, new int[] { R.id.propertyName, R.id.propertyValue }); return props; } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(SimpleAdapter props) { //Init View activity.setContentView(R.layout.server_info_general); ListView listInfo = (ListView) activity.findViewById(R.id.server_info_general); listInfo.setAdapter(props); if (listInfo.getCount() == 0){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } activity.setProgressBarIndeterminateVisibility(false); } @Override protected void onCancelled() { activity.setProgressBarIndeterminateVisibility(false); } }
Java
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.Map; import org.dom4j.Element; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.ServerInfoActivity; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; public class ServerInfoLoadingTask extends AsyncTask<String, Void, Map<String, ArrayList<CmisProperty>>> { private final Activity activity; private Server server; private ProgressDialog pg; public ServerInfoLoadingTask(Activity activity, Server server) { super(); this.activity = activity; this.server = server; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true); } @Override protected Map<String, ArrayList<CmisProperty>> doInBackground(String... params) { try { Element workspace; Map<String, ArrayList<CmisProperty>> properties = null; try { workspace = FeedUtils.getWorkspace(server.getWorkspace(), server.getUrl(), server.getUsername(), server.getPassword()); properties = FeedUtils.getCmisRepositoryProperties(workspace); } catch (Exception e) { e.printStackTrace(); } return properties; } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(Map<String, ArrayList<CmisProperty>> properties) { //Init View Intent intent = new Intent(activity, ServerInfoActivity.class); intent.putExtra("title", "Info " + server.getName()); intent.putParcelableArrayListExtra(Server.INFO_GENERAL, properties.get(Server.INFO_GENERAL)); intent.putParcelableArrayListExtra(Server.INFO_ACL_CAPABILITIES, properties.get(Server.INFO_ACL_CAPABILITIES)); intent.putParcelableArrayListExtra(Server.INFO_CAPABILITIES, properties.get(Server.INFO_CAPABILITIES)); activity.startActivity(intent); pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } }
Java
package de.fmaul.android.cmis.asynctask; import android.app.Activity; import android.app.Application; import android.app.ListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.SearchActivity; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class ServerSearchInitTask extends AsyncTask<String, Void, CmisRepository> { private final Activity currentActivity; private ProgressDialog pg; private Server server; private Application app; private Intent intent; public ServerSearchInitTask(Activity activity, Application app, final Server server, Intent intent) { super(); this.currentActivity = activity; this.app = app; this.server = server; this.intent = intent; } @Override protected void onPreExecute() { pg = ProgressDialog.show(currentActivity, "", currentActivity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ServerSearchInitTask.this.cancel(true); currentActivity.finish(); dialog.dismiss(); } }); } @Override protected CmisRepository doInBackground(String... params) { try { return CmisRepository.create(app, server); } catch (FeedLoadException fle) { return null; } catch (Exception fle) { return null; } } @Override protected void onPostExecute(CmisRepository repo) { try { repo.generateParams(currentActivity); ((CmisApp) currentActivity.getApplication()).setRepository(repo); repo.clearCache(repo.getServer().getWorkspace()); Intent i = new Intent(currentActivity, SearchActivity.class); i.putExtras(intent); currentActivity.startActivity(i); currentActivity.finish(); pg.dismiss(); } catch (StorageException e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); pg.dismiss(); } catch (Exception e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); currentActivity.finish(); pg.dismiss(); } } @Override protected void onCancelled() { currentActivity.finish(); pg.dismiss(); } private String getFeedFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("feed") != null) { return extras.get("feed").toString(); } } return null; } private String getTitleFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("title") != null) { return extras.get("title").toString(); } } return null; } }
Java
package de.fmaul.android.cmis.asynctask; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.view.View; import android.widget.Button; import de.fmaul.android.cmis.FileChooserActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FileSystemUtils; import de.fmaul.android.cmis.utils.StorageException; public class CopyFilesTask extends AsyncTask<String, Integer, Boolean> { private final Activity activity; private ProgressDialog progressDialog; private Application app; private static final int MAX_BUFFER_SIZE = 1024; public static final String STATUSES[] = {"Downloading", "Paused", "Complete", "Cancelled", "Error"}; public static final int DOWNLOADING = 0; public static final int PAUSED = 1; public static final int COMPLETE = 2; public static final int CANCELLED = 3; public static final int ERROR = 4; private int status; private int downloaded; private float sizeTotal = 0f; private File folder; private List<File> listingFiles; private List<File> moveFiles; public CopyFilesTask(Activity activity, final List<File> listingFiles, final List<File> moveFiles, final File folder) { super(); this.activity = activity; this.folder = folder; this.listingFiles = listingFiles; this.moveFiles = moveFiles; } @Override protected void onPreExecute() { status = DOWNLOADING; downloaded = 0; progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); //progressDialog.setMessage(this.activity.getText(R.string.copy)); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { CopyFilesTask.this.cancel(true); status = CANCELLED; dialog.dismiss(); } }); progressDialog.setCancelable(true); progressDialog.setTitle(this.activity.getText(R.string.copy)); //progressDialog.setMessage(this.activity.getText(R.string.copy)); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); for (File file : listingFiles) { sizeTotal += file.length(); } } @Override protected Boolean doInBackground(String... params) { try { for (File file : listingFiles) { copyFile(file); } for (File fileToMove : moveFiles) { FileSystemUtils.rename(folder, fileToMove); } return true; } catch (Exception fle) { return false; } } @Override protected void onPostExecute(Boolean statut) { try { if (statut){ listingFiles.clear(); moveFiles.clear(); activity.findViewById(R.id.paste).setVisibility(View.GONE); activity.findViewById(R.id.clear).setVisibility(View.GONE); progressDialog.dismiss(); ActionUtils.displayMessage(activity, R.string.action_paste_success); ((FileChooserActivity) activity).initialize(folder.getName(), folder); } else { ActionUtils.displayMessage(activity, R.string.generic_error); progressDialog.dismiss(); } } catch (Exception e) { ActionUtils.displayMessage(activity, R.string.generic_error); activity.finish(); progressDialog.dismiss(); } } @Override protected void onCancelled() { activity.finish(); progressDialog.dismiss(); } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); int percent = Math.round((float) values[0] / sizeTotal * 100); progressDialog.setProgress(percent); } private void copyFile(File src) throws StorageException { OutputStream os = null; InputStream in = null; int size = (int) src.length(); try { in = new FileInputStream(src); os = new FileOutputStream(createUniqueCopyName(src.getName())); byte[] buffer = new byte[MAX_BUFFER_SIZE]; while (status == DOWNLOADING) { if (size - downloaded < MAX_BUFFER_SIZE) { buffer = new byte[size - downloaded]; } int read = in.read(buffer); if (read == -1 || size == downloaded) break; os.write(buffer, 0, read); downloaded += read; stateChanged(); } if (status == DOWNLOADING) { status = COMPLETE; stateChanged(); } } catch (Exception e) { } finally { if (os != null) { try { os.close(); } catch (Exception e) {} } if (in != null) { try { in.close(); } catch (Exception e) {} } } } private File createUniqueCopyName(String fileName) { File file = new File(folder, fileName); if (!file.exists()) { return file; } file = new File(folder, activity.getString(R.string.copied_file_name) + fileName); if (!file.exists()) { return file; } int copyIndex = 2; while (copyIndex < 500) { file = new File(folder, activity.getString(R.string.copied_file_name) + copyIndex + "_" + fileName); if (!file.exists()) { return file; } copyIndex++; } return null; } private void stateChanged() { publishProgress(downloaded); } }
Java
package de.fmaul.android.cmis.asynctask; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.view.View; import android.widget.SimpleAdapter; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.DocumentDetailsActivity; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.CmisTypeDefinition; import de.fmaul.android.cmis.utils.FeedLoadException; public class ItemPropertiesDisplayTask extends AsyncTask<String, Void, List<Map<String, ?>>> { private final DocumentDetailsActivity activity; private ProgressDialog pg; private String[] filterProperties; private CmisPropertyFilter propertiesFilters; private boolean screenRotation = false; public ItemPropertiesDisplayTask(DocumentDetailsActivity activity) { super(); this.activity = activity; } public ItemPropertiesDisplayTask(DocumentDetailsActivity activity, boolean screenRotation) { super(); this.activity = activity; this.screenRotation = true; } public ItemPropertiesDisplayTask(DocumentDetailsActivity activity, String[] filterProperties) { super(); this.activity = activity; this.filterProperties = filterProperties; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ItemPropertiesDisplayTask.this.cancel(true); activity.finish(); dialog.dismiss(); } }); propertiesFilters = ((CmisApp) activity.getApplication()).getCmisPropertyFilter(); } @Override protected List<Map<String, ?>> doInBackground(String... params) { try { if (propertiesFilters != null){ if (screenRotation) { return propertiesFilters.render(); } else { return propertiesFilters.render(filterProperties); } } else { List<CmisProperty> propList = getPropertiesFromIntent(); CmisTypeDefinition typeDefinition = getRepository().getTypeDefinition(getObjectTypeIdFromIntent()); if (propertiesFilters == null){ propertiesFilters = new CmisPropertyFilter(propList, typeDefinition); } return propertiesFilters.render(filterProperties); } } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(List<Map<String, ?>> list) { ((CmisApp) activity.getApplication()).setCmisPropertyFilter(propertiesFilters); SimpleAdapter props = new SimpleAdapter(activity, list, R.layout.document_details_row, new String[] { "name", "value" }, new int[] { R.id.propertyName, R.id.propertyValue }); activity.setListAdapter(props); if (list.size() == 0 ){ activity.findViewById(R.id.empty).setVisibility(View.VISIBLE); } else { activity.findViewById(R.id.empty).setVisibility(View.GONE); } pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } private String getObjectTypeIdFromIntent() { return activity.getIntent().getStringExtra("objectTypeId"); } private ArrayList<CmisProperty> getPropertiesFromIntent() { ArrayList<CmisProperty> propList = activity.getIntent().getParcelableArrayListExtra("properties"); return propList; } CmisRepository getRepository() { return ((CmisApp) activity.getApplication()).getRepository(); } }
Java
package de.fmaul.android.cmis.asynctask; import org.dom4j.Document; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; import android.util.Log; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.FeedUtils; public class FeedItemDisplayTask extends AsyncTask<String, Void, CmisItem> { private static final String TAG = "FeedItemDisplayTask"; private final Activity activity; private ProgressDialog pg; private Server server; private String url; private int action; public static final int DISPLAY_DETAILS = 0; public static final int DISPLAY_FOLDER = 1; public FeedItemDisplayTask(Activity activity, final Server server, String url) { this(activity, server, url, -1); } public FeedItemDisplayTask(Activity activity, final Server server, String url, int action) { super(); this.activity = activity; this.url = url; this.server = server; this.action = action; } @Override protected void onPreExecute() { pg = ProgressDialog.show(activity, "", activity.getText(R.string.loading), true); } @Override protected CmisItem doInBackground(String... params) { try { Document doc = FeedUtils.readAtomFeed(url, server.getUsername(), server.getPassword()); return CmisItem.createFromFeed(doc.getRootElement()); } catch (FeedLoadException fle) { return null; } } @Override protected void onPostExecute(CmisItem item) { if (item != null){ if (action == -1){ if (item.getBaseType() == null){ action = DISPLAY_FOLDER; } else { action = DISPLAY_DETAILS; } } switch (action) { case DISPLAY_DETAILS: ActionUtils.displayDocumentDetails(activity, server, item); break; case DISPLAY_FOLDER: ActionUtils.openNewListViewActivity(activity, item); break; default: break; } } else { ActionUtils.displayMessage(activity, R.string.favorite_error_loading); } pg.dismiss(); } @Override protected void onCancelled() { pg.dismiss(); } }
Java
package de.fmaul.android.cmis.asynctask; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.DownloadItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.HttpUtils; import de.fmaul.android.cmis.utils.NotificationUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public abstract class AbstractDownloadTask extends AsyncTask<CmisItemLazy, Integer, File> { private final CmisRepository repository; private final Activity activity; private ProgressDialog progressDialog; private Boolean isDownload; private CmisItemLazy item; private static final int MAX_BUFFER_SIZE = 1024; private static final int NB_NOTIF = 10; public static final int DOWNLOADING = 0; private static final int PAUSED = 1; public static final int COMPLETE = 2; public static final int CANCELLED = 3; private static final int ERROR = 4; public int state; private int downloaded; private int size; private int notifCount = 0; private int percent; public AbstractDownloadTask(CmisRepository repository, Activity activity) { this(repository, activity, false); } public AbstractDownloadTask(CmisRepository repository, Activity activity, Boolean isDownload) { this.repository = repository; this.activity = activity; this.isDownload = isDownload; } @Override protected void onPreExecute() { super.onPreExecute(); if (isDownload == false){ state = DOWNLOADING; downloaded = 0; progressDialog = new ProgressDialog(activity); progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progressDialog.setMessage(this.activity.getText(R.string.download)); progressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { AbstractDownloadTask.this.cancel(true); state = CANCELLED; //NotificationUtils.cancelDownloadNotification(activity); dialog.dismiss(); } }); progressDialog.setCancelable(true); progressDialog.setTitle(this.activity.getText(R.string.download)); progressDialog.setMessage(this.activity.getText(R.string.download_progress)); progressDialog.setProgress(0); progressDialog.setMax(100); progressDialog.show(); } else { ActionUtils.displayMessage(activity, R.string.download_progress); } } @Override protected File doInBackground(CmisItemLazy... params) { item = params[0]; List<DownloadItem> dl = ((CmisApp) activity.getApplication()).getDownloadedFiles(); if (dl == null) { dl = new ArrayList<DownloadItem>(); } dl.add(new DownloadItem(item, this)); if (item != null) { //progressDialog.setMax(Integer.parseInt(item.getSize())); size = Integer.parseInt(item.getSize()); try { if (isDownload){ return retreiveContent(item, ((CmisApp) activity.getApplication()).getPrefs().getDownloadFolder()); } else { return retreiveContent(item); } } catch (Exception e) { ActionUtils.displayMessage(activity, R.string.generic_error); return null; } } return null; } protected void onPostExecute(File result) { if (state == CANCELLED){ result.delete(); result = null; } if (progressDialog != null && progressDialog.isShowing()){ progressDialog.dismiss(); } onDownloadFinished(result); } @Override protected void onCancelled() { state = CANCELLED; if (progressDialog.isShowing()){ progressDialog.dismiss(); } } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); percent = Math.round(((float) values[0] / Float.parseFloat(item.getSize())) * 100); if (isDownload == false){ progressDialog.setProgress(percent); } else { if (notifCount == NB_NOTIF){ String message = activity.getText(R.string.progress) + " : " + percent + " %"; NotificationUtils.updateDownloadNotification(activity, message); notifCount = 0; } else { notifCount++; } } } public abstract void onDownloadFinished(File result); private File retreiveContent(CmisItemLazy item) throws StorageException { File contentFile = StorageUtils.getStorageFile(activity.getApplication(), repository.getServer().getWorkspace(), StorageUtils.TYPE_CONTENT, item.getId(), item.getTitle()); return retreiveContent(item, contentFile); } private File retreiveContent(CmisItemLazy item, String downloadFolder) throws StorageException { File contentFile = item.getContentDownload(activity.getApplication(), downloadFolder); return retreiveContent(item, contentFile); } private File retreiveContent(CmisItemLazy item, File contentFile) throws StorageException { OutputStream os = null; InputStream in = null; try { contentFile.getParentFile().mkdirs(); contentFile.createNewFile(); os = new BufferedOutputStream(new FileOutputStream(contentFile)); in = HttpUtils.getWebRessourceAsStream(item.getContentUrl(), repository.getServer().getUsername(), repository.getServer().getPassword()); byte[] buffer = new byte[MAX_BUFFER_SIZE]; while (state == DOWNLOADING) { if (size - downloaded < MAX_BUFFER_SIZE) { buffer = new byte[size - downloaded]; } int read = in.read(buffer); if (read == -1) break; os.write(buffer, 0, read); downloaded += read; stateChanged(); } if (state == DOWNLOADING) { state = COMPLETE; stateChanged(); } return contentFile; } catch (Exception e) { } finally { // Close file. if (os != null) { try { os.close(); } catch (Exception e) {} } // Close connection to server. if (in != null) { try { in.close(); } catch (Exception e) {} } } return null; } private void stateChanged() { publishProgress(downloaded); } public int getPercent() { return percent; } public void setState(int state) { this.state = state; } public int getState(){ return state; } }
Java
package de.fmaul.android.cmis.asynctask; import android.app.Activity; import android.app.Application; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import de.fmaul.android.cmis.CmisApp; import de.fmaul.android.cmis.ListCmisFeedActivity; import de.fmaul.android.cmis.Prefs; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageException; public class ServerInitTask extends AsyncTask<String, Void, CmisRepository> { private final Activity currentActivity; private final ListCmisFeedActivity ListActivity; private final Activity activity; private ProgressDialog pg; private Server server; private Application app; public ServerInitTask(ListCmisFeedActivity activity, Application app, final Server server) { super(); this.currentActivity = activity; this.ListActivity = activity; this.app = app; this.server = server; this.activity = null; } public ServerInitTask(Activity activity, Application app, final Server server) { super(); this.currentActivity = activity; this.ListActivity = null; this.activity = activity; this.app = app; this.server = server; } @Override protected void onPreExecute() { pg = ProgressDialog.show(currentActivity, "", currentActivity.getText(R.string.loading), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { ServerInitTask.this.cancel(true); currentActivity.finish(); dialog.dismiss(); } }); } @Override protected CmisRepository doInBackground(String... params) { try { return CmisRepository.create(app, server); } catch (FeedLoadException fle) { return null; } catch (Exception fle) { return null; } } @Override protected void onPostExecute(CmisRepository repo) { try { repo.generateParams(currentActivity); ((CmisApp) currentActivity.getApplication()).setRepository(repo); repo.clearCache(repo.getServer().getWorkspace()); if (ListActivity != null){ ListActivity.setItem(repo.getRootItem()); new FeedDisplayTask(ListActivity, repo, getTitleFromIntent()).execute(getFeedFromIntent()); } pg.dismiss(); } catch (StorageException e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); pg.dismiss(); } catch (Exception e) { ActionUtils.displayMessage(currentActivity, R.string.generic_error); currentActivity.finish(); pg.dismiss(); } } @Override protected void onCancelled() { currentActivity.finish(); pg.dismiss(); } private String getFeedFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("feed") != null) { return extras.get("feed").toString(); } } return null; } private String getTitleFromIntent() { Bundle extras = currentActivity.getIntent().getExtras(); if (extras != null) { if (extras.get("title") != null) { return extras.get("title").toString(); } } return null; } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.ListActivity; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisItemLazy; public class ListCmisFeedActivitySave extends ListActivity { public CmisItemLazy getItem() { return item; } public CmisItemLazy getItemParent() { return itemParent; } public CmisItemCollection getItems() { return items; } public ArrayList<CmisItemLazy> getCurrentStack() { return currentStack; } public ListCmisFeedActivitySave(CmisItemLazy item, CmisItemLazy itemParent, CmisItemCollection items, ArrayList<CmisItemLazy> currentStack) { super(); this.item = item; this.itemParent = itemParent; this.items = items; this.currentStack = currentStack; } private CmisItemLazy item; private CmisItemLazy itemParent; private CmisItemCollection items; private ArrayList<CmisItemLazy> currentStack = new ArrayList<CmisItemLazy>(); }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.StorageException; import de.fmaul.android.cmis.utils.StorageUtils; public class CmisPreferences extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.preferences); ( (CheckBoxPreference) (getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)))).setChecked(false); getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)).setEnabled(true); getPreferenceManager().findPreference(this.getText(R.string.cmis_cache)).setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference){ try { StorageUtils.deleteCacheFolder(CmisPreferences.this.getApplication()); } catch (StorageException e) { ActionUtils.displayMessage(CmisPreferences.this, R.string.generic_error); } preference.setEnabled(false); return true; } }); } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); ActionUtils.initPrefs(this); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.utils.ActionItem; import de.fmaul.android.cmis.utils.QuickAction; public class ServerAdapter extends ArrayAdapter<Server> { private final Context context; private ArrayList<Server> items; private Server server; private ServerActivity serverActivity; private static final Integer ACTION_SERVER_OPEN = 0; private static final Integer ACTION_SERVER_INFO = 1; private static final Integer ACTION_SERVER_EDIT = 2; private static final Integer ACTION_SERVER_FAVORITE = 3; private static final Integer ACTION_SERVER_SEARCH = 4; private static final Integer ACTION_SERVER_DELETE = 5; public ServerAdapter(Context context, int textViewResourceId, ArrayList<Server> servers) { super(context, textViewResourceId,servers); this.items = servers; this.context = context; this.serverActivity = (ServerActivity) context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = convertView; if (v == null) { LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.server_row, null); } server = items.get(position); if (server != null) { TextView tv = (TextView) v.findViewById(R.id.rowserver); ImageView iv = (ImageView) v.findViewById(R.id.iconserver); iv.setTag(position); iv.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Integer position = (Integer)v.getTag(); server = items.get(position); showQuickAction(v); } }); if (tv != null) { tv.setText(server.getName()); } if(iv != null){ iv.setImageResource(R.drawable.repository); } } return v; } private void showQuickAction(View v){ final QuickAction qa = new QuickAction(v); v.getParent().getParent(); if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_OPEN)){ final ActionItem actionItem = new ActionItem(); actionItem.setTitle(context.getText(R.string.open).toString()); actionItem.setIcon(context.getResources().getDrawable(R.drawable.open_remote)); actionItem.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ListCmisFeedActivity.class); intent.putExtra("isFirstStart", true); intent.putExtra("server", server); intent.putExtra("title", server.getName()); context.startActivity(intent); qa.dismiss(); } }); qa.addActionItem(actionItem); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_INFO)){ final ActionItem info = new ActionItem(); info.setTitle(context.getText(R.string.server_info).toString()); info.setIcon(context.getResources().getDrawable(R.drawable.info)); info.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.getInfoServer(server); qa.dismiss(); } }); qa.addActionItem(info); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_EDIT)){ final ActionItem edit = new ActionItem(); edit.setTitle(context.getText(R.string.edit).toString()); edit.setIcon(context.getResources().getDrawable(R.drawable.editmetada)); edit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.editServer(server); qa.dismiss(); } }); qa.addActionItem(edit); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_FAVORITE)){ final ActionItem favorite = new ActionItem(); favorite.setTitle(context.getText(R.string.menu_item_favorites).toString()); favorite.setIcon(context.getResources().getDrawable(R.drawable.favorite)); favorite.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, FavoriteActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); context.startActivity(intent); qa.dismiss(); } }); qa.addActionItem(favorite); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_SEARCH)){ final ActionItem search = new ActionItem(); search.setTitle(context.getText(R.string.menu_item_search).toString()); search.setIcon(context.getResources().getDrawable(R.drawable.search)); search.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { serverActivity.startSearch(); qa.dismiss(); } }); qa.addActionItem(search); } if (getCmisPrefs().getQuickActionServer().get(ACTION_SERVER_DELETE)){ final ActionItem delete = new ActionItem(); delete.setTitle(context.getText(R.string.delete).toString()); delete.setIcon(context.getResources().getDrawable(R.drawable.delete)); delete.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(R.string.delete); builder.setMessage(context.getText(R.string.action_delete_desc) + " " + server.getName() + " ? ") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { serverActivity.deleteServer(server.getId()); qa.dismiss(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); qa.dismiss(); } }).create(); builder.show(); } }); qa.addActionItem(delete); } qa.setAnimStyle(QuickAction.ANIM_GROW_FROM_CENTER); qa.show(); } Prefs getCmisPrefs() { return ((CmisApp) serverActivity.getApplication()).getPrefs(); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class SearchPrefs { private final Activity activity; public SearchPrefs(Activity activity) { this.activity = activity; } public boolean getExactSearch() { return getPrefs().getBoolean(activity.getString(R.string.cmis_repo_exact_search), false); } private SharedPreferences getPrefs() { return PreferenceManager.getDefaultSharedPreferences(activity); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import android.app.AlertDialog; import android.app.ListActivity; import android.app.SearchManager; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import de.fmaul.android.cmis.asynctask.SearchDisplayTask; import de.fmaul.android.cmis.asynctask.ServerSearchInitTask; import de.fmaul.android.cmis.model.Search; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; import de.fmaul.android.cmis.utils.StorageUtils; import de.fmaul.android.cmis.utils.UIUtils; public class SearchActivity extends ListActivity { private static final String TAG = "SearchActivity"; private ListActivity activity = this; private ListView listView; private Server server; private String searchFeed; private String queryString; private Prefs prefs; private Search savedSearch = null; private EditText input; /** * Contains the current connection information and methods to access the * CMIS repository. */ /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); initWindow(); initActionIcon(); Bundle bundle = getIntent().getExtras(); if (bundle != null){ savedSearch = (Search) bundle.getSerializable("savedSearch"); } //Restart if (getLastNonConfigurationInstance() != null ){ } if (initRepository() == false){ doSearchWithIntent(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK){ this.finish(); return true; } return super.onKeyDown(keyCode, event); } @Override public Object onRetainNonConfigurationInstance() { return null; } @Override protected void onDestroy() { super.onDestroy(); } private void initActionIcon() { Button home = (Button) findViewById(R.id.home); Button refresh = (Button) findViewById(R.id.refresh); Button save = (Button) findViewById(R.id.save); Button pref = (Button) findViewById(R.id.preference); home.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); Intent intent = new Intent(activity, HomeActivity.class); intent.putExtra("EXIT", false); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); } }); refresh.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { if (StorageUtils.deleteFeedFile(getApplication(), getRepository().getServer().getWorkspace(), searchFeed)){ Log.d(TAG, "SearchFeed : " + searchFeed); if (savedSearch != null){ queryString = savedSearch.getName(); } if (new SearchPrefs(activity).getExactSearch()){ searchFeed = searchFeed.replaceAll("%25", ""); } new SearchDisplayTask(SearchActivity.this, getRepository(), queryString).execute(searchFeed); } } catch (Exception e) { // TODO: handle exception } } }); save.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { DialogInterface.OnClickListener saveSearch = new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { if (server == null){ server = getRepository().getServer(); } Log.d(TAG, "SearchFeed : " + server + " - " + searchFeed.substring( searchFeed.indexOf("=")+1, searchFeed.indexOf("&")) + " - " + input.getText().toString()); ActionUtils.createSaveSearch(SearchActivity.this, server, input.getText().toString(), searchFeed.substring( searchFeed.indexOf("=")+1, searchFeed.indexOf("&"))); } }; createDialog(R.string.search_create_title, R.string.search_create_desc, "", saveSearch).show(); } }); pref.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(activity, SearchPreferencesActivity.class)); } }); } private boolean initRepository() { if (savedSearch != null) { return false; } boolean init = true; try { if (getRepository() == null) { new ServerSearchInitTask(this, getApplication(), (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"), getIntent()).execute(); } else { // Case if we change repository. server = (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"); if (getRepository().getServer() != null && server!= null) { if (getRepository().getServer().getName().equals(server.getName())) { init = false; } else { new ServerSearchInitTask(this, getApplication(), (Server) getIntent().getBundleExtra(SearchManager.APP_DATA).getSerializable("server"), getIntent()).execute(); } } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } /** * Initialize the window and the activity. */ private void initWindow() { setRequestedOrientation(getResources().getConfiguration().orientation); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.search_list_main); prefs = ((CmisApp) activity.getApplication()).getPrefs(); listView = activity.getListView(); listView.setTextFilterEnabled(true); listView.setItemsCanFocus(true); listView.setClickable(true); listView.setOnItemClickListener(new CmisDocSelectedListener()); listView.setOnCreateContextMenuListener(this); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); UIUtils.createContextMenu(activity, menu, menuInfo); } @Override public boolean onContextItemSelected(MenuItem menuItem) { return UIUtils.onContextItemSelected(this, menuItem, prefs); } /** * Process the current intent as search intent, build a query url and * display the feed. * * @param queryIntent */ private void doSearchWithIntent() { if (savedSearch != null){ searchFeed = getRepository().getSearchFeed(this, QueryType.SAVEDSEARCH, savedSearch.getUrl()); Log.d(TAG, "SearchFeed : " + searchFeed); new SearchDisplayTask(this, getRepository(), savedSearch.getName()).execute(searchFeed); } else { queryString = getIntent().getStringExtra(SearchManager.QUERY); QueryType queryType = getQueryTypeFromIntent(getIntent()); searchFeed = getRepository().getSearchFeed(this, queryType, queryString); Log.d(TAG, "SearchFeed : " + searchFeed); new SearchDisplayTask(this, getRepository(), queryString).execute(searchFeed); } } /** * The type of the query is passed by the SearchManager through a bundle in * the search intent. * * @param intent * @return */ private QueryType getQueryTypeFromIntent(Intent intent) { Bundle appData = intent.getBundleExtra(SearchManager.APP_DATA); if (appData != null) { String queryType = appData.getString(QueryType.class.getName()); return QueryType.valueOf(queryType); } return QueryType.FULLTEXT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); UIUtils.createSearchMenu(menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intent = new Intent(this, SavedSearchActivity.class); if (server == null){ server = getRepository().getServer(); } intent.putExtra("server", server); startActivity(intent); this.finish(); return true; default: return false; } } public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); startSearch("", false, appData, false); return true; } /** * Listener that is called whenever a user clicks on a file or folder in the * list. */ private class CmisDocSelectedListener implements OnItemClickListener { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { CmisItem doc = (CmisItem) parent.getItemAtPosition(position); if (doc.hasChildren()) { ActionUtils.openNewListViewActivity(activity, doc); } else { ActionUtils.displayDocumentDetails(activity, getRepository().getServer(), doc); } } } private AlertDialog createDialog(int title, int message, String defaultValue, DialogInterface.OnClickListener positiveClickListener){ final AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle(title); alert.setMessage(message); input = new EditText(this); input.setText(defaultValue); alert.setView(input); alert.setPositiveButton(R.string.validate, positiveClickListener); alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.cancel(); } }); return alert.create(); } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } void setRepository(CmisRepository repo) { ((CmisApp) getApplication()).setRepository(repo); } CmisItemCollection getItems() { return ((CmisApp) getApplication()).getItems(); } void setItems(CmisItemCollection items) { ((CmisApp) getApplication()).setItems(items); } Prefs getCmisPrefs() { return ((CmisApp) getApplication()).getPrefs(); } public ListCmisFeedActivitySave getSaveContext(){ return ((CmisApp) getApplication()).getSavedContextItems(); } public void setSaveContext(ListCmisFeedActivitySave save){ ((CmisApp) getApplication()).setSavedContextItems(save); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import de.fmaul.android.cmis.utils.ActionUtils; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class HomeActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().getBooleanExtra("EXIT", false)) { finish(); } setContentView(R.layout.main); ActionUtils.initPrefs(this); ((Button) findViewById(R.id.about)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, AboutActivity.class)); } }); ((Button) findViewById(R.id.preferences)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { /*int PICK_REQUEST_CODE = 0; Intent intent = new Intent(); intent.setAction(Intent.ACTION_PICK); Uri startDir = Uri.fromFile(new File("/sdcard")); // Files and directories ! intent.setDataAndType(startDir, "vnd.android.cursor.dir/*"); //intent.setData(startDir); startActivityForResult(intent, PICK_REQUEST_CODE);*/ startActivity(new Intent(HomeActivity.this, CmisPreferences.class)); //startActivity(new Intent(HomeActivity.this, FileChooserActivity.class)); } }); ((Button) findViewById(R.id.filesystem)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, FileChooserActivity.class)); } }); ((Button) findViewById(R.id.repository)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(HomeActivity.this, ServerActivity.class)); } }); } protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == 0) { if (resultCode == RESULT_OK) { Toast.makeText(this, "Hello ! ", Toast.LENGTH_LONG); } } } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.ServerInfoLoadingTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.ServerDAO; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.QueryType; import de.fmaul.android.cmis.utils.ActionItem; import de.fmaul.android.cmis.utils.QuickAction; import de.fmaul.android.cmis.utils.UIUtils; public class ServerActivity extends ListActivity { private ServerAdapter cmisSAdapter; private ArrayList<Server> listServer; private Server server; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (activityIsCalledWithSearchAction()){ Intent intent = new Intent(this, SearchActivity.class); intent.putExtras(getIntent()); this.finish(); startActivity(intent); } else { setContentView(R.layout.server); createServerList(); registerForContextMenu(getListView()); } } private boolean activityIsCalledWithSearchAction() { final String queryAction = getIntent().getAction(); return Intent.ACTION_SEARCH.equals(queryAction); } public void createServerList(){ Database db = Database.create(this); ServerDAO serverDao = new ServerDAO(db.open()); listServer = new ArrayList<Server>(serverDao.findAll()); db.close(); cmisSAdapter = new ServerAdapter(this, R.layout.server_row, listServer); setListAdapter(cmisSAdapter); } public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuItem menuItem = menu.add(Menu.NONE, 1, 0, R.string.menu_item_server_add); menuItem.setIcon(R.drawable.add); menuItem = menu.add(Menu.NONE, 2, 0, R.string.menu_item_filter); menuItem.setIcon(R.drawable.filter); menuItem = menu.add(Menu.NONE, 3, 0, R.string.quit); menuItem.setIcon(R.drawable.quit); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ switch(item.getItemId()){ case 1: startActivity(new Intent(this,ServerEditActivity.class)); return true; case 2: startActivity( new Intent(this, CmisFilterActivity.class)); return true; case 3: Intent intent = new Intent(this, HomeActivity.class); intent.putExtra("EXIT", true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } protected void onListItemClick(ListView l, View v, int position, long id) { Server s = listServer.get(position); if (s != null){ Intent intent = new Intent(this, ListCmisFeedActivity.class); intent.putExtra("isFirstStart", true); intent.putExtra("server", s); intent.putExtra("title", s.getName()); startActivity(intent); } else { Toast.makeText(this, R.string.generic_error, Toast.LENGTH_LONG); } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(this.getString(R.string.context_menu_title)); menu.add(0, 1, Menu.NONE, getString(R.string.server_info)); menu.add(0, 2, Menu.NONE, getString(R.string.edit)); menu.add(0, 3, Menu.NONE, getString(R.string.delete)); menu.add(0, 4, Menu.NONE, getString(R.string.menu_item_favorites)); UIUtils.createSearchMenu(menu); } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } if (menuInfo != null){ server = (Server) getListView().getItemAtPosition(menuInfo.position); } switch (menuItem.getItemId()) { case 1: if (server != null) { getInfoServer(server); } return true; case 2: if (server != null) { editServer(server); } return true; case 3: if (server != null) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.delete); builder.setMessage(ServerActivity.this.getText(R.string.action_delete_desc) + " " + server.getName() + " ? ") .setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { deleteServer(server.getId()); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }).create(); builder.show(); } return true; case 4: if (server != null) { Intent intent = new Intent(this, FavoriteActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); } return true; case 20: onSearchRequested(QueryType.TITLE); return true; case 21: onSearchRequested(QueryType.FOLDER); return true; case 22: onSearchRequested(QueryType.FULLTEXT); return true; case 23: onSearchRequested(QueryType.CMISQUERY); return true; case 24: Intent intent = new Intent(this, SavedSearchActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); return true; default: return super.onContextItemSelected(menuItem); } } public boolean onSearchRequested(QueryType queryType) { Bundle appData = new Bundle(); appData.putString(QueryType.class.getName(), queryType.name()); appData.putSerializable("server", server); startSearch("", false, appData, false); return true; } public void deleteServer(long id){ Database db = Database.create(this); ServerDAO serverDao = new ServerDAO(db.open()); if (serverDao.delete(id)) { Toast.makeText(this, this.getString(R.string.server_delete), Toast.LENGTH_LONG).show(); createServerList(); } else { Toast.makeText(this, this.getString(R.string.server_delete_error), Toast.LENGTH_LONG).show(); } db.close(); } public void editServer(Server server){ Intent intent = new Intent(this, ServerEditActivity.class); intent.putExtra("server", server); startActivity(intent); } public void getInfoServer(Server server){ new ServerInfoLoadingTask(this, server).execute(); } private static ArrayList<String> getSearchItems(Activity activity) { ArrayList<String> filters = new ArrayList<String>(5); filters.add(activity.getText(R.string.menu_item_search_title).toString()); filters.add(activity.getText(R.string.menu_item_search_folder_title).toString()); filters.add(activity.getText(R.string.menu_item_search_fulltext).toString()); filters.add(activity.getText(R.string.menu_item_search_cmis).toString()); filters.add(activity.getText(R.string.menu_item_search_saved_search).toString()); return filters; } private ArrayList<QueryType> getQueryType() { ArrayList<QueryType> filters = new ArrayList<QueryType>(5); filters.add(QueryType.TITLE); filters.add(QueryType.FOLDER); filters.add(QueryType.FULLTEXT); filters.add(QueryType.CMISQUERY); filters.add(null); return filters; } private CharSequence[] getSearchItemsLabel() { ArrayList<String> filters = getSearchItems(this); return filters.toArray(new CharSequence[filters.size()]); } void startSearch(){ CharSequence[] cs = getSearchItemsLabel(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setIcon(R.drawable.search); builder.setTitle(R.string.menu_item_search); builder.setSingleChoiceItems(cs, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (getQueryType().get(which) != null){ onSearchRequested(getQueryType().get(which)); } else { Intent intent = new Intent(ServerActivity.this, SavedSearchActivity.class); intent.putExtra("server", server); intent.putExtra("isFirstStart", true); startActivity(intent); } dialog.dismiss(); } }); builder.setNegativeButton(this.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.FeedItemDisplayTask; import de.fmaul.android.cmis.asynctask.ServerInitTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.FavoriteDAO; import de.fmaul.android.cmis.model.Favorite; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; public class FavoriteActivity extends ListActivity { private ArrayList<Favorite> listFavorite; private Server currentServer; private Activity activity; private boolean firstStart = true; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = this; Bundle bundle = getIntent().getExtras(); if (bundle != null){ currentServer = (Server) bundle.getSerializable("server"); firstStart = bundle.getBoolean("isFirstStart"); } setContentView(R.layout.server); setTitle(this.getText(R.string.favorite_title) + " " + currentServer.getName()); createFavoriteList(); registerForContextMenu(getListView()); initRepository(); } public void createFavoriteList(){ Database db = Database.create(this); FavoriteDAO favoriteDao = new FavoriteDAO(db.open()); listFavorite = new ArrayList<Favorite>(favoriteDao.findAll(currentServer.getId())); db.close(); setListAdapter(new FavoriteAdapter(this, R.layout.feed_list_row, listFavorite)); } protected void onListItemClick(ListView l, View v, int position, long id) { final Favorite f = listFavorite.get(position); if (f != null){ if (f.getMimetype() != null && f.getMimetype().length() != 0 && f.getMimetype().equals("cmis:folder") == false){ new FeedItemDisplayTask(activity, currentServer, f.getUrl()).execute(); } else { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage(FavoriteActivity.this.getText(R.string.favorite_open)).setCancelable(true) .setPositiveButton(FavoriteActivity.this.getText(R.string.favorite_open_details), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new FeedItemDisplayTask(activity, currentServer, f.getUrl(), FeedItemDisplayTask.DISPLAY_DETAILS).execute(); } }).setNegativeButton(FavoriteActivity.this.getText(R.string.favorite_open_folder), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { new FeedItemDisplayTask(activity, currentServer, f.getUrl(), FeedItemDisplayTask.DISPLAY_FOLDER).execute(); } }); AlertDialog alert = builder.create(); alert.show(); } } else { ActionUtils.displayMessage(this, R.string.favorite_error); } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(this.getString(R.string.favorite_option)); menu.add(0, 1, Menu.NONE, getString(R.string.delete)); } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } Favorite favorite = (Favorite) getListView().getItemAtPosition(menuInfo.position); switch (menuItem.getItemId()) { case 1: if (favorite != null) { delete(favorite.getId()); } return true; default: return super.onContextItemSelected(menuItem); } } public void delete(long id){ Database db = Database.create(this); FavoriteDAO favoriteDao = new FavoriteDAO(db.open()); if (favoriteDao.delete(id)) { Toast.makeText(this, this.getString(R.string.favorite_delete), Toast.LENGTH_LONG).show(); createFavoriteList(); } else { Toast.makeText(this, this.getString(R.string.favorite_delete_error), Toast.LENGTH_LONG).show(); } db.close(); } private boolean initRepository() { boolean init = true; try { if (getRepository() == null) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { // Case if we change repository. if (firstStart) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.os.Bundle; import android.preference.PreferenceActivity; public class SearchPreferencesActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.search); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import java.util.List; import java.util.Map; import android.app.Application; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.repo.DownloadItem; import de.fmaul.android.cmis.utils.MimetypeUtils; public class CmisApp extends Application { private static final String TAG = "CmisApp"; private CmisRepository repository; private Prefs prefs; private CmisItemCollection items; private ListCmisFeedActivitySave savedContextItems; private CmisPropertyFilter cmisPropertyFilter; private Map<String,Integer> mimetypesMap; private List<DownloadItem> downloadedFiles = new ArrayList<DownloadItem>(5); @Override public void onCreate() { super.onCreate(); mimetypesMap = MimetypeUtils.createIconMap(); } public CmisRepository getRepository() { return repository; } public void setRepository(CmisRepository repository) { this.repository = repository; } public Prefs getPrefs() { return prefs; } public void setPrefs(Prefs prefs) { this.prefs = prefs; } public void setItems(CmisItemCollection items) { this.items = items; } public CmisItemCollection getItems() { return items; } public void setCmisPropertyFilter(CmisPropertyFilter cmisPropertyFilter) { this.cmisPropertyFilter = cmisPropertyFilter; } public CmisPropertyFilter getCmisPropertyFilter() { return cmisPropertyFilter; } public void setMimetypesMap(Map<String,Integer> mimetypesMap) { this.mimetypesMap = mimetypesMap; } public Map<String,Integer> getMimetypesMap() { return mimetypesMap; } public void setSavedContextItems(ListCmisFeedActivitySave savedContextItems) { this.savedContextItems = savedContextItems; } public ListCmisFeedActivitySave getSavedContextItems() { return savedContextItems; } public void setDownloadedFiles(List<DownloadItem> downloadedFiles) { this.downloadedFiles = downloadedFiles; } public List<DownloadItem> getDownloadedFiles() { return downloadedFiles; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.ServerDAO; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedUtils; public class ServerEditActivity extends Activity { private Database database; private Context context = this; private boolean isEdit = false; private Server currentServer; private EditText serverNameEditText; private EditText serverUrlEditText; private EditText userEditText; private EditText passwordEditText; private Button workspaceEditText; private List<String> workspaces; private CharSequence[] cs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.server_edit); initServerData(); database = Database.create(this); Button button = (Button)findViewById(R.id.validation_button); button.setOnClickListener( new Button.OnClickListener(){ public void onClick(View view){ try{ if(serverNameEditText.getText().toString().equals("") || serverUrlEditText.getText().toString().equals("") || workspaceEditText.getText().toString().equals("")){ Toast.makeText(ServerEditActivity.this, R.string.cmis_repo_fields, Toast.LENGTH_LONG).show(); } else if (isEdit == false){ ServerDAO serverDao = new ServerDAO(database.open()); serverDao.insert( serverNameEditText.getText().toString(), serverUrlEditText.getText().toString(), userEditText.getText().toString(), passwordEditText.getText().toString(), workspaceEditText.getText().toString()); database.close(); Intent intent = new Intent(context, ServerActivity.class); finish(); startActivity(intent); } else if (isEdit) { ServerDAO serverDao = new ServerDAO(database.open()); serverDao.update( currentServer.getId(), serverNameEditText.getText().toString(), serverUrlEditText.getText().toString(), userEditText.getText().toString(), passwordEditText.getText().toString(), workspaceEditText.getText().toString() ); database.close(); Intent intent = new Intent(context, ServerActivity.class); finish(); startActivity(intent); } } catch (Exception e) { ActionUtils.displayMessage(ServerEditActivity.this, R.string.generic_error); } } }); workspaceEditText.setOnClickListener(new Button.OnClickListener() { @Override public void onClick(View v) { chooseWorkspace(); } }); } private void chooseWorkspace(){ try { workspaces = FeedUtils.getRootFeedsFromRepo(getEditTextValue(serverUrlEditText), getEditTextValue(userEditText), getEditTextValue(passwordEditText)); cs = workspaces.toArray(new CharSequence[workspaces.size()]); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(R.string.cmis_repo_choose_workspace); builder.setSingleChoiceItems(cs, workspaces.indexOf(workspaceEditText.getText()) ,new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { workspaceEditText.setText(cs[item]); dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } catch (Exception e) { Toast.makeText(ServerEditActivity.this, R.string.error_repo_connexion, Toast.LENGTH_LONG).show(); workspaceEditText.setText(""); } } private String getEditTextValue(EditText editText){ if (editText != null && editText.getText() != null && editText.getText().length() > 0 ){ return editText.getText().toString(); } else { return null; } } private void initServerData() { workspaces = null; Bundle bundle = getIntent().getExtras(); if (bundle != null){ currentServer = (Server) getIntent().getExtras().getSerializable("server"); } serverNameEditText = (EditText) findViewById(R.id.cmis_repo_server_name); serverUrlEditText = (EditText) findViewById(R.id.cmis_repo_url_id); userEditText = (EditText) findViewById(R.id.cmis_repo_user_id); passwordEditText = (EditText) findViewById(R.id.cmis_repo_password_id); workspaceEditText = (Button) findViewById(R.id.cmis_repo_workspace_id); if (currentServer != null){ serverNameEditText.setText(currentServer.getName()); serverUrlEditText.setText(currentServer.getUrl()); userEditText.setText(currentServer.getUsername()); passwordEditText.setText(currentServer.getPassword()); workspaceEditText.setText(currentServer.getWorkspace()); isEdit = true; } } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.Date; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.content.Context; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.MimetypeUtils; public class CmisItemCollectionAdapter extends ArrayAdapter<CmisItem> { private final Context context; static private class ViewHolder { TextView topText; TextView bottomText; ImageView icon; } public CmisItemCollectionAdapter(Context context, int textViewResourceId, CmisItemCollection itemCollection) { super(context, textViewResourceId, itemCollection.getItems()); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); CmisItem item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.feed_list_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); vh.bottomText = (TextView) v.findViewById(R.id.bottomtext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, CmisItem item) { if (item != null) { updateControlTitle(v, item); updateControlDescriptionText(v, item); updateControlIcon(v, item); } } private void updateControlIcon(ViewHolder vh, CmisItem item) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(MimetypeUtils.getIcon((Activity)context, item))); } private void updateControlDescriptionText(ViewHolder vh, CmisItem item) { vh.bottomText.setText(buildBottomText(item)); } private void updateControlTitle(ViewHolder vh, CmisItem item) { vh.topText.setText(item.getTitle()); } private CharSequence buildBottomText(CmisItem doc) { List<String> infos = new LinkedList<String>(); appendInfoAuthor(doc, infos); appendInfoModificationDate(doc, infos); appendInfoDocumentSize(doc, infos); return TextUtils.join(" | ", infos); } private void appendInfoDocumentSize(CmisItem doc, List<String> infos) { if (doc.getSize() != null) { infos.add(ActionUtils.convertAndFormatSize((Activity) context, doc.getSize())); } } private void appendInfoAuthor(CmisItem doc, List<String> infos) { if (!TextUtils.isEmpty(doc.getAuthor())) { infos.add(doc.getAuthor()); } } private void appendInfoModificationDate(CmisItem doc, List<String> infos) { Date modificationDate = doc.getModificationDate(); String modDate = ""; String modTime = ""; if (modificationDate != null) { modDate = DateFormat.getDateFormat(context).format(modificationDate); modTime = DateFormat.getTimeFormat(context).format(modificationDate); if (!TextUtils.isEmpty(modDate)) { infos.add(modDate); } if (!TextUtils.isEmpty(modTime)) { infos.add(modTime); } } } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import de.fmaul.android.cmis.asynctask.ItemPropertiesDisplayTask; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.repo.CmisPropertyFilter; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.IntentIntegrator; public class DocumentDetailsActivity extends ListActivity { private CmisItemLazy item; private Button view, download, share, edit, delete, qrcode, filter, openwith; private Activity activity; private CmisPropertyFilter propertyFilter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.document_details_main); propertyFilter = (CmisPropertyFilter) getLastNonConfigurationInstance(); activity = this; item = (CmisItemLazy) getIntent().getExtras().getSerializable("item"); setTitleFromIntent(); displayActionIcons(); displayPropertiesFromIntent(); } @Override public Object onRetainNonConfigurationInstance() { final CmisPropertyFilter data = getCmisPropertyFilter(); return data; } private void displayActionIcons(){ download = (Button) findViewById(R.id.download); view = (Button) findViewById(R.id.view); share = (Button) findViewById(R.id.share); edit = (Button) findViewById(R.id.editmetadata); delete = (Button) findViewById(R.id.delete); qrcode = (Button) findViewById(R.id.qrcode); filter = (Button) findViewById(R.id.filter); openwith = (Button) findViewById(R.id.openwith); //File if (item != null && item.getSize() != null){ view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ActionUtils.openDocument(activity, item); } }); download.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ActionUtils.saveAs(activity, activity.getIntent().getStringExtra("workspace"), item); } }); openwith.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ActionUtils.openWithDocument(activity, item); } }); edit.setVisibility(View.GONE); delete.setVisibility(View.GONE); //qrcode.setVisibility(View.GONE); } else { //FOLDER view.setVisibility(View.GONE); download.setVisibility(View.GONE); edit.setVisibility(View.GONE); //share.setVisibility(View.GONE); //qrcode.setVisibility(View.GONE); delete.setVisibility(View.GONE); openwith.setVisibility(View.GONE); } share.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { ActionUtils.shareDocument(activity, activity.getIntent().getStringExtra("workspace"), item); } }); if (getCmisPrefs().isEnableScan()){ qrcode.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { IntentIntegrator.shareText(activity, item.getSelfUrl()); } }); } else { qrcode.setVisibility(View.GONE); } filter.setOnClickListener(new OnClickListener() { private CharSequence[] cs; @Override public void onClick(View v) { cs = CmisPropertyFilter.getFiltersLabel(DocumentDetailsActivity.this, item); AlertDialog.Builder builder = new AlertDialog.Builder(DocumentDetailsActivity.this); builder.setTitle(R.string.item_filter_title); builder.setSingleChoiceItems(cs, -1, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); new ItemPropertiesDisplayTask(DocumentDetailsActivity.this, CmisPropertyFilter.getFilters(item).get(which)).execute(); } }); builder.setNegativeButton(DocumentDetailsActivity.this.getText(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } }); } private void setTitleFromIntent() { setTitle(getString(R.string.title_details) + " '" + item.getTitle() + "'"); } private void displayPropertiesFromIntent() { if (propertyFilter != null){ new ItemPropertiesDisplayTask(this, true).execute(""); } else { new ItemPropertiesDisplayTask(this).execute(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem settingsItem = menu.add(Menu.NONE, 1, 0, R.string.menu_item_home); settingsItem.setIcon(R.drawable.home); settingsItem = menu.add(Menu.NONE, 2, 0, R.string.menu_item_download_manager); settingsItem.setIcon(R.drawable.download_manager); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: startActivity(new Intent(this, HomeActivity.class)); return true; case 2: startActivity(new Intent(this, DownloadProgressActivity.class)); return true; } return false; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } CmisPropertyFilter getCmisPropertyFilter() { return ((CmisApp) getApplication()).getCmisPropertyFilter(); } Prefs getCmisPrefs() { return ((CmisApp) getApplication()).getPrefs(); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.Activity; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import de.fmaul.android.cmis.asynctask.FeedItemDisplayTask; import de.fmaul.android.cmis.asynctask.ServerInitTask; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.FavoriteDAO; import de.fmaul.android.cmis.database.SearchDAO; import de.fmaul.android.cmis.model.Favorite; import de.fmaul.android.cmis.model.Search; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisRepository; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.FeedLoadException; public class SavedSearchActivity extends ListActivity { private ArrayList<Search> listSearch; private Server currentServer; private Activity activity; private boolean firstStart = true; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); activity = this; Bundle bundle = getIntent().getExtras(); if (bundle != null){ currentServer = (Server) bundle.getSerializable("server"); firstStart = bundle.getBoolean("isFirstStart"); } setContentView(R.layout.server); setTitle(this.getText(R.string.saved_search_title) + " : " + currentServer.getName()); createSearchList(); registerForContextMenu(getListView()); initRepository(); } public void createSearchList(){ try { Database db = Database.create(this); SearchDAO searchDao = new SearchDAO(db.open()); listSearch = new ArrayList<Search>(searchDao.findAll(currentServer.getId())); db.close(); setListAdapter(new SavedSearchAdapter(this, R.layout.feed_list_row, listSearch)); } catch (Exception e) { ActionUtils.displayMessage(this, e.getMessage()); } } protected void onListItemClick(ListView l, View v, int position, long id) { final Search s = listSearch.get(position); if (s != null){ Intent intents = new Intent(this, SearchActivity.class); intents.putExtra("savedSearch", s); startActivity(intents); this.finish(); } else { ActionUtils.displayMessage(this, R.string.favorite_error); } } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderIcon(android.R.drawable.ic_menu_more); menu.setHeaderTitle(this.getString(R.string.saved_search_option)); menu.add(0, 1, Menu.NONE, getString(R.string.delete)); } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } Search search = (Search) getListView().getItemAtPosition(menuInfo.position); switch (menuItem.getItemId()) { case 1: if (search != null) { delete(search.getId()); } return true; default: return super.onContextItemSelected(menuItem); } } public void delete(long id){ Database db = Database.create(this); SearchDAO searchDao = new SearchDAO(db.open()); if (searchDao.delete(id)) { Toast.makeText(this, this.getString(R.string.favorite_delete), Toast.LENGTH_LONG).show(); createSearchList(); } else { Toast.makeText(this, this.getString(R.string.favorite_delete_error), Toast.LENGTH_LONG).show(); } db.close(); } private boolean initRepository() { boolean init = true; try { if (getRepository() == null) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { // Case if we change repository. if (firstStart) { new ServerInitTask(this, getApplication(), (Server) getIntent().getExtras().getSerializable("server")).execute(); } else { init = false; } } } catch (FeedLoadException fle) { ActionUtils.displayMessage(activity, R.string.generic_error); } return init; } CmisRepository getRepository() { return ((CmisApp) getApplication()).getRepository(); } }
Java
package de.fmaul.android.cmis; import java.util.ArrayList; import de.fmaul.android.cmis.database.Database; import de.fmaul.android.cmis.database.ServerDAO; import de.fmaul.android.cmis.model.Server; import android.app.ListActivity; import android.os.Bundle; public class CustomDialogActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.server); createServerList(); } public void createServerList(){ Database db = Database.create(this); ServerDAO serverDao = new ServerDAO(db.open()); ArrayList<Server> listServer = new ArrayList<Server>(serverDao.findAll()); db.close(); ServerAdapter cmisSAdapter = new ServerAdapter(this, R.layout.server_row, listServer); setListAdapter(cmisSAdapter); } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import android.app.Activity; import android.content.Context; import android.text.TextUtils; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.R; import de.fmaul.android.cmis.model.Server; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.repo.CmisProperty; import de.fmaul.android.cmis.repo.DownloadItem; import de.fmaul.android.cmis.utils.ActionUtils; import de.fmaul.android.cmis.utils.MimetypeUtils; public class DownloadAdapter extends ArrayAdapter<DownloadItem> { private final Context context; static private class ViewHolder { TextView topText; TextView bottomText; ImageView icon; } public DownloadAdapter(Context context, int textViewResourceId, List<DownloadItem> itemCollection) { super(context, textViewResourceId, itemCollection); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); DownloadItem item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.feed_list_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); vh.bottomText = (TextView) v.findViewById(R.id.bottomtext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, DownloadItem item) { if (item != null) { updateControlTitle(v, item); updateControlDescriptionText(v, item); updateControlIcon(v, item); } } private void updateControlIcon(ViewHolder vh, DownloadItem item) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(MimetypeUtils.getIcon((Activity)context, item.getItem()))); } private void updateControlDescriptionText(ViewHolder vh, DownloadItem item) { vh.bottomText.setText(buildBottomText(item)); } private void updateControlTitle(ViewHolder vh, DownloadItem item) { vh.topText.setText(item.getItem().getTitle()); } private CharSequence buildBottomText(DownloadItem doc) { List<String> infos = new LinkedList<String>(); appendInfoDocumentSize(doc, infos); appendState(doc, infos); //appendStatus(doc, infos); return TextUtils.join(" | ", infos); } private void appendInfoDocumentSize(DownloadItem doc, List<String> infos) { if (doc.getItem().getSize() != null) { infos.add(ActionUtils.convertAndFormatSize((Activity) context, doc.getItem().getSize())); } } /*private void appendStatus(DownloadItem doc, List<String> infos) { if (doc.getTask().getStatus() != null) { infos.add("Status : " + doc.getTask().getStatus()); } }*/ private void appendState(DownloadItem doc, List<String> infos) { if (doc.getTask().getStatus() != null) { infos.add(doc.getStatut((Activity) context)); } } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class AboutResourcesActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about_res); ((Button) findViewById(R.id.open_icon)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent viewIntent = new Intent(Intent.ACTION_VIEW); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setData(Uri.parse("http://openiconlibrary.sourceforge.net/")); try { startActivity(viewIntent); } catch (ActivityNotFoundException e) { Toast.makeText(AboutResourcesActivity.this, R.string.application_not_available, Toast.LENGTH_SHORT).show(); } } }); } }
Java
package de.fmaul.android.cmis; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.repo.CmisItemCollection; import de.fmaul.android.cmis.utils.MimetypeUtils; public class GridAdapter extends ArrayAdapter<CmisItem> { private Activity activity; static private class ViewHolder { TextView topText; ImageView icon; } public GridAdapter(Activity activity, int textViewResourceId, CmisItemCollection itemCollection) { super(activity, textViewResourceId, itemCollection.getItems()); this.activity = activity; } // create a new ImageView for each item referenced by the Adapter public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); CmisItem item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.feed_grid_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, CmisItem item) { if (item != null) { v.topText.setText(item.getTitle()); updateControlIcon(v, item); } } private void updateControlIcon(ViewHolder vh, CmisItem item) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(MimetypeUtils.getIcon((Activity)activity, item))); } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.model; import java.io.Serializable; public class Server implements Serializable{ private static final long serialVersionUID = 1L; public static final String INFO_GENERAL = "serverInfoGeneral"; public static final String INFO_CAPABILITIES = "serverInfoCapabilites"; public static final String INFO_ACL_CAPABILITIES = "serverInfoACL"; private long id; private String name; private String url; private String username; private String password; private String workspace; public Server(long id, String name, String url, String username, String password, String workspace) { super(); this.id = id; this.name = name; this.url = url; this.username = username; this.password = password; this.workspace = workspace; } public Server() { } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getId() { return id; } public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setWorkspace(String workspace) { this.workspace = workspace; } public String getWorkspace() { return workspace; } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.model; public class Favorite { public final long id; public final String name; public final String url; public final long serverId; public final String mimetype; public Favorite(long id, String name, String url, long serverId, String mimetype) { super(); this.id = id; this.name = name; this.url = url; this.serverId = serverId; this.mimetype = mimetype; } public long getId() { return id; } public String getName() { return name; } public String getUrl() { return url; } public long getServerId() { return serverId; } public String getMimetype() { return mimetype; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis.model; import java.io.Serializable; public class Search implements Serializable{ private static final long serialVersionUID = 2L; private long id; private String name; private String url; private long serverId; public Search(long id, String name, String url, long serverId) { super(); this.id = id; this.name = name; this.url = url; this.serverId = serverId; } public Search() { } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public long getId() { return id; } public void setId(long id) { this.id = id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setServerId(long serverId) { this.serverId = serverId; } public long getServerId() { return serverId; } }
Java
/* * Copyright (C) 2010 Florian Maul * * 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 de.fmaul.android.cmis; import android.app.Activity; import android.content.SharedPreferences; import android.preference.PreferenceManager; public class FilterPrefs { private final Activity activity; public FilterPrefs(Activity activity) { this.activity = activity; } public String getMaxItems() { return getPrefs().getString(activity.getString(R.string.cmis_repo_maxitems), "0"); } public String getFilter() { return getPrefs().getString(activity.getString(R.string.cmis_repo_filter), ""); } public String getTypes() { return getPrefs().getString(activity.getString(R.string.cmis_repo_types), ""); } public String getOrder() { return getPrefs().getString(activity.getString(R.string.cmis_repo_orderby), ""); } public Boolean getPaging () { return getPrefs().getBoolean(activity.getString(R.string.cmis_repo_paging), true); } public int getSkipCount () { return getPrefs().getInt(activity.getString(R.string.cmis_repo_skipcount), 0); } public Boolean getParams() { return getPrefs().getBoolean(activity.getString(R.string.cmis_repo_params), false); } private SharedPreferences getPrefs() { return PreferenceManager.getDefaultSharedPreferences(activity); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.os.Bundle; import android.preference.PreferenceActivity; public class CmisFilterActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.filter); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.model.Favorite; import de.fmaul.android.cmis.model.Search; import de.fmaul.android.cmis.repo.CmisItem; import de.fmaul.android.cmis.utils.MimetypeUtils; public class SavedSearchAdapter extends ArrayAdapter<Search> { static private class ViewHolder { TextView topText; TextView bottomText; ImageView icon; } private Context context; public SavedSearchAdapter(Context context, int textViewResourceId, ArrayList<Search> favorites) { super(context, textViewResourceId,favorites); this.context = context; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); Search item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.feed_list_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); vh.bottomText = (TextView) v.findViewById(R.id.bottomtext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, Search item) { if (item != null) { v.topText.setText(item.getName()); v.bottomText.setText(item.getUrl()); updateControlIcon(v, item); } } private void updateControlIcon(ViewHolder vh, Search item) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(R.drawable.search)); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class SearchSchema { public static final String TABLENAME = "SavedSearch"; public static final String COLUMN_ID = "id"; public static final int COLUMN_ID_ID = 0; public static final String COLUMN_NAME = "name"; public static final int COLUMN_NAME_ID = 1; public static final String COLUMN_URL = "url"; public static final int COLUMN_URL_ID = 2; public static final String COLUMN_SERVER = "serverid"; public static final int COLUMN_SERVER_ID = 3; private static final String QUERY_TABLE_CREATE = "create table " + TABLENAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_URL + " TEXT NOT NULL," + COLUMN_SERVER + " INTEGER NOT NULL" + ");"; private static final String QUERY_TABLE_DROP = "DROP TABLE IF EXISTS " + TABLENAME; public static void onCreate(SQLiteDatabase db) { db.execSQL(SearchSchema.QUERY_TABLE_CREATE); SearchDAO searchDao = new SearchDAO(db); searchDao.insert("Query Document Test", "SELECT+*+FROM+cmis%3Adocument+WHERE+cmis%3Aname+LIKE+%27%25test%25%27", 1); searchDao.insert("Query Document Test", "SELECT+*+FROM+cmis%3Adocument+WHERE+cmis%3Aname+LIKE+%27%25test%25%27", 2); searchDao.insert("Query Document Test", "SELECT+*+FROM+cmis%3Adocument+WHERE+cmis%3Aname+LIKE+%27%25test%25%27", 3); searchDao.insert("Query Document Test", "SELECT+*+FROM+cmis%3Adocument+WHERE+cmis%3Aname+LIKE+%27%25test%25%27", 4); //searchDao.insert(); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("ServersSchema: ", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(QUERY_TABLE_DROP); onCreate(db); } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import de.fmaul.android.cmis.model.Favorite; public class FavoriteDAO implements DAO<Favorite> { private final SQLiteDatabase db; public FavoriteDAO(SQLiteDatabase db) { this.db = db; } public long insert(String name, String url, long serverId, String mimetype) { ContentValues insertValues = createContentValues(name, url, serverId, mimetype); return db.insert(FavoriteSchema.TABLENAME, null, insertValues); } public boolean delete(long id) { return db.delete(FavoriteSchema.TABLENAME, FavoriteSchema.COLUMN_ID + "=" + id, null) > 0; } public List<Favorite> findAll() { Cursor c = db.query( FavoriteSchema.TABLENAME, new String[] { FavoriteSchema.COLUMN_ID, FavoriteSchema.COLUMN_NAME, FavoriteSchema.COLUMN_URL, FavoriteSchema.COLUMN_SERVERID, FavoriteSchema.COLUMN_MIMETYPE }, null, null, null, null, null); return cursorToFavorites(c); } public List<Favorite> findAll(Long serverId) { Cursor c = db.query( FavoriteSchema.TABLENAME, new String[] { FavoriteSchema.COLUMN_ID, FavoriteSchema.COLUMN_NAME, FavoriteSchema.COLUMN_URL, FavoriteSchema.COLUMN_SERVERID, FavoriteSchema.COLUMN_MIMETYPE }, FavoriteSchema.COLUMN_SERVERID + " = " + serverId, null, null, null, null); return cursorToFavorites(c); } public Favorite findById(long id) { Cursor c = db.query(FavoriteSchema.TABLENAME, null, FavoriteSchema.COLUMN_ID + " like " + id, null, null, null, null); if (c != null) { c.moveToFirst(); } return cursorToFavorite(c); } public boolean isPresentByURL(String url) { Cursor c = db.query(FavoriteSchema.TABLENAME, null, FavoriteSchema.COLUMN_URL + " = '" + url + "'", null, null, null, null); if (c != null) { if (c.getCount() == 1){ return true; } else { return false; } } return false; } private ContentValues createContentValues(String name, String url, long repoId, String mimetype) { ContentValues updateValues = new ContentValues(); updateValues.put(FavoriteSchema.COLUMN_NAME, name); updateValues.put(FavoriteSchema.COLUMN_URL, url); updateValues.put(FavoriteSchema.COLUMN_SERVERID, repoId); updateValues.put(FavoriteSchema.COLUMN_MIMETYPE, mimetype); return updateValues; } private ArrayList<Favorite> cursorToFavorites(Cursor c){ if (c.getCount() == 0){ return new ArrayList<Favorite>(); } ArrayList<Favorite> servers = new ArrayList<Favorite>(c.getCount()); c.moveToFirst(); do { Favorite favs = createFromCursor(c); servers.add(favs); } while (c.moveToNext()); c.close(); return servers; } private Favorite createFromCursor(Cursor c) { Favorite fav = new Favorite( c.getInt(FavoriteSchema.COLUMN_ID_ID), c.getString(FavoriteSchema.COLUMN_NAME_ID), c.getString(FavoriteSchema.COLUMN_URL_ID), c.getInt(FavoriteSchema.COLUMN_SERVERID_ID), c.getString(FavoriteSchema.COLUMN_MIMETYPE_ID) ); return fav; } private Favorite cursorToFavorite(Cursor c){ if (c.getCount() == 0){ return null; } Favorite fav = createFromCursor(c); c.close(); return fav; } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class ServerSchema { public static final String TABLENAME = "Servers"; public static final String COLUMN_ID = "id"; public static final int COLUMN_ID_ID = 0; public static final String COLUMN_NAME = "name"; public static final int COLUMN_NAME_ID = 1; public static final String COLUMN_URL = "url"; public static final int COLUMN_URL_ID = 2; public static final String COLUMN_USER = "username"; public static final int COLUMN_USER_ID = 3; public static final String COLUMN_PASS = "password"; public static final int COLUMN_PASS_ID = 4; public static final String COLUMN_WS = "workspace"; public static final int COLUMN_WS_ID = 5; private static final String QUERY_TABLE_CREATE = "create table " + TABLENAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_URL + " TEXT NOT NULL," + COLUMN_USER + " TEXT NOT NULL," + COLUMN_PASS + " TEXT NOT NULL," + COLUMN_WS + " TEXT NOT NULL" + ");"; private static final String QUERY_TABLE_DROP = "DROP TABLE IF EXISTS " + TABLENAME; public static void onCreate(SQLiteDatabase db) { db.execSQL(ServerSchema.QUERY_TABLE_CREATE); ServerDAO serverDao = new ServerDAO(db); serverDao.insert("CMIS Nuxeo", "http://cmis.demo.nuxeo.org/nuxeo/atom/cmis", "Administrator", "Administrator", "Nuxeo Repository default"); serverDao.insert("CMIS Alfresco", "http://cmis.alfresco.com/service/cmis", "admin", "admin", "Main Repository"); serverDao.insert("CMIS eXo", "http://xcmis.org/xcmis1/rest/cmisatom", "", "", "cmis1"); serverDao.insert("CMIS Day CRX", "http://cmis.day.com/cmis/repository", "", "", "CRX"); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("ServersSchema: ", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(QUERY_TABLE_DROP); onCreate(db); } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import java.util.List; public interface DAO<T> { T findById(long id); List<T> findAll(); boolean delete(long id); /* boolean update(T object); long insert(T object); */ }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class Database { private static final String DATABASE_NAME = "DatabaseCMIS"; private static final int DATABASE_VERSION = 1; private final SQLiteOpenHelper cmisDbHelper; private SQLiteDatabase sqliteDb; protected Database(Context ctx){ this.cmisDbHelper = new CMISDBAdapterHelper(ctx); } public static Database create(Context ctx) { return new Database(ctx); } public SQLiteDatabase open() { if (sqliteDb == null || !sqliteDb.isOpen()) { sqliteDb = cmisDbHelper.getWritableDatabase(); } return sqliteDb; } public void close() { sqliteDb.close(); } private static class CMISDBAdapterHelper extends SQLiteOpenHelper { CMISDBAdapterHelper(Context ctx) { super(ctx, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { ServerSchema.onCreate(db); FavoriteSchema.onCreate(db); SearchSchema.onCreate(db); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { ServerSchema.onUpgrade(db, oldVersion, newVersion); FavoriteSchema.onUpgrade(db, oldVersion, newVersion); SearchSchema.onUpgrade(db, oldVersion, newVersion); } } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import de.fmaul.android.cmis.model.Server; public class ServerDAO implements DAO<Server> { private final SQLiteDatabase db; public ServerDAO(SQLiteDatabase db) { this.db = db; } public long insert(String name, String url, String username, String pass, String workspace) { ContentValues insertValues = createContentValues(name, url, username, pass, workspace); return db.insert(ServerSchema.TABLENAME, null, insertValues); } public boolean update(long id, String name, String url, String username, String pass, String workspace) { ContentValues updateValues = createContentValues(name, url, username, pass, workspace); return db.update(ServerSchema.TABLENAME, updateValues, ServerSchema.COLUMN_ID + "=" + id, null) > 0; } public boolean delete(long id) { return db.delete(ServerSchema.TABLENAME, ServerSchema.COLUMN_ID + "=" + id, null) > 0; } public List<Server> findAll() { Cursor c = db.query( ServerSchema.TABLENAME, new String[] { ServerSchema.COLUMN_ID, ServerSchema.COLUMN_NAME, ServerSchema.COLUMN_URL, ServerSchema.COLUMN_USER, ServerSchema.COLUMN_PASS, ServerSchema.COLUMN_WS }, null, null, null, null, null); return cursorToServers(c); } public Server findById(long id) { Cursor c = db.query(ServerSchema.TABLENAME, null, ServerSchema.COLUMN_ID + " like " + id, null, null, null, null); if (c != null) { c.moveToFirst(); } return cursorToServer(c); } private ContentValues createContentValues(String name, String url, String username, String pass, String workspace) { ContentValues updateValues = new ContentValues(); updateValues.put(ServerSchema.COLUMN_NAME, name); updateValues.put(ServerSchema.COLUMN_URL, url); updateValues.put(ServerSchema.COLUMN_USER, username); updateValues.put(ServerSchema.COLUMN_PASS, pass); updateValues.put(ServerSchema.COLUMN_WS, workspace); return updateValues; } private ArrayList<Server> cursorToServers(Cursor c){ if (c.getCount() == 0){ return new ArrayList<Server>(); } ArrayList<Server> servers = new ArrayList<Server>(c.getCount()); c.moveToFirst(); do { Server server = createServerFromCursor(c); servers.add(server); } while (c.moveToNext()); c.close(); return servers; } private Server createServerFromCursor(Cursor c) { Server server = new Server( c.getInt(ServerSchema.COLUMN_ID_ID), c.getString(ServerSchema.COLUMN_NAME_ID), c.getString(ServerSchema.COLUMN_URL_ID), c.getString(ServerSchema.COLUMN_USER_ID), c.getString(ServerSchema.COLUMN_PASS_ID), c.getString(ServerSchema.COLUMN_WS_ID) ); return server; } private Server cursorToServer(Cursor c){ if (c.getCount() == 0){ return null; } Server server = createServerFromCursor(c); c.close(); return server; } }
Java
/* * Copyright (C) 2010 Florian Maul & Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import android.database.sqlite.SQLiteDatabase; import android.util.Log; public class FavoriteSchema { public static final String TABLENAME = "Favorites"; public static final String COLUMN_ID = "id"; public static final int COLUMN_ID_ID = 0; public static final String COLUMN_NAME = "name"; public static final int COLUMN_NAME_ID = 1; public static final String COLUMN_URL = "url"; public static final int COLUMN_URL_ID = 2; public static final String COLUMN_SERVERID = "serverid"; public static final int COLUMN_SERVERID_ID = 3; public static final String COLUMN_MIMETYPE = "mimetype"; public static final int COLUMN_MIMETYPE_ID = 4; private static final String QUERY_TABLE_CREATE = "create table " + TABLENAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT NOT NULL," + COLUMN_URL + " TEXT NOT NULL," + COLUMN_SERVERID + " INTEGER NOT NULL," + COLUMN_MIMETYPE + " TEXT NOT NULL" + ");"; private static final String QUERY_TABLE_DROP = "DROP TABLE IF EXISTS " + TABLENAME; public static void onCreate(SQLiteDatabase db) { db.execSQL(FavoriteSchema.QUERY_TABLE_CREATE); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w("FavoriteSchema: ", "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(QUERY_TABLE_DROP); onCreate(db); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis.database; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import de.fmaul.android.cmis.model.Search; public class SearchDAO implements DAO<Search> { private final SQLiteDatabase db; public SearchDAO(SQLiteDatabase db) { this.db = db; } public long insert(String name, String url, long serverId) { ContentValues insertValues = createContentValues(name, url, serverId); return db.insert(SearchSchema.TABLENAME, null, insertValues); } public boolean update(long id, String name, String url, long serverId) { ContentValues updateValues = createContentValues(name, url, serverId); return db.update(SearchSchema.TABLENAME, updateValues, SearchSchema.COLUMN_ID + "=" + id, null) > 0; } public boolean delete(long id) { return db.delete(SearchSchema.TABLENAME, SearchSchema.COLUMN_ID + "=" + id, null) > 0; } public List<Search> findAll() { Cursor c = db.query( SearchSchema.TABLENAME, new String[] { SearchSchema.COLUMN_ID, SearchSchema.COLUMN_NAME, SearchSchema.COLUMN_URL, SearchSchema.COLUMN_SERVER }, null, null, null, null, null); return cursorToSearches(c); } public List<Search> findAll(long id) { Cursor c = db.query( SearchSchema.TABLENAME, new String[] { SearchSchema.COLUMN_ID, SearchSchema.COLUMN_NAME, SearchSchema.COLUMN_URL, SearchSchema.COLUMN_SERVER }, SearchSchema.COLUMN_SERVER + "=" + id, null, null, null, null); return cursorToSearches(c); } public Search findById(long id) { Cursor c = db.query(SearchSchema.TABLENAME, null, SearchSchema.COLUMN_ID + " like " + id, null, null, null, null); if (c != null) { c.moveToFirst(); } return cursorToSearch(c); } public boolean isPresentByURL(String url) { Cursor c = db.query(SearchSchema.TABLENAME, null, SearchSchema.COLUMN_URL + " = '" + url + "'", null, null, null, null); if (c != null) { if (c.getCount() == 1){ return true; } else { return false; } } return false; } private ContentValues createContentValues(String name, String url, long serverId) { ContentValues updateValues = new ContentValues(); updateValues.put(SearchSchema.COLUMN_NAME, name); updateValues.put(SearchSchema.COLUMN_URL, url); updateValues.put(SearchSchema.COLUMN_SERVER, serverId); return updateValues; } private ArrayList<Search> cursorToSearches(Cursor c){ if (c.getCount() == 0){ return new ArrayList<Search>(); } ArrayList<Search> searches = new ArrayList<Search>(c.getCount()); c.moveToFirst(); do { Search search = createSearchFromCursor(c); searches.add(search); } while (c.moveToNext()); c.close(); return searches; } private Search createSearchFromCursor(Cursor c) { Search search = new Search( c.getInt(SearchSchema.COLUMN_ID_ID), c.getString(SearchSchema.COLUMN_NAME_ID), c.getString(SearchSchema.COLUMN_URL_ID), c.getInt(SearchSchema.COLUMN_SERVER_ID) ); return search; } private Search cursorToSearch(Cursor c){ if (c.getCount() == 0){ return null; } Search search = createSearchFromCursor(c); c.close(); return search; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.io.File; import java.net.FileNameMap; import java.net.URLConnection; import java.util.ArrayList; import java.util.HashMap; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import de.fmaul.android.cmis.model.Favorite; public class FileAdapter extends ArrayAdapter<File> { static private class ViewHolder { TextView topText; ImageView icon; } private File parent; public FileAdapter(Context context, int textViewResourceId, ArrayList<File> files, File parent) { super(context, textViewResourceId, files); this.parent = parent; } @Override public View getView(int position, View convertView, ViewGroup parent) { View v = recycleOrCreateView(convertView); ViewHolder vh = (ViewHolder) v.getTag(); File item = getItem(position); updateControls(vh, item); return v; } private View recycleOrCreateView(View v) { if (v == null) { LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); v = vi.inflate(R.layout.file_list_row, null); ViewHolder vh = new ViewHolder(); vh.icon = (ImageView) v.findViewById(R.id.icon); vh.topText = (TextView) v.findViewById(R.id.toptext); v.setTag(vh); } return v; } private void updateControls(ViewHolder v, File item) { if (item != null) { v.topText.setText(item.getName()); updateControlIcon(v, item); } } public static String getExtension(String uri) { if (uri == null) { return null; } int dot = uri.lastIndexOf("."); if (dot >= 0) { return uri.substring(dot+1); } else { return ""; } } private void updateControlIcon(ViewHolder vh, File item) { if (item.isDirectory()){ if (item.equals(parent)){ vh.icon.setImageDrawable(getContext().getResources().getDrawable(R.drawable.up)); } else { vh.icon.setImageDrawable(getContext().getResources().getDrawable(R.drawable.mt_folderopen)); } } else { String mimetype = getExtension(item.getName()); if (mimetype == null || mimetype.length() == 0) { vh.icon.setImageDrawable(getContext().getResources().getDrawable(R.drawable.mt_text)); } else if (fileExtensions.get(mimetype) != null){ vh.icon.setImageDrawable(getContext().getResources().getDrawable(fileExtensions.get(mimetype))); } else { vh.icon.setImageDrawable(getContext().getResources().getDrawable(R.drawable.mt_text)); } } } private static HashMap<String, Integer> fileExtensions = new HashMap<String, Integer>(); static { fileExtensions.put("jpg", R.drawable.mt_image); fileExtensions.put("jpeg", R.drawable.mt_image); fileExtensions.put("gif", R.drawable.mt_image); fileExtensions.put("png", R.drawable.mt_image); fileExtensions.put("pdf", R.drawable.mt_pdf); fileExtensions.put("doc", R.drawable.mt_msword); fileExtensions.put("docx", R.drawable.mt_msword); fileExtensions.put("xls", R.drawable.mt_msexcel); fileExtensions.put("xlsx", R.drawable.mt_msexcel); fileExtensions.put("ppt", R.drawable.mt_mspowerpoint); fileExtensions.put("pptx", R.drawable.mt_mspowerpoint); fileExtensions.put("html", R.drawable.mt_html); fileExtensions.put("htm", R.drawable.mt_html); fileExtensions.put("mov", R.drawable.mt_video); fileExtensions.put("avi", R.drawable.mt_video); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import de.fmaul.android.cmis.utils.IntentIntegrator; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.Toast; public class AboutDevActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about_dev); ListView lv1 = (ListView) findViewById(R.id.Listdev); String[] devs = getResources().getStringArray(R.array.dev); lv1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, devs)); ((Button) findViewById(R.id.open_icon)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent viewIntent = new Intent(Intent.ACTION_VIEW); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setData(Uri.parse("http://code.google.com/p/android-cmis-browser/")); try { startActivity(viewIntent); } catch (ActivityNotFoundException e) { Toast.makeText(AboutDevActivity.this, R.string.application_not_available, Toast.LENGTH_SHORT).show(); } } }); ((Button) findViewById(R.id.open_market)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent viewIntent = new Intent(Intent.ACTION_VIEW); viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); viewIntent.setData(Uri.parse("http://market.android.com/details?id=de.fmaul.android.cmis")); try { startActivity(viewIntent); } catch (ActivityNotFoundException e) { Toast.makeText(AboutDevActivity.this, R.string.application_not_available, Toast.LENGTH_SHORT).show(); } } }); ((Button) findViewById(R.id.share_app)).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { IntentIntegrator.shareText(AboutDevActivity.this, "http://market.android.com/details?id=de.fmaul.android.cmis"); } catch (ActivityNotFoundException e) { Toast.makeText(AboutDevActivity.this, R.string.application_not_available, Toast.LENGTH_SHORT).show(); } } }); } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import java.util.List; import android.app.ListActivity; import android.os.AsyncTask.Status; import android.os.Bundle; import android.os.Handler; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import de.fmaul.android.cmis.asynctask.AbstractDownloadTask; import de.fmaul.android.cmis.repo.DownloadItem; import de.fmaul.android.cmis.utils.ActionUtils; public class DownloadProgressActivity extends ListActivity { private DownloadAdapter downloadAdapter; private DownloadItem downloadItem; private Handler handler; private Runnable runnable; private List<DownloadItem> downloadedFiles; private int finishTaks; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.server); setTitle(R.string.menu_item_download_manager); createDownloadProgress(); handler = new Handler(); runnable = new Runnable() { public void run() { finishTaks = 0; for (DownloadItem downloadedFile : downloadedFiles) { if (Status.FINISHED.equals(downloadedFile.getTask().getStatus())){ finishTaks++; } } if (finishTaks == downloadedFiles.size()){ handler.removeCallbacks(runnable); } else { handler.postDelayed(this, 1000); } createDownloadProgress(); } }; registerForContextMenu(getListView()); runnable.run(); } public void createDownloadProgress(){ downloadedFiles = ((CmisApp) getApplication()).getDownloadedFiles(); downloadAdapter = new DownloadAdapter(this, R.layout.download_list_row, downloadedFiles); setListAdapter(downloadAdapter); } public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderIcon(android.R.drawable.ic_menu_more); AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo; downloadItem = (DownloadItem) getListView().getItemAtPosition(info.position); menu.setHeaderTitle(downloadItem.getItem().getTitle()); if (isFinish(downloadItem)){ menu.add(0, 2, Menu.NONE, getString(R.string.open)); menu.add(0, 3, Menu.NONE, getString(R.string.delete_list)); } else { if (isCancellable(downloadItem)){ menu.add(0, 1, Menu.NONE, getString(R.string.cancel_download)); } else { menu.add(0, 3, Menu.NONE, getString(R.string.delete_list)); } } } @Override public boolean onContextItemSelected(MenuItem menuItem) { AdapterView.AdapterContextMenuInfo menuInfo; try { menuInfo = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo(); } catch (ClassCastException e) { return false; } downloadItem = (DownloadItem) getListView().getItemAtPosition(menuInfo.position); switch (menuItem.getItemId()) { case 1: downloadItem.getTask().setState(AbstractDownloadTask.CANCELLED); return true; case 2: ActionUtils.openDocument(DownloadProgressActivity.this, downloadItem.getItem()); return true; case 3: downloadedFiles.remove(menuInfo.position); createDownloadProgress(); return true; default: return super.onContextItemSelected(menuItem); } } @Override protected void onListItemClick(ListView l, View v, int position, long id) { downloadItem = (DownloadItem) getListView().getItemAtPosition(position); if (isFinish(downloadItem)){ ActionUtils.openDocument(DownloadProgressActivity.this, downloadItem.getItem()); } } private boolean isFinish(DownloadItem downloadItem){ if (Status.FINISHED.equals(downloadItem.getTask().getStatus()) && downloadItem.getTask().getPercent() == 100){ return true; } else { return false; } } private boolean isCancellable(DownloadItem downloadItem){ if (Status.RUNNING.equals(downloadItem.getTask().getStatus()) && downloadItem.getTask().getPercent() != 100){ return true; } else { return false; } } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TabHost; public class AboutActivity extends TabActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); Resources res = getResources(); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; intent = new Intent().setClass(this, AboutDevActivity.class); spec = tabHost.newTabSpec("dev").setIndicator(this.getText(R.string.about_dev),res.getDrawable(R.drawable.dev)) .setContent(intent); tabHost.addTab(spec); intent = new Intent().setClass(this, AboutResourcesActivity.class); spec = tabHost.newTabSpec("res").setIndicator(this.getText(R.string.about_resources), res.getDrawable(R.drawable.resources)) .setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem settingsItem = menu.add(Menu.NONE, 1, 0, "Home"); settingsItem.setIcon(R.drawable.cmisexplorer); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: startActivity(new Intent(this, HomeActivity.class)); return true; } return false; } }
Java
/* * Copyright (C) 2010 Jean Marie PASCAL * * 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 de.fmaul.android.cmis; import android.app.TabActivity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.TabHost; import de.fmaul.android.cmis.model.Server; public class ServerInfoActivity extends TabActivity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.about); Resources res = getResources(); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; // TAB GENERAL INFO intent = new Intent().setClass(this, ServerInfoGeneralActivity.class); intent.putParcelableArrayListExtra(Server.INFO_GENERAL, getIntent().getParcelableArrayListExtra(Server.INFO_GENERAL)); intent.putExtra("context", Server.INFO_GENERAL); spec = tabHost.newTabSpec(this.getText(R.string.server_info_general).toString()).setIndicator(this.getText(R.string.server_info_general), res.getDrawable(R.drawable.resources)).setContent(intent); tabHost.addTab(spec); // TAB CAPABILITIES intent = new Intent().setClass(this, ServerInfoGeneralActivity.class); intent.putExtra("context", Server.INFO_CAPABILITIES); intent.putParcelableArrayListExtra(Server.INFO_CAPABILITIES, getIntent().getParcelableArrayListExtra(Server.INFO_CAPABILITIES)); spec = tabHost.newTabSpec(this.getText(R.string.server_info_capabilites).toString()).setIndicator(this.getText(R.string.server_info_capabilites), res.getDrawable(R.drawable.capabilities)).setContent(intent); tabHost.addTab(spec); tabHost.setCurrentTab(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem settingsItem = menu.add(Menu.NONE, 1, 0, R.string.menu_item_home); settingsItem.setIcon(R.drawable.home); return true; } public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1: startActivity(new Intent(this, HomeActivity.class)); return true; } return false; } }
Java
package de.fmaul.android.cmis; import java.io.File; import java.util.ArrayList; import de.fmaul.android.cmis.repo.CmisItemLazy; import de.fmaul.android.cmis.utils.ActionUtils; import android.app.Activity; import android.app.ListActivity; import android.os.Bundle; public class OpenFileActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { try{ File file = new File(getIntent().getStringExtra("path")); String mimeType = getIntent().getStringExtra("mimeType"); ActionUtils.viewFileInAssociatedApp(this, file, mimeType); } catch (Exception e) { this.finish(); } //this.finish(); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import com.google.beepmystuff.BmsClient.ShareWith; public class FakePreferences implements BmsClient.SessionStorage, Preferences { private String version = ""; private String nickname = ""; private String password = ""; private String sessionToken = ""; private ShareWith shareWith; public FakePreferences() { } @Override public String getLastRunVersion() { return version; } @Override public void setLastRunVersion(String version) { this.version = version; } @Override public String getNickname() { return nickname; } @Override public void setNickname(String nickname) { this.nickname = nickname; } @Override public String getPassword() { return password; } @Override public void setPassword(String password) { this.password = password; } @Override public ShareWith getShareWith() { return shareWith; } @Override public void setShareWith(ShareWith shareWith) { this.shareWith = shareWith; } @Override public String getSessionToken() { return sessionToken; } @Override public void setSessionToken(String sessionToken) { this.sessionToken = sessionToken; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.verify; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import junit.framework.TestCase; import org.apache.http.HttpEntity; import org.apache.http.ProtocolVersion; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicHttpResponse; public class DefaultBmsHttpClientTest extends TestCase { private HttpClient mockHttpClient; private DefaultBmsHttpClient client; @Override protected void setUp() throws Exception { mockHttpClient = createMock(HttpClient.class); client = new DefaultBmsHttpClient(mockHttpClient); } public void testShouldReturnResponseBody() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); String responseBody = "Hello world"; HttpEntity entity = new StringEntity(responseBody, "UTF-8"); response.setEntity(entity); expect(mockHttpClient.execute(dummyRequest)).andReturn(response); replay(mockHttpClient); byte[] expected = responseBody.getBytes("UTF-8"); byte[] actual = client.getResponseBody(dummyRequest); assertTrue(Arrays.equals(expected, actual)); verify(mockHttpClient); } public void testShouldReturnResponseBodyAsString() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); String expected = "Hello world"; HttpEntity entity = new StringEntity(expected, "UTF-8"); response.setEntity(entity); expect(mockHttpClient.execute(dummyRequest)).andReturn(response); replay(mockHttpClient); String actual = client.getResponseBodyAsString(dummyRequest); assertEquals(expected, actual); verify(mockHttpClient); } public void testShouldFailOnClientProtocolError() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); expect(mockHttpClient.execute(dummyRequest)).andThrow( new ClientProtocolException("you did it wrong")); replay(mockHttpClient); try { client.getResponseBody(dummyRequest); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("you did it wrong", e.getMessage()); assertEquals(ClientProtocolException.class, e.getCause().getClass()); } verify(mockHttpClient); } public void testShouldFailWithRetryOnInitialIOException() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); expect(mockHttpClient.execute(dummyRequest)).andThrow( new IOException("couldn't find server")); replay(mockHttpClient); try { client.getResponseBody(dummyRequest); fail("Expected BmsTransportException"); } catch (BmsTransportException e) { assertEquals("couldn't find server", e.getMessage()); assertEquals(IOException.class, e.getCause().getClass()); } verify(mockHttpClient); } public void testShouldFailOn4xxResponse() throws Exception { HttpUriRequest request = new HttpGet(); assertFalse(request.isAborted()); BasicHttpResponse response = createHttpResponse(404); expect(mockHttpClient.execute(request)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(request); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("HTTP request returned HTTP/1.0 404 Otherwise", e.getMessage()); assertNull(e.getCause()); } assertTrue(request.isAborted()); verify(mockHttpClient); } public void testShouldFailWithRetryOn5xxResponse() throws Exception { HttpUriRequest request = new HttpGet(); assertFalse(request.isAborted()); BasicHttpResponse response = createHttpResponse(503); expect(mockHttpClient.execute(request)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(request); fail("Expected BmsTransportException"); } catch (BmsTransportException e) { assertEquals("HTTP request returned HTTP/1.0 503 Otherwise", e.getMessage()); assertNull(e.getCause()); } assertTrue(request.isAborted()); verify(mockHttpClient); } public void testShouldFailOnUnexpectedHttpStatus() throws Exception { HttpUriRequest request = new HttpGet(); assertFalse(request.isAborted()); BasicHttpResponse response = createHttpResponse(123); expect(mockHttpClient.execute(request)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(request); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Unexpected HTTP response HTTP/1.0 123 Otherwise", e.getMessage()); assertNull(e.getCause()); } assertTrue(request.isAborted()); verify(mockHttpClient); } public void testShouldFailIfReceive200WithNoBody() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); expect(mockHttpClient.execute(dummyRequest)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(dummyRequest); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Received 200 OK with no content?!", e.getMessage()); assertNull(e.getCause()); } verify(mockHttpClient); } public void testShouldFailWithRetryOnIOExceptionWhileReading() throws Exception { HttpUriRequest dummyRequest = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(2048); // Create a mock InputStream that will allow some data to be read, then // throws an IOException. MockInputStream in = new MockInputStream(); entity.setContent(in); response.setEntity(entity); expect(mockHttpClient.execute(dummyRequest)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(dummyRequest); fail("Expected BmsTransportException"); } catch (BmsTransportException e) { assertEquals("Unable to read response from server", e.getMessage()); assertEquals(IOException.class, e.getCause().getClass()); } assertEquals(3, in.getReads()); // two successful, one failed assertTrue(in.isClosed()); verify(mockHttpClient); } public void testShouldFailIfResponseDeclaredTooLarge() throws Exception { HttpUriRequest request = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(20 * 1024 * 1024); // 20MB // The dummy InputStream expects no calls. entity.setContent(new DummyInputStream()); response.setEntity(entity); expect(mockHttpClient.execute(request)).andReturn(response); replay(mockHttpClient); try { client.getResponseBody(request); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Response is 20971520 bytes, larger than allowed (10485760 bytes)", e.getMessage()); assertNull(e.getCause()); } assertTrue(request.isAborted()); verify(mockHttpClient); } public void testShouldFailIfResponseFoundToBeTooLarge() throws Exception { HttpUriRequest request = new HttpGet(); BasicHttpResponse response = createHttpResponse(200); BasicHttpEntity entity = new BasicHttpEntity(); entity.setContentLength(-1); // e.g. chunked encoding // Allow two 512-byte reads, then throws. MockInputStream in = new MockInputStream(); entity.setContent(in); response.setEntity(entity); expect(mockHttpClient.execute(request)).andReturn(response); replay(mockHttpClient); client.setMaxResponseSize(1023); try { client.getResponseBody(request); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Read 1024 response bytes, larger than allowed (1023 bytes)", e.getMessage()); assertNull(e.getCause()); } assertTrue(request.isAborted()); assertEquals(2, in.getReads()); // two successful assertTrue(in.isClosed()); verify(mockHttpClient); } private BasicHttpResponse createHttpResponse(int status) { return new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 0), status, (status == 200) ? "OK" : "Otherwise"); } /** * A simple handwritten mock for above, because InputStream isn't an * interface, and I don't want to start using EasyMock classextension * just for this. * * Allows two 512-byte reads, throws an IOException on the third. * Permits exactly one close, but does no explicit validation. */ private static class MockInputStream extends InputStream { private int reads = 0; private boolean closed = false; @Override public int read(byte[] b) throws IOException { switch (++reads) { case 1: case 2: return 512; case 3: throw new IOException(); default: throw new AssertionError("unexpected read"); } } @Override public void close() { if (closed) { throw new AssertionError("unexpected close"); } closed = true; } @Override public int read() { throw new UnsupportedOperationException(); } public int getReads() { return reads; } public boolean isClosed() { return closed; } } /** * A dummy InputStream that expects no calls. */ private static class DummyInputStream extends InputStream { @Override public int read() { throw new UnsupportedOperationException(); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reportMatcher; import static org.easymock.EasyMock.verify; import com.google.beepmystuff.BmsClient.AddEanResult; import com.google.beepmystuff.BmsClient.LoginResult; import com.google.beepmystuff.BmsClient.ShareWith; import com.google.beepmystuff.DefaultBmsLowLevelClient.BmsRawHttpApiClient; import junit.framework.TestCase; import org.apache.http.Header; import org.apache.http.HttpRequest; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.easymock.IArgumentMatcher; import org.w3c.dom.Document; import org.xml.sax.SAXException; import java.util.Collections; public class DefaultBmsLowLevelClientTest extends TestCase { private static final String TEST_KEY = "squeamish_ossifrage"; private BmsHttpClient mockHttpClient; private BmsLowLevelClient client; @Override protected void setUp() throws Exception { mockHttpClient = createMock(BmsHttpClient.class); client = new DefaultBmsLowLevelClient(mockHttpClient, TEST_KEY); } public void testShouldLogin() throws Exception { HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/login" + "?apikey=squeamish_ossifrage&username=me&password=secret%2F"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/login?username=me&amp;" + "apikey=sqeamish_ossifrage&amp;password=secret%2F</request>" + "<key>squeamish_ossifrage</key></info>" + "<login><session>abcd1234</session></login>" + "<error><errorcode>0</errorcode><string>Success</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); LoginResult result = client.login("me", "secret/"); assertEquals("abcd1234", result.getSessionToken()); verify(mockHttpClient); } public void testShouldReportInvalidCredentialsDuringLogin() throws Exception { HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/login" + "?apikey=squeamish_ossifrage&username=me&password=secret%2F"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/login?username=me&amp;" + "apikey=sqeamish_ossifrage&amp;password=secret%2F</request>" + "<key>squeamish_ossifrage</key></info>" + "<login><session>abcd1234</session></login>" + "<error><errorcode>-2</errorcode>" + "<string>Invalid username or password</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { client.login("me", "secret/"); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertEquals(BmsApiException.ErrorCode.INVALID_USERNAME, e.getErrorCode()); assertEquals("Invalid username or password", e.getMessage()); } verify(mockHttpClient); } public void testShouldGetAvatarPath() throws Exception { HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/getavatarpath" + "?apikey=squeamish_ossifrage&session=abcd1234"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/getavatarpath?" + "apikey=squeamish_ossifrage&amp;session=abcd1234</request>" + "<key>squeamish_ossifrage</key></info>" + "<avatar><path>http://www.beepmystuff.com/static/images/avatar.png</path></avatar>" + "<error><errorcode>0</errorcode><string>Success</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); String result = client.getAvatarPath("abcd1234"); assertEquals("http://www.beepmystuff.com/static/images/avatar.png", result); verify(mockHttpClient); } public void testShouldReportSessionTokenExpiry() throws Exception { // Using a getavatarpath request as an example of a call that might fail. HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/getavatarpath" + "?apikey=squeamish_ossifrage&session=expired"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/getavatarpath?" + "apikey=squeamish_ossifrage&amp;session=expired</request>" + "<key>squeamish_ossifrage</key></info>" + "<error><errorcode>-3</errorcode><string>Session has expired</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { client.getAvatarPath("expired"); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertEquals(BmsApiException.ErrorCode.INVALID_SESSION, e.getErrorCode()); assertEquals("Session has expired", e.getMessage()); } verify(mockHttpClient); } public void testShouldAddEanSharedWithEveryone() throws Exception { HttpUriRequest expectedRequest = new HttpPost("http://www.beepmystuff.com/api/addean" + "?apikey=squeamish_ossifrage&session=abcd1234&ean=9780321356680&public=true&share=true"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/addean?" + "apikey=squeamish_ossifrage&amp;session=abcd1234&amp;share=true&amp;public=true" + "&amp;ean=9780321356680</request>" + "<key>squeamish_ossifrage</key></info>" + "<addean><msg>Your item has been added</msg><error_msg></error_msg>" + "<imgurl>http://example.com/images/418.jpg</imgurl>" + "<title>Book</title></addean>" + "<error><errorcode>0</errorcode><string>Success</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); AddEanResult result = client.addEan("abcd1234", "9780321356680", ShareWith.PUBLIC); assertEquals("Your item has been added", result.getMessage()); assertEquals("", result.getErrorMessage()); assertEquals("http://example.com/images/418.jpg", result.getImageUrl()); assertEquals("Book", result.getTitle()); verify(mockHttpClient); } public void testShouldAddEanSharedWithFriends() throws Exception { HttpUriRequest expectedRequest = new HttpPost("http://www.beepmystuff.com/api/addean" + "?apikey=squeamish_ossifrage&session=abcd1234&ean=9780321356680&public=false&share=true"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/addean?" + "apikey=squeamish_ossifrage&amp;session=abcd1234&amp;share=true&amp;public=false" + "&amp;ean=9780321356680</request>" + "<key>squeamish_ossifrage</key></info>" + "<addean><msg>Your item has been added</msg><error_msg></error_msg>" + "<imgurl>http://example.com/images/418.jpg</imgurl>" + "<title>Book</title></addean>" + "<error><errorcode>0</errorcode><string>Success</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); AddEanResult result = client.addEan("abcd1234", "9780321356680", ShareWith.FRIENDS); assertEquals("Your item has been added", result.getMessage()); assertEquals("", result.getErrorMessage()); assertEquals("http://example.com/images/418.jpg", result.getImageUrl()); assertEquals("Book", result.getTitle()); verify(mockHttpClient); } public void testShouldAddEanSharedWithNobody() throws Exception { HttpUriRequest expectedRequest = new HttpPost("http://www.beepmystuff.com/api/addean" + "?apikey=squeamish_ossifrage&session=abcd1234&ean=9780321356680&public=false&share=false"); String response = "<result><info><version>1.0</version>" + "<request>http://www.beepmystuff.com/api/addean?" + "apikey=squeamish_ossifrage&amp;session=abcd1234&amp;share=false&amp;public=false" + "&amp;ean=9780321356680</request>" + "<key>squeamish_ossifrage</key></info>" + "<addean><msg>Your item has been added</msg><error_msg></error_msg>" + "<imgurl>http://example.com/images/418.jpg</imgurl>" + "<title>Book</title></addean>" + "<error><errorcode>0</errorcode><string>Success</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); AddEanResult result = client.addEan("abcd1234", "9780321356680", ShareWith.PRIVATE); assertEquals("Your item has been added", result.getMessage()); assertEquals("", result.getErrorMessage()); assertEquals("http://example.com/images/418.jpg", result.getImageUrl()); assertEquals("Book", result.getTitle()); verify(mockHttpClient); } public void testShouldExtractTextFromXml() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info><version>1.0</version><request>url</request></info></result>"; Document document = rawClient.parse(response); assertEquals("url", BmsRawHttpApiClient.getTextContent(document, "info", "request")); } public void testShouldFailToExtractTextIfNonUnique() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info><request>url</request>" + "<version>1.0</version><request>url</request></info></result>"; Document document = rawClient.parse(response); try { BmsRawHttpApiClient.getTextContent(document, "info", "request"); fail("Expected BmsClientException"); } catch(BmsClientException e) { assertEquals("Document has more than one 'request' child in path [info, request]", e.getMessage()); } } public void testShouldFailToExtractTextIfNotFound() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info><request>url</request>" + "<version>1.0</version><request>url</request></info></result>"; Document document = rawClient.parse(response); try { BmsRawHttpApiClient.getTextContent(document, "notfound", "request"); fail("Expected BmsClientException"); } catch(BmsClientException e) { assertEquals("Document has no 'notfound' child in path [notfound, request]", e.getMessage()); } } public void testShouldFailToExtractTextIfMixedContent() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info>some info here" + "<version>1.0</version><request>url</request></info></result>"; Document document = rawClient.parse(response); try { BmsRawHttpApiClient.getTextContent(document, "info"); fail("Expected BmsClientException"); } catch(BmsClientException e) { assertEquals("Mixed-content element (type 1) at path [info]", e.getMessage()); } } public void testShouldExtractTextIgnoringComments() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); // Technically, I think this _is_ mixed content too, but we know what it // means. String response = "<result><info><version><!-- some comments here -->" + "1.0<!-- and here --> at least</version></info></result>"; Document document = rawClient.parse(response); assertEquals("1.0 at least", BmsRawHttpApiClient.getTextContent(document, "info", "version")); } public void testShouldExtractTextCombiningTextAndCData() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info><version attr=\"attr\">1.0<![CDATA[ (<>) ]]> 2.0" + "</version></info></result>"; Document document = rawClient.parse(response); assertEquals("1.0 (<>) 2.0", BmsRawHttpApiClient.getTextContent(document, "info", "version")); } public void testShouldExtractTextFromEmptyElement() throws Exception { BmsHttpClient dummyClient = createMock(BmsHttpClient.class); replay(dummyClient); DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(dummyClient); String response = "<result><info><version/></info></result>"; Document document = rawClient.parse(response); assertEquals("", BmsRawHttpApiClient.getTextContent(document, "info", "version")); } public void testShouldParseErrorDetailsFromResponse() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "<result>" + "<error><errorcode>-3</errorcode><string>Session has expired</string></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap()); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertEquals(BmsApiException.ErrorCode.INVALID_SESSION, e.getErrorCode()); assertEquals("Session has expired", e.getMessage()); } verify(mockHttpClient); } public void testShouldOnlyCheckErrorMessageIfError() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "<result>" + "<error><errorcode>0</errorcode></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); assertNotNull(rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap())); verify(mockHttpClient); } public void testShouldThrowIfErrorCodeUnparsable() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "<result>" + "<error><errorcode>kittens</errorcode></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap()); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Error parsing result: errorcode 'kittens' unparsable", e.getMessage()); } verify(mockHttpClient); } public void testShouldThrowIfErrorCodeUnknown() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "<result>" + "<error><errorcode>404</errorcode></error></result>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap()); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Error parsing result: errorcode 404 unknown", e.getMessage()); } verify(mockHttpClient); } public void testShouldThrowIfResponseUnparsable() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "I'm not <xml>"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap()); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertTrue(e.getMessage().startsWith("Error parsing result: ")); assertTrue(e.getCause() instanceof SAXException); } verify(mockHttpClient); } public void testShouldThrowIfResponseIsText() throws Exception { DefaultBmsLowLevelClient.BmsRawHttpApiClient rawClient = new DefaultBmsLowLevelClient.BmsRawHttpApiClient(mockHttpClient); HttpUriRequest expectedRequest = new HttpGet("http://www.beepmystuff.com/api/verb"); String response = "418 I'm a little teapot"; expect(mockHttpClient.getResponseBodyAsString(eqHttpRequest(expectedRequest))) .andReturn(response); replay(mockHttpClient); try { rawClient.makeRpc("verb", true, Collections.<String, String>emptyMap()); fail("Expected BmsClientException"); } catch (BmsClientException e) { assertEquals("Error parsing result: no document element", e.getMessage()); assertNull(e.getCause()); } verify(mockHttpClient); } /** Expects an HttpRequest that is equal to the given value. */ private static <T extends HttpRequest> T eqHttpRequest(T value) { reportMatcher(new HttpRequestEquals(value)); return null; } /** * A matcher for HttpRequest, as the default implementations implement * neither equals() nor toString(). */ private static class HttpRequestEquals implements IArgumentMatcher { private final HttpRequest expected; public HttpRequestEquals(HttpRequest expected) { this.expected = expected; } @Override public boolean matches(Object argument) { if (!(argument instanceof HttpRequest)) { return false; } return toString(expected).equals(toString((HttpRequest) argument)); } @Override public void appendTo(StringBuffer buffer) { buffer.append(toString(expected)); } private static String toString(HttpRequest request) { StringBuilder sb = new StringBuilder(); sb.append(request.getRequestLine()); for (Header header : request.getAllHeaders()) { sb.append(String.format("\n%s: %s", header.getName(), header.getValue())); } return sb.toString(); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import com.google.beepmystuff.BmsClient.SessionStorage; /** * An {@link Injector} that must be provided with explicit dependencies, for * tests. */ public class TestInjector extends Injector { private BmsHttpClient bmsHttpClient; private BmsLowLevelClient bmsLowLevelClient; private Preferences preferences; private SessionStorage sessionStorage; @Override public synchronized BmsHttpClient getBmsHttpClient() { if (bmsHttpClient == null) { throw new IllegalStateException("no injected BmsHttpClient available"); } return bmsHttpClient; } public TestInjector setBmsHttpClient(BmsHttpClient bmsHttpClient) { this.bmsHttpClient = bmsHttpClient; return this; } @Override public synchronized BmsLowLevelClient getBmsLowLevelClient() { if (bmsLowLevelClient == null) { throw new IllegalStateException("no injected BmsLowLevelClient available"); } return bmsLowLevelClient; } public TestInjector setBmsLowLevelClient(BmsLowLevelClient bmsLowLevelClient) { this.bmsLowLevelClient = bmsLowLevelClient; return this; } @Override public synchronized Preferences getPreferences() { if (preferences == null) { throw new IllegalStateException("no injected Preferences available"); } return preferences; } public TestInjector setPreferences(Preferences preferences) { this.preferences = preferences; return this; } @Override public synchronized SessionStorage getSessionStorage() { if (sessionStorage == null) { throw new IllegalStateException("no injected SessionStorage available"); } return sessionStorage; } public TestInjector setSessionStorage(SessionStorage sessionStorage) { this.sessionStorage = sessionStorage; return this; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.replay; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.test.ActivityUnitTestCase; /** * Test cases for the home screen activity. */ public class HomeScreenActivityTest extends ActivityUnitTestCase<HomeScreenActivity> { private static final String SESSION_TOKEN = "a_session_token"; private static final String PASSWORD = "a_password"; private static final String NICKNAME = "a_nickname"; private final TestInjector injector; private final BmsLowLevelClient mockBmsLowLevelClient; public HomeScreenActivityTest() { super(HomeScreenActivity.class); injector = new TestInjector(); mockBmsLowLevelClient = createStrictMock(BmsLowLevelClient.class); // order matters } @Override protected void setUp() throws Exception { super.setUp(); Injector.configureForTest(injector); } @Override protected void tearDown() throws Exception { Injector.resetForTest(); super.tearDown(); } /** * Ensures the activity launched and ran ok. */ public void testActivityTestCaseSetUpProperly() throws Exception { FakePreferences preferences = createDefaultFakePreferences(); injector.setPreferences(preferences) .setSessionStorage(preferences) .setBmsHttpClient(new DummyBmsHttpClient()) .setBmsLowLevelClient(mockBmsLowLevelClient); replay(mockBmsLowLevelClient); startActivity(getIntent(), null, null); assertNotNull("activity should be launched successfully", getActivity()); getActivity().onResume(); assertNull(getStartedActivityIntent()); getActivity().waitUntilServiceFullyBound(); } public void testLaunchesLoginActivityOnNoNickname() throws Exception { FakePreferences preferences = createDefaultFakePreferences(); preferences.setNickname(""); injector.setPreferences(preferences) .setSessionStorage(preferences) .setBmsHttpClient(new DummyBmsHttpClient()) .setBmsLowLevelClient(mockBmsLowLevelClient); replay(mockBmsLowLevelClient); startActivity(getIntent(), null, null); getActivity().onResume(); Intent startedIntent = getStartedActivityIntent(); assertNotNull("should have started an intent", startedIntent); assertEquals(LoginActivity.class.getName(), startedIntent.getComponent().getClassName()); getActivity().waitUntilServiceFullyBound(); } public void testLaunchesLoginActivityOnNoPassword() throws Exception { FakePreferences preferences = createDefaultFakePreferences(); preferences.setPassword(""); injector.setPreferences(preferences) .setSessionStorage(preferences) .setBmsHttpClient(new DummyBmsHttpClient()) .setBmsLowLevelClient(mockBmsLowLevelClient); replay(mockBmsLowLevelClient); startActivity(getIntent(), null, null); getActivity().onResume(); Intent startedIntent = getStartedActivityIntent(); assertNotNull("should have started an intent", startedIntent); assertEquals(LoginActivity.class.getName(), startedIntent.getComponent().getClassName()); getActivity().waitUntilServiceFullyBound(); } // TODO: this test seems bogus. Why is the home screen activity checking // the session token? public void testLaunchesLoginActivityOnNoSessionToken() throws Exception { FakePreferences preferences = createDefaultFakePreferences(); preferences.setSessionToken(""); injector.setPreferences(preferences) .setSessionStorage(preferences) .setBmsHttpClient(new DummyBmsHttpClient()) .setBmsLowLevelClient(mockBmsLowLevelClient); replay(mockBmsLowLevelClient); startActivity(getIntent(), null, null); getActivity().onResume(); Intent startedIntent = getStartedActivityIntent(); assertNotNull("should have started an intent", startedIntent); assertEquals(LoginActivity.class.getName(), startedIntent.getComponent().getClassName()); getActivity().waitUntilServiceFullyBound(); } /** * Creates some FakePreferences, with defaults to just get the BeepMyStuff * screen up and running. */ private FakePreferences createDefaultFakePreferences() { FakePreferences fakePreferences = new FakePreferences(); PackageInfo pi; try { PackageManager pm = getInstrumentation().getTargetContext().getPackageManager(); pi = pm.getPackageInfo("com.google.beepmystuff", 0); } catch (NameNotFoundException e) { throw new AssertionError("Could not get our own package info: " + e); } fakePreferences.setLastRunVersion(Integer.toString(pi.versionCode)); fakePreferences.setNickname(NICKNAME); fakePreferences.setPassword(PASSWORD); fakePreferences.setSessionToken(SESSION_TOKEN); return fakePreferences; } /** * Create an Intent to pass to the activity. */ private Intent getIntent() { Intent testIntent = new Intent(); testIntent.addCategory(Intent.CATEGORY_TEST); return testIntent; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import static org.easymock.EasyMock.createMock; import static org.easymock.EasyMock.createStrictMock; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.reset; import static org.easymock.EasyMock.verify; import com.google.beepmystuff.BmsApiException.ErrorCode; import junit.framework.TestCase; public class BmsClientTest extends TestCase { private final BmsClient.SessionStorage sessionStore = createMock(BmsClient.SessionStorage.class); private final BmsLowLevelClient lowLevelClient = createStrictMock(BmsLowLevelClient.class); // order matters! private final BmsClient client = new BmsClient(lowLevelClient, sessionStore); public void testShouldStoreSessionTokenAfterLogin() throws Exception { BmsClient.LoginResult result = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "sessiony"; } }; expect(lowLevelClient.login("nickname", "password")).andReturn(result); sessionStore.setSessionToken("sessiony"); replay(lowLevelClient); replay(sessionStore); assertEquals(result, client.login("nickname", "password")); verify(lowLevelClient); verify(sessionStore); } public void testShouldPropagateExceptionsRaisedDuringLogin() throws Exception { replay(sessionStore); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_USERNAME, "Fail."); expect(lowLevelClient.login("nickname", "password")).andThrow(exception); replay(lowLevelClient); try { client.login("nickname", "password"); fail("Expected BmsApiException"); } catch(BmsApiException e) { assertSame(e, exception); } verify(lowLevelClient); } public void testShouldRequestSessionTokenIfNoneAvailable() throws Exception { // Set credentials without attempting to login. client.setCredentials("nickname", "password"); // Now we can try something that requires a session token. BmsClient.LoginResult loginResult = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "sessiony"; } }; expect(sessionStore.getSessionToken()).andReturn(null); expect(lowLevelClient.login("nickname", "password")).andReturn(loginResult); sessionStore.setSessionToken("sessiony"); expect(lowLevelClient.getAvatarPath("sessiony")).andReturn("somepath"); replay(lowLevelClient); replay(sessionStore); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); verify(sessionStore); } public void testShouldReuseLastUsedSessionToken() throws Exception { // Repeat the test above: no session token known, none available in storage. client.setCredentials("nickname", "password"); BmsClient.LoginResult loginResult = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "sessiony"; } }; expect(sessionStore.getSessionToken()).andReturn(null); expect(lowLevelClient.login("nickname", "password")).andReturn(loginResult); sessionStore.setSessionToken("sessiony"); expect(lowLevelClient.getAvatarPath("sessiony")).andReturn("somepath"); replay(lowLevelClient); replay(sessionStore); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); verify(sessionStore); // Now, the next request should use the cached session token without // consulting the session store. reset(lowLevelClient); reset(sessionStore); replay(sessionStore); expect(lowLevelClient.getAvatarPath("sessiony")).andReturn("somepath"); replay(lowLevelClient); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); } public void testShouldUseStoredSessionToken() throws Exception { // Don't set any credentials. expect(sessionStore.getSessionToken()).andReturn("sessiony"); replay(sessionStore); expect(lowLevelClient.getAvatarPath("sessiony")).andReturn("somepath"); replay(lowLevelClient); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); verify(sessionStore); // Again, the next request should use the cached session token without // consulting the session store. reset(lowLevelClient); reset(sessionStore); replay(sessionStore); expect(lowLevelClient.getAvatarPath("sessiony")).andReturn("somepath"); replay(lowLevelClient); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); } public void testShouldPropagateNonSessionException() throws Exception { // Don't set any credentials. expect(sessionStore.getSessionToken()).andReturn("sessiony"); replay(sessionStore); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_KEY, "Fail."); expect(lowLevelClient.getAvatarPath("sessiony")).andThrow(exception); replay(lowLevelClient); try { client.getAvatarPath(); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertSame(exception, e); } verify(lowLevelClient); verify(sessionStore); } public void testShouldRequestSessionTokenIfExpired() throws Exception { client.setCredentials("nickname", "password"); expect(sessionStore.getSessionToken()).andReturn("sessiony"); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_SESSION, "Ohno!"); expect(lowLevelClient.getAvatarPath("sessiony")).andThrow(exception); sessionStore.setSessionToken(null); BmsClient.LoginResult loginResult = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "newsessiony"; } }; expect(lowLevelClient.login("nickname", "password")).andReturn(loginResult); sessionStore.setSessionToken("newsessiony"); expect(lowLevelClient.getAvatarPath("newsessiony")).andReturn("somepath"); replay(sessionStore); replay(lowLevelClient); assertEquals("somepath", client.getAvatarPath()); verify(lowLevelClient); verify(sessionStore); } public void testShouldOnlyRequestSessionTokenOnce() throws Exception { // Infinite loops of 'session expired' are bad, so we only retry once. client.setCredentials("nickname", "password"); expect(sessionStore.getSessionToken()).andReturn("sessiony"); expect(lowLevelClient.getAvatarPath("sessiony")).andThrow( new BmsApiException(ErrorCode.INVALID_SESSION, "Ohno!")); sessionStore.setSessionToken(null); BmsClient.LoginResult loginResult = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "newsessiony"; } }; expect(lowLevelClient.login("nickname", "password")).andReturn(loginResult); sessionStore.setSessionToken("newsessiony"); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_SESSION, "Still Ohno!"); expect(lowLevelClient.getAvatarPath("newsessiony")).andThrow(exception); sessionStore.setSessionToken(null); replay(sessionStore); replay(lowLevelClient); try { client.getAvatarPath(); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertSame(exception, e); } verify(lowLevelClient); verify(sessionStore); } public void testShouldNotRequestSessionTokenIfNew() throws Exception { // We don't call login more than once per request. client.setCredentials("nickname", "password"); BmsClient.LoginResult loginResult = new BmsClient.LoginResult() { @Override public String getSessionToken() { return "sessiony"; } }; expect(sessionStore.getSessionToken()).andReturn(null); expect(lowLevelClient.login("nickname", "password")).andReturn(loginResult); sessionStore.setSessionToken("sessiony"); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_SESSION, "Ohno!"); expect(lowLevelClient.getAvatarPath("sessiony")).andThrow(exception); sessionStore.setSessionToken(null); replay(sessionStore); replay(lowLevelClient); try { client.getAvatarPath(); fail("Expected BmsApiException"); } catch (BmsApiException e) { assertSame(exception, e); } verify(lowLevelClient); verify(sessionStore); } public void testShouldRetainOldCredentialsIfLoginFailed() throws Exception { client.setCredentials("nickname", "password"); BmsApiException exception = new BmsApiException(ErrorCode.INVALID_USERNAME, "Fail."); expect(lowLevelClient.login("newnickname", "secretpassword")).andThrow(exception); replay(lowLevelClient); replay(sessionStore); try { client.login("newnickname", "secretpassword"); fail("Expected BmsApiException"); } catch(BmsApiException e) { assertSame(e, exception); } verify(lowLevelClient); reset(lowLevelClient); reset(sessionStore); // Now try something that requires a login. It should use the old // credentials. Just for fun, let's pretend that they didn't work either. expect(sessionStore.getSessionToken()).andReturn(null); expect(lowLevelClient.login("nickname", "password")).andThrow(exception); replay(lowLevelClient); replay(sessionStore); try { client.getAvatarPath(); fail("Expected BmsApiException"); } catch(BmsApiException e) { assertSame(e, exception); } verify(lowLevelClient); verify(sessionStore); } public void testShouldAllowAddingEan() throws Exception { expect(sessionStore.getSessionToken()).andReturn("sessiony"); replay(sessionStore); BmsClient.AddEanResult dummyResult = new BmsClient.AddEanResult() { @Override public String getErrorMessage() { throw new UnsupportedOperationException(); } @Override public String getImageUrl() { throw new UnsupportedOperationException(); } @Override public String getMessage() { throw new UnsupportedOperationException(); } @Override public String getTitle() { throw new UnsupportedOperationException(); } }; expect(lowLevelClient.addEan("sessiony", "1234", BmsClient.ShareWith.PUBLIC)) .andReturn(dummyResult); replay(lowLevelClient); assertSame(dummyResult, client.addEan("1234", BmsClient.ShareWith.PUBLIC)); verify(lowLevelClient); verify(sessionStore); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.database.Cursor; import android.test.AndroidTestCase; /** * Tests the ScanRegistry. * * Uses a temporary file to back the ScanRegistry's sqlite database. * TODO: more tests! */ public class ScanRegistryTest extends AndroidTestCase { private ScanRegistry scanRegistry; private MockClock mockClock; private static class MockClock implements ScanRegistry.Clock { public void setTime(long time) { now = time; } private long now; @Override public long now() { return now; } } @Override public void setUp() { mockClock = new MockClock(); scanRegistry = new ScanRegistry(getContext(), mockClock, null); } @Override public void tearDown() { scanRegistry.close(); } /** * Ensure a fresh database is empty. */ public void testDatabaseInitiallyEmpty() { Cursor displayCursor = scanRegistry.getDisplayCursor(); assertTrue(displayCursor.isBeforeFirst()); assertTrue(displayCursor.isAfterLast()); } /** * Add an item and test it is the only item in the database. */ public void testAddItem() { long id = scanRegistry.addEan("12345", BmsClient.ShareWith.PUBLIC); Cursor displayCursor = scanRegistry.getDisplayCursor(); assertTrue(displayCursor.isBeforeFirst()); assertFalse(displayCursor.isAfterLast()); assertTrue(displayCursor.moveToNext()); ScanRegistry.Item item = scanRegistry.createItemFromCursor(displayCursor); assertEquals(item.getId(), id); assertEquals("12345", item.getEan()); assertFalse(displayCursor.moveToNext()); assertTrue(displayCursor.isAfterLast()); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import org.apache.http.client.methods.HttpUriRequest; /** A dummy {@link BmsHttpClient} that does nothing. */ public class DummyBmsHttpClient implements BmsHttpClient { @Override public byte[] getResponseBody(HttpUriRequest request) throws BmsTransportException { throw new UnsupportedOperationException(); } @Override public String getResponseBodyAsString(HttpUriRequest request) throws BmsTransportException { throw new UnsupportedOperationException(); } }
Java
/* * Copyright 2009 ZXing authors * * 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.google.zxing.integration.android; /** * <p>Encapsulates the result of a barcode scan invoked through {@link IntentIntegrator}.</p> * * @author Sean Owen */ public final class IntentResult { private final String contents; private final String formatName; IntentResult(String contents, String formatName) { this.contents = contents; this.formatName = formatName; } /** * @return raw content of barcode */ public String getContents() { return contents; } /** * @return name of format, like "QR_CODE", "UPC_A". See <code>BarcodeFormat</code> for more format names. */ public String getFormatName() { return formatName; } }
Java
/* * Copyright 2009 ZXing authors * * 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.google.zxing.integration.android; import android.app.AlertDialog; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; /** * <p>A utility class which helps ease integration with Barcode Scanner via {@link Intent}s. This is a simple * way to invoke barcode scanning and receive the result, without any need to integrate, modify, or learn the * project's source code.</p> * * <h2>Initiating a barcode can</h2> * * <p>Integration is essentially as easy as calling {@link #initiateScan(Activity)} and waiting * for the result in your app.</p> * * <p>It does require that the Barcode Scanner application is installed. The * {@link #initiateScan(Activity)} method will prompt the user to download the application, if needed.</p> * * <p>There are a few steps to using this integration. First, your {@link Activity} must implement * the method {@link Activity#onActivityResult(int, int, Intent)} and include a line of code like this:</p> * * <p>{@code * public void onActivityResult(int requestCode, int resultCode, Intent intent) { * IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); * if (scanResult != null) { * // handle scan result * } * // else continue with any other code you need in the method * ... * } * }</p> * * <p>This is where you will handle a scan result. * Second, just call this in response to a user action somewhere to begin the scan process:</p> * * <p>{@code integrator.initiateScan();}</p> * * <p>You can use {@link #initiateScan(Activity, String, String, String, String)} or * {@link #initiateScan(Activity, int, int, int, int)} to customize the download prompt with * different text labels.</p> * * <h2>Sharing text via barcode</h2> * * <p>To share text, encoded as a QR Code on-screen, similarly, see {@link #shareText(Activity, String)}.</p> * * <p>Some code, particularly download integration, was contributed from the Anobiit application.</p> * * @author Sean Owen * @author Fred Lin * @author Isaac Potoczny-Jones */ public final class IntentIntegrator { public static final int REQUEST_CODE = 0x0ba7c0de; // get it? private static final String DEFAULT_TITLE = "Install Barcode Scanner?"; private static final String DEFAULT_MESSAGE = "This application requires Barcode Scanner. Would you like to install it?"; private static final String DEFAULT_YES = "Yes"; private static final String DEFAULT_NO = "No"; private IntentIntegrator() { } /** * See {@link #initiateScan(Activity, String, String, String, String)} -- * same, but uses default English labels. */ public static void initiateScan(Activity activity) { initiateScan(activity, DEFAULT_TITLE, DEFAULT_MESSAGE, DEFAULT_YES, DEFAULT_NO); } /** * See {@link #initiateScan(Activity, String, String, String, String)} -- * same, but takes string IDs which refer * to the {@link Activity}'s resource bundle entries. */ public static void initiateScan(Activity activity, int stringTitle, int stringMessage, int stringButtonYes, int stringButtonNo) { initiateScan(activity, activity.getString(stringTitle), activity.getString(stringMessage), activity.getString(stringButtonYes), activity.getString(stringButtonNo)); } /** * Invokes scanning. * * @param stringTitle title of dialog prompting user to download Barcode Scanner * @param stringMessage text of dialog prompting user to download Barcode Scanner * @param stringButtonYes text of button user clicks when agreeing to download * Barcode Scanner (e.g. "Yes") * @param stringButtonNo text of button user clicks when declining to download * Barcode Scanner (e.g. "No") * @return the contents of the barcode that was scanned, or null if none was found * @throws InterruptedException if timeout expires before a scan completes */ public static void initiateScan(Activity activity, String stringTitle, String stringMessage, String stringButtonYes, String stringButtonNo) { Intent intentScan = new Intent("com.google.zxing.client.android.SCAN"); intentScan.addCategory(Intent.CATEGORY_DEFAULT); try { activity.startActivityForResult(intentScan, REQUEST_CODE); } catch (ActivityNotFoundException e) { showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo); } } private static void showDownloadDialog(final Activity activity, String stringTitle, String stringMessage, String stringButtonYes, String stringButtonNo) { AlertDialog.Builder downloadDialog = new AlertDialog.Builder(activity); downloadDialog.setTitle(stringTitle); downloadDialog.setMessage(stringMessage); downloadDialog.setPositiveButton(stringButtonYes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android"); Intent intent = new Intent(Intent.ACTION_VIEW, uri); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { new AlertDialog.Builder(activity) .setTitle("Attention") .setMessage("Couldn't launch the Market. Perhaps it isn't installed?") .setPositiveButton("OK", null) .show(); } } }); downloadDialog.setNegativeButton(stringButtonNo, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) {} }); downloadDialog.show(); } /** * <p>Call this from your {@link Activity}'s * {@link Activity#onActivityResult(int, int, Intent)} method.</p> * * @return null if the event handled here was not related to {@link IntentIntegrator}, or * else an {@link IntentResult} containing the result of the scan. If the user cancelled scanning, * the fields will be null. */ public static IntentResult parseActivityResult(int requestCode, int resultCode, Intent intent) { if (requestCode == REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { String contents = intent.getStringExtra("SCAN_RESULT"); String formatName = intent.getStringExtra("SCAN_RESULT_FORMAT"); return new IntentResult(contents, formatName); } else { return new IntentResult(null, null); } } return null; } /** * See {@link #shareText(Activity, String, String, String, String, String)} -- * same, but uses default English labels. */ public static void shareText(Activity activity, String text) { shareText(activity, text, DEFAULT_TITLE, DEFAULT_MESSAGE, DEFAULT_YES, DEFAULT_NO); } /** * See {@link #shareText(Activity, String, String, String, String, String)} -- * same, but takes string IDs which refer to the {@link Activity}'s resource bundle entries. */ public static void shareText(Activity activity, String text, int stringTitle, int stringMessage, int stringButtonYes, int stringButtonNo) { shareText(activity, text, activity.getString(stringTitle), activity.getString(stringMessage), activity.getString(stringButtonYes), activity.getString(stringButtonNo)); } /** * Shares the given text by encoding it as a barcode, such that another user can * scan the text off the screen of the device. * * @param text the text string to encode as a barcode * @param stringTitle title of dialog prompting user to download Barcode Scanner * @param stringMessage text of dialog prompting user to download Barcode Scanner * @param stringButtonYes text of button user clicks when agreeing to download * Barcode Scanner (e.g. "Yes") * @param stringButtonNo text of button user clicks when declining to download * Barcode Scanner (e.g. "No") */ public static void shareText(Activity activity, String text, String stringTitle, String stringMessage, String stringButtonYes, String stringButtonNo) { Intent intent = new Intent(); intent.setAction("com.google.zxing.client.android.ENCODE"); intent.putExtra("ENCODE_TYPE", "TEXT_TYPE"); intent.putExtra("ENCODE_DATA", text); try { activity.startActivity(intent); } catch (ActivityNotFoundException e) { showDownloadDialog(activity, stringTitle, stringMessage, stringButtonYes, stringButtonNo); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; /** * An exception representing a failure to communicate with a server due to * transport errors (e.g. an IOException reading data, or a 5xx series * HTTP error). * * Operations that fail with this exception may always be retried * without further user input. */ @SuppressWarnings("serial") public class BmsTransportException extends BmsException { public BmsTransportException(String reason) { super(reason); } public BmsTransportException(String reason, Throwable cause) { super(reason, cause); } @Override public boolean canRetry() { return true; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import android.widget.CursorAdapter; import com.google.beepmystuff.NetworkService.NetworkServiceConnection; /** * Shows a list of the most recently scanned items. * Based on a list view activity. */ public class RecentlyScannedActivity extends ListActivity { private static final String TAG = "BMS.RecentlyScannedActivity"; private NetworkServiceConnection networkServiceConnection = new NetworkServiceConnection(); private NetworkService networkService; private CursorAdapter adapter; /** * Called when the activity is first created. * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.recently_scanned); // Establish a connection with our service (starting it if necessary). NetworkService.bind(this, networkServiceConnection, new Runnable() { @Override public void run() { networkService = networkServiceConnection.getService(); createAfterServiceAvailable(); } }); } /** Continue creation after the network service has been started. */ private void createAfterServiceAvailable() { // Create the list view adapter which takes information from the // ScanRegistry and binds it to our view. ScanRegistry scanRegistry = networkService.getScanRegistry(); adapter = new ScanRegistryAdapter(getApplicationContext(), R.layout.item, scanRegistry .getDisplayCursor(), new String[] { ScanRegistry.FIELD_EAN, ScanRegistry.FIELD_TITLE, ScanRegistry.FIELD_STATUS }, new int[] { R.id.ean, R.id.description, R.id.status }); setListAdapter(adapter); // Add a listener to the scan registry, listening for change events in the // data, and causing the list view to refresh. Note that the events come in // from a separate thread but the adapter needs to be queried in the UI // thread. scanRegistry.addListener(new ScanRegistry.Listener() { public void notifyChanged() { runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "Data changed, requerying"); adapter.getCursor().requery(); } }); } }); } /** * Called before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); // This check isn't foolproof: if the service has been recently unbound, // we may not have received the notification yet, but this call will still // fail. Luckily, we're the only people who unbind the service, so we // should be okay. if (networkServiceConnection.getService() != null) { unbindService(networkServiceConnection); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import org.apache.http.client.methods.HttpUriRequest; /** * An abstraction for HTTP requests made by the BMS API. */ public interface BmsHttpClient { /** * Makes an HTTP request using our client, and returns the body of the * response. * * @throws BmsTransportException if the request was unsuccessful (i.e. the * HTTP request could not be made). */ byte[] getResponseBody(HttpUriRequest request) throws BmsTransportException; /** * Makes an HTTP request using our client, and returns the body of the * response as a string. * * <p>Note: assumes that the response is delivered in UTF-8 encoding. * * @throws BmsTransportException if the request was unsuccessful (i.e. the * HTTP request could not be made). */ String getResponseBodyAsString(HttpUriRequest request) throws BmsTransportException; }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import java.util.concurrent.Callable; import android.util.Log; /** * Implements a high-level wrapper around the Beep My Stuff HTTP API, * documented at http://www.beepmystuff.com/static/apidocs/index.html. * * This class automatically re-requests session tokens as required, reissuing * commands as necessary when session tokens expire. Users provide an optional * callback to allow the session token to be persisted, and set the credentials * to use via {@link #setCredentials(String, String)}. * * Instances of this class are thread-safe. */ public class BmsClient { private static final String TAG = "BMS.BmsClient"; /** * Provides methods to read and write the session token to persistent storage. */ public interface SessionStorage { /** Returns the session token, or null if no token is persisted. */ String getSessionToken(); /** * Saves the session token. May provide a null token if the current token * has expired. */ void setSessionToken(String sessionToken); } /** The low-level client. */ private final BmsLowLevelClient client; /** The session storage callback. */ private final SessionStorage sessionStorage; /** The current session token, or null if none exists. */ private String sessionToken = null; /** Whether we've fetched an initial session token from storage. */ private boolean haveReadSessionToken = false; /** The most-recently-used nickname. */ private String nickname = null; /** The most-recently-used password. */ private String password = null; /** * Creates a new client using the provided low-level client and optional * session storage callback. * * @param client the BMS Low-level client * @param sessionStorage the session storage callback, or null if no * persistent storage is available. */ public BmsClient(BmsLowLevelClient client, SessionStorage sessionStorage) { this.client = client; this.sessionStorage = sessionStorage != null ? sessionStorage : new NullSessionStorage(); } /** * Provides credentials for future login attempts (but does not actually * force a login). * * Only invalidates the current session token (if one is available) if the * nickname provided is different to that which was previously provided. * If no nickname has previously been provided, assumes that the session token * should be reused. */ public synchronized void setCredentials(String nickname, String password) { if (nickname.equals(this.nickname) && password.equals(this.password)) { return; } Log.v(TAG, "Received new credentials"); if (this.nickname != null && !this.nickname.equals(nickname)) { invalidateSessionToken(); } this.nickname = nickname; this.password = password; } /** * Log a user in to to Beep My Stuff to get a valid session token. * * Users do not need to call this method, but can do so to force a login using * the specified nickname and password. If successful, the session token will * be cached, and stored using the session storage callback, and the * credentials will be cached for future reuse. * * @param nickname the nickname of the user who wants to login * @param password the API password for the user * @return the result of this call * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public synchronized LoginResult login(String nickname, String password) throws BmsTransportException, BmsApiException { Log.v(TAG, String.format("RPC: login(%s, %s)", nickname, password)); LoginResult result = client.login(nickname, password); this.nickname = nickname; this.password = password; sessionToken = result.getSessionToken(); sessionStorage.setSessionToken(sessionToken); Log.d(TAG, "got session token " + sessionToken); return result; } /** * Result information for the "log in" call. * Holds the session token. */ public static interface LoginResult { /** Returns the session token associated with this log in. */ String getSessionToken(); } /** * Who to share an item with. * @see #addEan(String, ShareWith) */ enum ShareWith { /** Visible only to the user. */ PRIVATE, /** Share with the user's friends. */ FRIENDS, /** Share publicly. */ PUBLIC; /** Returns valueOf(name), or defaultValue if the name is not valid. */ public static ShareWith tryValueOf(String name, ShareWith defaultValue) { try { return valueOf(name); } catch (IllegalArgumentException e) { return defaultValue; } } } /** * Add an EAN to the user's library. * * @param ean a valid EAN or UPC * @param shareWith who the item should be shared with * @return the result of this call * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public synchronized AddEanResult addEan(final String ean, final ShareWith shareWith) throws BmsTransportException, BmsApiException { Log.v(TAG, String.format("RPC: addEan(%s, %s)", ean, shareWith)); return makeRpcWithAutoRetryOnSessionExpiration(new ApiCallable<AddEanResult>() { @Override public AddEanResult call() throws BmsApiException, BmsTransportException { return client.addEan(sessionToken, ean, shareWith); } }); } /** * Extended result interface for the "Add an EAN" call. * Holds extra information about the item that was added, if successful. */ public static interface AddEanResult { /** * Returns the BeepMyStuff "add" message. */ String getMessage(); /** * Returns the BeepMyStuff error message for the add, if any. This is * set when (e.g.) adding an existing item. * * If this is set then all other fields will be invalid. */ String getErrorMessage(); /** * Returns the image URL associated with this added item. May be empty if * there is no image. */ String getImageUrl(); /** * Returns the title of this added item. */ String getTitle(); } /** * Returns the path to the user's avatar icon. * * @return the path to the icon. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public synchronized String getAvatarPath() throws BmsTransportException, BmsApiException { Log.v(TAG, String.format("RPC: getAvatarPath()")); return makeRpcWithAutoRetryOnSessionExpiration(new ApiCallable<String>() { @Override public String call() throws BmsApiException, BmsTransportException { return client.getAvatarPath(sessionToken); } }); } /** A Callable with a narrowed throws clause. */ private static interface ApiCallable<T> extends Callable<T> { @Override public T call() throws BmsApiException, BmsTransportException; } /** * Perform an RPC (represented by a Callable), returning the result. * * Automatically reissues the request (once) if the first request used a * cached session token that has expired. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ private <T> T makeRpcWithAutoRetryOnSessionExpiration(ApiCallable<T> callable) throws BmsTransportException, BmsApiException { if (!haveReadSessionToken) { Log.d(TAG, "Reading stored session token, if any"); sessionToken = sessionStorage.getSessionToken(); haveReadSessionToken = true; } // If we have a session token, make a call using our (possibly-stale) // token. Otherwise, fall through to where we'll request a new token. if (sessionToken != null) { try { return callable.call(); } catch (BmsApiException e) { if ((e.getErrorCode() != BmsApiException.ErrorCode.INVALID_SESSION)) { // Some other error. throw e; } } // Session token was stale, so invalidate what we have and keep going. invalidateSessionToken(); } else { Log.d(TAG, "No session token, requesting one"); } // Request a new session token. if (nickname == null || password == null) { throw new BmsClientException("Can't login, no nickname/password"); } login(nickname, password); if (sessionToken == null) { throw new BmsClientException("Login resulted in a null session token?"); } // Make the call using our new shiny session token. Propagate any errors // we see. try { return callable.call(); } catch (BmsApiException e) { if ((e.getErrorCode() == BmsApiException.ErrorCode.INVALID_SESSION)) { // Well, that's odd. invalidateSessionToken(); } throw e; } } /** * Invalidates the cached session token. Called when an invalid session API * error is returned, so that the session token will not be reused. */ private void invalidateSessionToken() { Log.v(TAG, "Invalidating session token"); sessionToken = null; sessionStorage.setSessionToken(null); } /** Returns the cached session token. */ // VisibleForTesting String getCachedSessionToken() { return sessionToken; } /** A null implementation of the SessionStorage interface. */ private static class NullSessionStorage implements SessionStorage { @Override public String getSessionToken() { return null; } @Override public void setSessionToken(String sessionToken) { } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.View; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; /** * An implementation of SimpleCursorAdapter which binds BeepMyStuff item * entries to the item.xml layout, including decoding the image and setting * it as a bitmap. */ public class ScanRegistryAdapter extends SimpleCursorAdapter { public ScanRegistryAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); } @Override public void bindView(View view, Context context, Cursor cursor) { super.bindView(view, context, cursor); ImageView imageView = (ImageView) view.findViewById(R.id.item_image); int imageIndex = cursor.getColumnIndexOrThrow(ScanRegistry.FIELD_IMAGE_DATA); byte[] data = cursor.getBlob(imageIndex); if (data != null) { Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length); imageView.setImageBitmap(bm); } else { int stateIndex = cursor.getColumnIndexOrThrow(ScanRegistry.FIELD_STATE); int state = cursor.getInt(stateIndex); if (ScanRegistry.isStatePendingImage(state)) { imageView.setImageResource(R.drawable.waiting); } else { imageView.setImageResource(R.drawable.error); } } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.os.Bundle; import android.preference.PreferenceActivity; /** * Extremely lightweight class to provide access to the BeepMyStuff client * settings. */ public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.settings); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; /** * Implements an activity for entering product codes by hand. */ public class ManualEntryActivity extends Activity { /** * Array of ids associated with the button grid. * @see #KEYCODES */ private static final int[] BUTTONS = { R.id.zero, R.id.one, R.id.two, R.id.three, R.id.four, R.id.five, R.id.six, R.id.seven, R.id.eight, R.id.nine, R.id.backspace }; /** * Array of key codes corresponding to pressing the on-screen buttons. * Must be in the same order as the BUTTONS array. * @see #BUTTONS */ private static final int[] KEYCODES = { KeyEvent.KEYCODE_0, KeyEvent.KEYCODE_1, KeyEvent.KEYCODE_2, KeyEvent.KEYCODE_3, KeyEvent.KEYCODE_4, KeyEvent.KEYCODE_5, KeyEvent.KEYCODE_6, KeyEvent.KEYCODE_7, KeyEvent.KEYCODE_8, KeyEvent.KEYCODE_9, KeyEvent.KEYCODE_DEL, }; private EditText editText; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.manual_entry); editText = (EditText) findViewById(R.id.manual_entry_edit); Button submitButton = (Button) findViewById(R.id.submit); submitButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { submit(); } }); OnClickListener buttonListener = new OnClickListener() { @Override public void onClick(View view) { for (int i = 0; i < BUTTONS.length; ++i) { if (BUTTONS[i] == view.getId()) { handleButtonPress(i); return; } } throw new AssertionError("Unknown button clicked"); } }; for (int buttonId : BUTTONS) { Button button = (Button) findViewById(buttonId); button.setOnClickListener(buttonListener); } } public void submit() { Intent result = new Intent(); result.putExtra("SCAN_RESULT", editText.getText().toString()); result.putExtra("SCAN_TYPE", "MANUAL"); setResult(RESULT_OK, result); finish(); } public void handleButtonPress(int buttonIndex) { int keyCode = KEYCODES[buttonIndex]; editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, keyCode)); editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, keyCode)); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.content.Context; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; import com.google.beepmystuff.BmsClient.ShareWith; /** Encapsulates the preferences used by the BeepMyStuff activities. */ public class SharedPreferences implements BmsClient.SessionStorage, Preferences { private final String keyNickname; private final String keyPassword; private final String keyShareWith; private final ShareWith shareWithDefault; private final String keySessionToken; private final String keyLastRunVersion; private final android.content.SharedPreferences sharedPreferences; /** * Constructs a Preferences object backed by the default shared preferences * for the given context. */ public SharedPreferences(Context context) { sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); keyNickname = context.getResources().getString(R.string.pref_nickname); keyPassword = context.getResources().getString(R.string.pref_password); keyShareWith = context.getResources().getString(R.string.pref_share_with); shareWithDefault = ShareWith.valueOf( context.getResources().getString(R.string.share_with_entryvalue_default)); keySessionToken = context.getResources().getString(R.string.pref_session_token); keyLastRunVersion = context.getResources().getString(R.string.pref_last_run_version); } /** Returns a given string preference, or a default value if not set. */ private String getStringPreference(String key, String defaultValue) { return sharedPreferences.getString(key, defaultValue); } /** Sets a given string preference. */ private void setStringPreference(String key, String value) { Editor editor = sharedPreferences.edit(); editor.putString(key, value); editor.commit(); } @Override public String getNickname() { return getStringPreference(keyNickname, ""); } @Override public void setNickname(String nickname) { setStringPreference(keyNickname, nickname); } @Override public String getPassword() { return getStringPreference(keyPassword, ""); } @Override public void setPassword(String password) { setStringPreference(keyPassword, password); } @Override public ShareWith getShareWith() { return ShareWith.tryValueOf(getStringPreference(keyShareWith, ""), shareWithDefault); } @Override public void setShareWith(ShareWith shareWith) { setStringPreference(keyShareWith, shareWith.name()); } @Override public String getLastRunVersion() { return getStringPreference(keyLastRunVersion, ""); } @Override public void setLastRunVersion(String version) { setStringPreference(keyLastRunVersion, version); } @Override public String getSessionToken() { return getStringPreference(keySessionToken, null); } @Override public void setSessionToken(String sessionToken) { setStringPreference(keySessionToken, sessionToken); } /** Clears all preferences. */ public void clear() { sharedPreferences.edit().clear().commit(); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; /** * An exception representing a failure to communicate with the BMS server due to * an API error. */ @SuppressWarnings("serial") public class BmsApiException extends BmsException { private final ErrorCode errorCode; enum ErrorCode { /** Success. */ SUCCESS(-0), /** Invalid developer key. */ INVALID_KEY(-1), /** Invalid username or password. */ INVALID_USERNAME(-2), /** Invalid session. The session is unknown or has expired. */ INVALID_SESSION(-3), /** Invalid EAN/UPC. */ INVALID_EAN(-4), /** Missing required argument. */ MISSING_ARGUMENT(-5); int number; ErrorCode(int number) { this.number = number; } public int getNumber() { return number; } /** * Returns the ErrorCode with the given error number, or null if no such * ErrorCode exists. */ public static ErrorCode valueOf(int number) { for (ErrorCode e : ErrorCode.values()) { if (e.number == number) { return e; } } return null; } } /** * Constructs a new BmsApiException with the given API error code and error * message. */ public BmsApiException(ErrorCode errorCode, String reason) { super(reason); this.errorCode = errorCode; } /** * Constructs a new BmsApiException with the given API error code and error * message. */ public BmsApiException(ErrorCode errorCode, String reason, Throwable cause) { super(reason, cause); this.errorCode = errorCode; } /** Returns the BMS API error code. */ public ErrorCode getErrorCode() { return errorCode; } @Override public String toString() { return super.toString() + " errorCode: " + errorCode; } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; /** * The root class of exceptions generated when talking to a server. */ @SuppressWarnings("serial") public abstract class BmsException extends RuntimeException { public BmsException(String reason) { super(reason); } public BmsException(String reason, Throwable cause) { super(reason, cause); } /** Returns whether the operation can be retried. */ public boolean canRetry() { return false; } @Override public String toString() { return super.toString() + " canRetry: " + canRetry(); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Binder; import android.os.IBinder; import android.util.Log; /** * Network handling service for the various activities. * * @see NetworkThread */ public class NetworkService extends Service { private static final String TAG = "BMS.NetworkService"; private Preferences preferences; private BmsClient bmsClient; private ScanRegistry scanRegistry; private NetworkThread thread; private final IBinder binder = new LocalBinder(); /** * A class to implement the Binder interface. * Because we're running in the same process as our clients, we can ignore * IDL and everything related to IPC. */ private class LocalBinder extends Binder { // Just provide a single accessor method that can return the service // instance. public NetworkService getService() { return NetworkService.this; } } /** * Class used to bind to a NetworkService instance. * * This is an implementation of ServiceConnection that uses a local binder * to retrieve the original instance of the NetworkService class, then makes * it available via a getter. * * @see NetworkService#bind(Context, NetworkServiceConnection, Runnable) */ public static class NetworkServiceConnection implements ServiceConnection { private Runnable runnable = null; private NetworkService networkService = null; private void setRunnable(Runnable runnable) { if (this.runnable != null || networkService != null) { throw new IllegalStateException( "This NetworkServiceConnection has already been used to bind to a service."); } this.runnable = runnable; } @Override public void onServiceConnected(ComponentName name, IBinder service) { Log.d(TAG, "Service connected"); // Just cast directly and access the service itself - it's in-process. networkService = ((LocalBinder) service).getService(); runnable.run(); } @Override public void onServiceDisconnected(ComponentName name) { Log.d(TAG, "Service disconnected"); // It's crashed or (perhaps?) the client disconnected. // The former should be impossible, since it's in-process. networkService = null; } /** * Returns the network service instance. Null until the runnable * passed to {@link NetworkService#bind(Context, NetworkServiceConnection, Runnable)} * has been called, and null after the service has been disconnected. */ public NetworkService getService() { return networkService; } } @Override public IBinder onBind(Intent intent) { return binder; } /** * Convenience method to bind a context to an instance of this service, * starting it if necessary. * * The Runnable passed here will be called once the service has started, at * which point {@link NetworkServiceConnection#getService()} will return a * non-null value. * * Callers must unbind by passing the {@code connection} to * {@link Context#unbindService(ServiceConnection)}. * * @param context the activity's context * @param connection the {@link NetworkServiceConnection} for this activity * @param runnable the Runnable to call once the service has started */ public static void bind(Context context, NetworkServiceConnection connection, Runnable runnable) { // The service will be started asynchronously in the current thread - so // we can't block here until it's started, because that would block the // startup we're waiting for! (I suspect that it's started in response to a // message arriving at the UI thread's message queue.) Instead, we call a // Runnable once bound. connection.setRunnable(runnable); if (!context.bindService(new Intent(context, NetworkService.class), connection, BIND_AUTO_CREATE)) { Log.e(TAG, "Couldn't start local service?"); throw new AssertionError("fail."); } } @Override public void onCreate() { super.onCreate(); // Create and initialise the BeepMyStuff API and the ScanRegistry. Injector injector = Injector.getInjector(getApplication()); preferences = injector.getPreferences(); String nickname = preferences.getNickname(); String password = preferences.getPassword(); bmsClient = new BmsClient(injector.getBmsLowLevelClient(), injector.getSessionStorage()); if (!nickname.equals("") && !password.equals("")) { bmsClient.setCredentials(nickname, password); } scanRegistry = new ScanRegistry(getApplicationContext()); Log.d(TAG, "Starting background thread"); BmsHttpClient httpClient = injector.getBmsHttpClient(); thread = new NetworkThread(getApplicationContext(), httpClient, bmsClient, scanRegistry); thread.start(); } @Override public void onDestroy() { thread.shutdown(); super.onDestroy(); } // Methods called by our clients. /** Returns the scan registry in use. */ public ScanRegistry getScanRegistry() { return scanRegistry; } /** Provides the API client with new credentials. */ public void setCredentials(String nickname, String password) { bmsClient.setCredentials(nickname, password); } /** Wakes up the workqueue to look for more work. */ public void wakeUp() { thread.wakeUp(); } /** * Log a user in to to Beep My Stuff to get a valid session token. * * Note that this is a synchronous activity - it is not performed on the * network thread. * * @param nickname the nickname of the user who wants to login * @param password the API password for the user * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public void login(String nickname, String password) throws BmsApiException, BmsTransportException { bmsClient.login(nickname, password); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.util.Log; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpUriRequest; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; /** * An implementation of {@link BmsHttpClient} as a thin wrapper around * {@link HttpClient}. */ public class DefaultBmsHttpClient implements BmsHttpClient { private static final String TAG = "BMS.BmsHttpClient"; /** The default maximum allowed response size (10MB). */ public static final long DEFAULT_MAX_RESPONSE_SIZE_BYTES = 10 * 1024 * 1024; private final HttpClient httpClient; /** The maximum allowed response size. */ private long maxResponseSizeBytes = DEFAULT_MAX_RESPONSE_SIZE_BYTES; public DefaultBmsHttpClient(HttpClient httpClient) { this.httpClient = httpClient; } /** * Sets the maximum allowed response size, by default * {@link #DEFAULT_MAX_RESPONSE_SIZE_BYTES}. */ public void setMaxResponseSize(long maxResponseSizeBytes) { this.maxResponseSizeBytes = maxResponseSizeBytes; } /** * Returns the maximum allowed response size, by default * {@link #DEFAULT_MAX_RESPONSE_SIZE_BYTES}. */ public long getMaxResponseSize() { return maxResponseSizeBytes; } @Override public byte[] getResponseBody(HttpUriRequest request) throws BmsTransportException { Log.d(TAG, String.format("Req: %s %s", request.getMethod(), request.getURI())); HttpResponse response; try { response = httpClient.execute(request); } catch (ClientProtocolException e) { throw new BmsClientException(e.getMessage(), e); } catch (IOException e) { throw new BmsTransportException(e.getMessage(), e); } Log.d(TAG, String.format("Res: %s", response.getStatusLine())); if (response.getStatusLine().getStatusCode() != 200) { request.abort(); // free the connection. // Fatal if the server said it was our fault (4xx), a transport error if // it was the server's fault (5xx), and a client error otherwise. switch (response.getStatusLine().getStatusCode() / 100) { case 4: throw new BmsClientException("HTTP request returned " + response.getStatusLine()); case 5: throw new BmsTransportException("HTTP request returned " + response.getStatusLine()); default: throw new BmsClientException("Unexpected HTTP response " + response.getStatusLine()); } } HttpEntity entity = response.getEntity(); if (entity == null) { throw new BmsClientException("Received 200 OK with no content?!"); } if (entity.getContentLength() > maxResponseSizeBytes) { request.abort(); throw new BmsClientException( String.format("Response is %s bytes, larger than allowed (%s bytes)", entity.getContentLength(), maxResponseSizeBytes)); } InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); long total = 0; try { in = entity.getContent(); byte[] buffer = new byte[4096]; while (true) { int bytesRead = in.read(buffer); if (bytesRead == -1) { break; } total += bytesRead; if (total > maxResponseSizeBytes) { request.abort(); throw new BmsClientException( String.format("Read %s response bytes, larger than allowed (%s bytes)", total, maxResponseSizeBytes)); } out.write(buffer, 0, bytesRead); } } catch (IOException e) { throw new BmsTransportException("Unable to read response from server", e); } finally { if (in != null) { try { // Triggers connection release for the HttpClient. in.close(); } catch (IOException e) { // Really don't care. } } } return out.toByteArray(); } @Override public String getResponseBodyAsString(HttpUriRequest request) throws BmsTransportException { byte[] response = getResponseBody(request); // TODO: work out how to get the correct charset from the response. try { return new String(response, "UTF-8"); } catch (UnsupportedEncodingException impossible) { throw new AssertionError("UTF-8 must be supported. " + impossible.toString()); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.text.TextUtils; import android.util.Log; import org.apache.http.client.methods.HttpGet; /** * Background processing for BeepMyStuff - item adding and image fetching. * * All work is driven off the ScanRegistry, and updates are posted there. * * TODO: fix what's going on with InterruptedException here. */ public class NetworkThread extends Thread { private static final String TAG = "BMS.NetworkThread"; private static final long INACTIVE_SLEEP_TIME_MS = 10000; private final BmsClient bmsClient; private final ScanRegistry scanRegistry; private final Context context; private final BmsHttpClient httpClient; /** An object to wait upon when waiting for events. */ private final Object waiter = new Object(); /** Whether the thread should shut down. Mutated under the waiter lock. */ private boolean stopping; /** * Constructs a background network thread. * The thread doesn't start until start() is called. * @param context global application context * @param httpClient BMS HTTP client * @param bmsClient BMS high-level API client * @param scanRegistry registry to read from and post results to */ public NetworkThread(Context context, BmsHttpClient httpClient, BmsClient bmsClient, ScanRegistry scanRegistry) { this.context = context; this.httpClient = httpClient; this.bmsClient = bmsClient; this.scanRegistry = scanRegistry; } /** * Wakes up the network thread, causing it to start processing if it had * previously started sleeping due to having no work. */ public void wakeUp() { synchronized (waiter) { waiter.notify(); } } /** * Shuts down the network thread cleanly. Blocks until the thread has stopped. */ public void shutdown() { Log.d(TAG, "Stopping background thread"); synchronized (waiter) { stopping = true; wakeUp(); } try { join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d(TAG, "Background thread stopped"); } /** * Returns whether the thread is being asked to stop. */ private boolean isStopping() { synchronized (waiter) { return stopping; } } /** * Waits for a INACTIVE_SLEEP_TIME_MS, unless interrupted by a wake up. */ private void interruptibleWait() { try { Log.v(TAG, "Waiting for something to do"); synchronized (waiter) { waiter.wait(INACTIVE_SLEEP_TIME_MS); } } catch (InterruptedException e) { // do nothing } } @Override public void run() { stopping = false; // TODO: maybe rename to BmsSessionHandler? while (!isStopping()) { waitForNetwork(); if (isStopping()) { break; } ScanRegistry.Item item = scanRegistry.getNextItemToAdd(); if (item != null) { addItem(item); continue; } item = scanRegistry.getNextItemToGetImage(); if (item != null) { fetchImage(item); continue; } interruptibleWait(); } } /** * Adds an item to BeepMyStuff. * @param item item to add */ private void addItem(ScanRegistry.Item item) { Log.i(TAG, "Adding EAN " + item.getEan() + " share: " + item.shareWith()); BmsClient.AddEanResult result; try { result = bmsClient.addEan(item.getEan(), item.shareWith()); } catch (BmsException e) { Log.i(TAG, "Add failed (" + (!e.canRetry() ? "fatal" : "non-fatal") + "): " + e.getMessage()); item.addFailed(e.getMessage(), !e.canRetry()); return; } if (TextUtils.isEmpty(result.getErrorMessage())) { Log.v(TAG, "Succeeded '" + result.getMessage() + "' - '" + result.getTitle() + "' - '" + result.getImageUrl() + "'"); item.addSucceeded(result.getMessage(), result.getTitle(), result.getImageUrl()); } else { Log.i(TAG, "Add failed (fatal): '" + result.getErrorMessage()); item.addFailed(result.getErrorMessage(), true); } } /** * Fetches the image data for an Item. * @param item item to fetch data for */ private void fetchImage(ScanRegistry.Item item) { String url = item.getImageUrl(); Log.i(TAG, "Fetching image: '" + url); byte[] data; try { data = httpClient.getResponseBody(new HttpGet(url)); } catch(BmsTransportException e) { Log.v(TAG, "Image fetch failed " + e.toString()); item.imageFetchFailed(!e.canRetry()); return; } item.imageFetchSucceeded(data); Log.i(TAG, "Image fetch succeeded"); } /** * Waits until the network is up and available. */ private void waitForNetwork() { ConnectivityManager conMgr = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); while (!isStopping()) { NetworkInfo activeInfo = conMgr.getActiveNetworkInfo(); if (activeInfo != null && activeInfo.isConnected()) { Log.v(TAG, "Network is up!"); return; } // TODO: better than this! cf ConnectivityManager.CONNECTIVITY_ACTION interruptibleWait(); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.os.AsyncTask; import android.os.Bundle; import android.text.method.LinkMovementMethod; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.beepmystuff.NetworkService.NetworkServiceConnection; /** * An activity to get the user's credentials and to let them test them * interactively. */ public class LoginActivity extends Activity { private NetworkServiceConnection networkServiceConnection = new NetworkServiceConnection(); private NetworkService networkService; private TextView nickname; private TextView password; private Preferences preferences; /** * Called when the activity is first created. * */ @Override public void onCreate(Bundle savedInstanceState) { setTheme(R.style.BeepMyStuffDialog); super.onCreate(savedInstanceState); setContentView(R.layout.login); // Establish a connection with our service (starting it if necessary). NetworkService.bind(this, networkServiceConnection, new Runnable() { @Override public void run() { networkService = networkServiceConnection.getService(); createAfterServiceAvailable(); } }); // Enable the web link in the explanatory text. // See http://code.google.com/p/android/issues/detail?id=2219 TextView explanatoryText = (TextView) findViewById(R.id.explanatory_text); explanatoryText.setMovementMethod(LinkMovementMethod.getInstance()); preferences = Injector.getInjector(getApplication()).getPreferences(); nickname = (TextView) findViewById(R.id.nickname); nickname.setText(preferences.getNickname()); password = (TextView) findViewById(R.id.password); password.setText(preferences.getPassword()); } /** Continue creation after the network service has been started. */ private void createAfterServiceAvailable() { Button loginButton = (Button) findViewById(R.id.login); loginButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { new LoginTask().execute(); } }); } /** * Called before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); unbindService(networkServiceConnection); } /** * Asynchronous task to check a username and password. */ private class LoginTask extends AsyncTask<Object, Integer, String> { private ProgressDialog loginProgress; /** * Called on the UI thread before the background thread starts. */ @Override protected void onPreExecute() { loginProgress = ProgressDialog.show(LoginActivity.this, getString(R.string.logging_in_title), getString(R.string.logging_in_message), true, true, new OnCancelListener() { @Override public void onCancel(DialogInterface ignored) { cancel(true); } }); } /** * Called on the background thread. We don't use the parameters passed to * us, and we return an error string, or null if the login was successful. */ @Override protected String doInBackground(Object... ignored) { try { networkService.login(getNickname(), getPassword()); } catch (BmsException bms) { return bms.getMessage(); } // We succeeded; return a null. return null; } /** * Called in the UI thread with the result of doInBackground. */ @Override protected void onPostExecute(String error) { loginProgress.dismiss(); if (error != null) { new AlertDialog.Builder(LoginActivity.this) .setMessage(error) .setTitle(R.string.login_failed_title) .setPositiveButton(R.string.login_failed_button_title, null) .show(); } else { preferences.setNickname(getNickname()); preferences.setPassword(getPassword()); Toast.makeText(LoginActivity.this, R.string.logged_in_ok, Toast.LENGTH_SHORT) .show(); finish(); } } } /** Get the nickname set in the ui. */ private String getNickname() { return nickname.getText().toString(); } /** Get the password set in the ui. */ private String getPassword() { return password.getText().toString(); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; /** * An exception representing a failure to communicate with a server due to * non-transient errors (e.g. a 404 HTTP error, or an invalid or unexpected * response). */ @SuppressWarnings("serial") public class BmsClientException extends BmsException { public BmsClientException(String reason) { super(reason); } public BmsClientException(String reason, Throwable cause) { super(reason, cause); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import com.google.beepmystuff.BmsClient.ShareWith; /** * Interface to stored user preferences. */ public interface Preferences { /** Returns the nickname, or an empty string if none is set. */ String getNickname(); void setNickname(String nickname); /** Returns the password, or an empty string if none is set. */ String getPassword(); void setPassword(String password); /** Returns the current share mode, or a default if none is set. */ ShareWith getShareWith(); void setShareWith(ShareWith shareWith); /** Returns the last run version of the application (empty by default) */ String getLastRunVersion(); void setLastRunVersion(String version); }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.Activity; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import com.google.beepmystuff.NetworkService.NetworkServiceConnection; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; /** * Main activity for BeepMyStuff for Android. * * Provides a simple home screen. */ public class HomeScreenActivity extends Activity { private static final String TAG = "BMS.HomeScreenActivity"; private NetworkServiceConnection networkServiceConnection = new NetworkServiceConnection(); private NetworkService networkService; private Preferences preferences; private BmsClient.SessionStorage bmsSessionStorage; private boolean showDebuggingMenu = false; /** * Whether a successful scan should initiate another scan. * Set before each scan. */ private boolean continuousMode = false; /** * Notified to indicate that the network service has been created and the * activity has finished initialising. For tests. * * @see #waitUntilServiceFullyBound() */ private Object serviceFullyBound = new Object(); /** * Called when the activity is first created. * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.home); Injector injector = Injector.getInjector(getApplication()); preferences = injector.getPreferences(); bmsSessionStorage = injector.getSessionStorage(); // TODO: a) shouldn't we delegate to LoginActivity here if needed? // b) Make sure we never attempt to login using a blank u/p. // c) make LoginActivity _replace_ this activity (and remove the menu option?) // d) write a test to test backing out of LoginActivity after first-run?? // e) test with Wireshark to see what our HTTP traffic looks like? // Establish a connection with our service (starting it if necessary). NetworkService.bind(this, networkServiceConnection, new Runnable() { @Override public void run() { Log.d(TAG, "Network service has bound"); networkService = networkServiceConnection.getService(); createAfterServiceAvailable(); synchronized (serviceFullyBound) { serviceFullyBound.notify(); } } }); } /** Continue creation after the network service has been started. */ private void createAfterServiceAvailable() { // Connect the scan button's click event to the item scanner. findViewById(R.id.beep).setOnClickListener(new OnClickListener() { public void onClick(View view) { scanItem(false); } }); findViewById(R.id.beep_lots).setOnClickListener(new OnClickListener() { public void onClick(View view) { scanItem(true); } }); // Wire up the recently scanned button. findViewById(R.id.recently_scanned).setOnClickListener(new OnClickListener() { public void onClick(View view) { startActivity(new Intent(HomeScreenActivity.this, RecentlyScannedActivity.class)); } }); } /** * Waits until the network service has been started and bound. * Called by tests to ensure that activity initialisation is complete. */ public void waitUntilServiceFullyBound() throws InterruptedException { synchronized (serviceFullyBound) { while (networkService == null) { serviceFullyBound.wait(); } } } /** * Called just before the activity starts interacting with the user. * This may be due to the settings dialog having been dismissed; so re-read * the network credentials from the preferences, and pass them to the network * service. */ @Override public void onResume() { super.onResume(); // The network service may not have started yet, in which case we can't // provide it with new credentials (it reads them from preferences on // creation anyway). if (networkService != null) { networkService.setCredentials(preferences.getNickname(), preferences.getPassword()); } checkUpgrade(); checkCredentials(); } /** * Checks to see if the credentials we have are valid, and if not, goes to * the login activity to get them. */ private void checkCredentials() { if (TextUtils.isEmpty(preferences.getNickname()) || TextUtils.isEmpty(preferences.getPassword()) || TextUtils.isEmpty(bmsSessionStorage.getSessionToken())) { // With no valid nickname, password and session token, go to the login // activity. startActivity(new Intent(this, LoginActivity.class)); } } /** * Checks to see if we've been installed for the first time or have been * upgraded from a prior version. In future info screens explaining what's * new can be displayed here. */ private void checkUpgrade() { @SuppressWarnings("unused") String lastVersion = preferences.getLastRunVersion(); PackageInfo pi; try { pi = getPackageManager().getPackageInfo(getPackageName(), 0); } catch (NameNotFoundException e) { throw new AssertionError("Could not get our own package info: " + e); } preferences.setLastRunVersion(Integer.toString(pi.versionCode)); // Any required upgrade notification performed here. } /** * Called before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); // This check isn't foolproof: if the service has been recently unbound, // we may not have received the notification yet, but this call will still // fail. Luckily, we're the only people who unbind the service, so we // should be okay. if (networkServiceConnection.getService() != null) { unbindService(networkServiceConnection); } } /** * Create the activity's options menu. */ @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); menu.findItem(R.id.menu_login) .setIntent(new Intent(this, LoginActivity.class)); menu.findItem(R.id.menu_settings) .setIntent(new Intent(this, SettingsActivity.class)); menu.findItem(R.id.menu_manual) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { startActivityForResult(new Intent(HomeScreenActivity.this, ManualEntryActivity.class), IntentIntegrator.REQUEST_CODE); return true; } }); menu.findItem(R.id.menu_debug_clear_prefs) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { debugClearPrefs(); return true; } }); menu.findItem(R.id.menu_debug_fake_scan) .setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { debugFakeScan(); return true; } }); return true; } /** * Start a scan by asking zxing to scan an item. It will return to us via * onActivityResult below. * @see #onActivityResult(int, int, Intent) */ private void scanItem(boolean continuousMode) { // TODO: prior to moving to zxing's own IntentIntegrator, I used to set // zxing to only look for products. Would be nice to update // IntentIntegrator to give the same functionality. this.continuousMode = continuousMode; IntentIntegrator.initiateScan(this); } /** * Called when an external activity completes, returning a value to us. * This is used after we've shelled out to zxing to ask it to scan a barcode * for us. */ @Override public void onActivityResult(int requestCode, int resultCode, Intent intent) { IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent); if (result != null && !TextUtils.isEmpty(result.getContents())) { String contents = result.getContents(); String format = result.getFormatName(); Log.i(TAG, "Scanned " + format + " barcode: " + contents); networkService.getScanRegistry().addEan(contents, preferences.getShareWith()); networkService.wakeUp(); if (continuousMode) { Log.d(TAG, "Multiple mode - rescanning"); scanItem(true); } } } /** Optionally makes debugging menu visible. */ @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.setGroupVisible(R.id.menu_debug_group, showDebuggingMenu); return super.onPrepareOptionsMenu(menu); } /** * Debug menu option: clears preferences and shuts down. * Does nothing if we're running with an injected preferences object. */ private void debugClearPrefs() { if (preferences instanceof SharedPreferences) { ((SharedPreferences) preferences).clear(); // This doesn't exit the process: it seems to be waiting for something. // TODO: investigate whether we're leaking something. finish(); } } /** * Debug menu option: Fakes a scan, so that it's possible to test * manually without installing Barcode Scanner (which is a pain if there's * also no Market installed). */ private void debugFakeScan() { onActivityResult(IntentIntegrator.REQUEST_CODE, RESULT_OK, new Intent().putExtra("SCAN_RESULT", "9780201038095") .putExtra("SCAN_RESULT_FORMAT", "EAN_13")); } /** Toggle the debugging menu when the secret debugging key is pressed. */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_1) { showDebuggingMenu = !showDebuggingMenu; return true; } return super.onKeyDown(keyCode, event); } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.ListActivity; import android.os.Bundle; import android.util.Log; import com.google.beepmystuff.NetworkService.NetworkServiceConnection; /** * Shows detailed information about a single item in the scan registry. */ public class ItemDetailsActivity extends ListActivity { private static final String TAG = "BMS.ItemDetailsActivity"; private NetworkServiceConnection networkServiceConnection = new NetworkServiceConnection(); private NetworkService networkService; /** * Called when the activity is first created. * */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.item_details); // Establish a connection with our service (starting it if necessary). NetworkService.bind(this, networkServiceConnection, new Runnable() { @Override public void run() { networkService = networkServiceConnection.getService(); createAfterServiceAvailable(); } }); } /** Continue creation after the network service has been started. */ private void createAfterServiceAvailable() { // Create the list view adapter which takes information from the // ScanRegistry and binds it to our view. ScanRegistry scanRegistry = networkService.getScanRegistry(); // Add a listener to the scan registry, listening for change events in the // data, and causing the list view to refresh. Note that the events come in // from a separate thread but the adapter needs to be queried in the UI // thread. scanRegistry.addListener(new ScanRegistry.Listener() { public void notifyChanged() { runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "Data changed, requerying"); //adapter.getCursor().requery(); } }); } }); } /** * Called before the activity is destroyed. */ @Override public void onDestroy() { super.onDestroy(); Log.d(TAG, "onDestroy"); // This check isn't foolproof: if the service has been recently unbound, // we may not have received the notification yet, but this call will still // fail. Luckily, we're the only people who unbind the service, so we // should be okay. if (networkServiceConnection.getService() != null) { unbindService(networkServiceConnection); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.app.Application; import com.google.beepmystuff.BmsClient.SessionStorage; import org.apache.http.impl.client.DefaultHttpClient; /** A static factory for creating dependencies. */ public abstract class Injector { private static Injector instance = null; private static final Injector TEST_DEATH_SENTINEL = new TestDeathInjector(); /** * Returns the singleton instance of Injector that was configured via * {@link #configureForTest(Injector)}, or a default injector if none has * been configured. * * @throws IllegalStateException if no injector has been configured. */ public static synchronized Injector getInjector(Application application) { if (instance == null) { setInjector(new DefaultInjector(application)); } return instance; } /** * Sets the singleton injector to return from * {{@link #getInjector(Application)}. * * @throws IllegalStateException if an injector has already been configured. */ private static void setInjector(Injector injector) { if (instance != null) { throw new IllegalStateException("An injector has already been configured"); } instance = injector; } /** * Configures this class to return a provided injector. * * @throws IllegalStateException if an injector has already been configured. */ public static synchronized void configureForTest(Injector injector) { // We want to catch the case where a testcase hasn't called resetForTest() // in its tearDown() method, so we only clear the current instance if it // was a TestDeathInjector sentinel. If not, setInjector() will throw an // ISE. if (instance == TEST_DEATH_SENTINEL) { instance = null; } setInjector(injector); } /** * Resets the provided injector so that another test can call * {@link #configureForTest(Injector)}. * * @throws IllegalStateException if no injector has been configured. */ public static synchronized void resetForTest() { if (instance == null) { throw new IllegalStateException("No injector has been configured"); } instance = TEST_DEATH_SENTINEL; } /** * Returns the default injector that was created by calling * {@link #getInjector(Application)}, allowing calling code to inject some * dependencies (but retain the default creation for others). * * @throws IllegalStateException if the default injector is not in use. */ public DefaultInjector asDefault() { if (this instanceof DefaultInjector) { return (DefaultInjector) this; } throw new IllegalStateException("Default injector is not in use"); } public abstract Preferences getPreferences(); public abstract SessionStorage getSessionStorage(); public abstract BmsHttpClient getBmsHttpClient(); public abstract BmsLowLevelClient getBmsLowLevelClient(); /** * An implementation of {@link Injector} that creates dependencies on-demand * using a provided Application context. * * Individual dependencies can be replaced using methods provided on this * class. */ public static class DefaultInjector extends Injector { // This apikey is one allocated to me (Matt Godbolt) for this client // only. Please do not use it for another project, instead email // beepmaster@beepmystuff.com for your own key! private static final String BMSAPIKEY = "hRYBzzQ9LUqNMMHB3A8BUfeg0uuGRgEY"; private final Application application; private BmsHttpClient bmsHttpClient; private BmsLowLevelClient bmsLowLevelClient; private Preferences preferences; private SessionStorage sessionStorage; private DefaultInjector(Application application) { this.application = application; } @Override public synchronized BmsHttpClient getBmsHttpClient() { if (bmsHttpClient == null) { bmsHttpClient = new DefaultBmsHttpClient(new DefaultHttpClient()); } return bmsHttpClient; } public synchronized void setBmsHttpClient(BmsHttpClient bmsHttpClient) { this.bmsHttpClient = bmsHttpClient; } @Override public synchronized BmsLowLevelClient getBmsLowLevelClient() { if (bmsLowLevelClient == null) { bmsLowLevelClient = new DefaultBmsLowLevelClient(getBmsHttpClient(), BMSAPIKEY); } return bmsLowLevelClient; } public synchronized void setBmsLowLevelClient(BmsLowLevelClient bmsLowLevelClient) { this.bmsLowLevelClient = bmsLowLevelClient; } @Override public synchronized Preferences getPreferences() { if (preferences == null) { createSharedPreferences(); } return preferences; } public synchronized void setPreferences(Preferences preferences) { this.preferences = preferences; } @Override public synchronized SessionStorage getSessionStorage() { if (sessionStorage == null) { createSharedPreferences(); } return sessionStorage; } public synchronized void setSessionStorage(SessionStorage sessionStorage) { this.sessionStorage = sessionStorage; } private void createSharedPreferences() { SharedPreferences sharedPreferences = new SharedPreferences(application); if (preferences == null) { preferences = sharedPreferences; } if (sessionStorage == null) { sessionStorage = sharedPreferences; } } } /** * An implementation of {@link Injector} that fails all calls. * * This is used as a sentinel during tests to inhibit the creation of a * default injector. */ private static class TestDeathInjector extends Injector { @Override public BmsHttpClient getBmsHttpClient() { throw new UnsupportedOperationException(); } @Override public BmsLowLevelClient getBmsLowLevelClient() { throw new UnsupportedOperationException(); } @Override public Preferences getPreferences() { throw new UnsupportedOperationException(); } @Override public SessionStorage getSessionStorage() { throw new UnsupportedOperationException(); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import android.net.Uri; import com.google.beepmystuff.BmsClient.ShareWith; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import java.io.IOException; import java.io.StringReader; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.Map; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; /** * Implements the low-level Beep My Stuff HTTP API, documented at * http://www.beepmystuff.com/static/apidocs/index.html. */ public class DefaultBmsLowLevelClient implements BmsLowLevelClient { private static final String HOST_NAME = "www.beepmystuff.com"; private final BmsRawHttpApiClient client; private final String developerKey; /** * Constructs a class to talk to the BeepMyStuff servers, with the supplied * HTTP Client and developer key. */ public DefaultBmsLowLevelClient(BmsHttpClient httpClient, String developerKey) { this.client = new BmsRawHttpApiClient(httpClient); this.developerKey = developerKey; } /** * Internal class to parse the results of a login RPC. */ private static class LoginResultImpl implements BmsClient.LoginResult { private final String sessionToken; public LoginResultImpl(Document document) { sessionToken = BmsRawHttpApiClient.getTextContent(document, "login", "session"); } @Override public String getSessionToken() { return sessionToken; } } @Override public BmsClient.LoginResult login(String nickname, String password) throws BmsTransportException, BmsApiException { return new LoginResultImpl(client.login(developerKey, nickname, password)); } /** * Internal class to parse the results of an addean RPC. */ private static class AddEanResultImpl implements BmsClient.AddEanResult { public final String message; public final String errorMessage; public final String imageUrl; public final String title; public AddEanResultImpl(Document document) { message = BmsRawHttpApiClient.getTextContent(document, "addean", "msg"); errorMessage = BmsRawHttpApiClient.getTextContent(document, "addean", "error_msg"); imageUrl = BmsRawHttpApiClient.getTextContent(document, "addean", "imgurl"); title = BmsRawHttpApiClient.getTextContent(document, "addean", "title"); } @Override public String getErrorMessage() { return errorMessage; } @Override public String getMessage() { return message; } @Override public String getImageUrl() { return imageUrl; } @Override public String getTitle() { return title; } } @Override public BmsClient.AddEanResult addEan(String session, String ean, ShareWith shareWith) throws BmsTransportException, BmsApiException { return new AddEanResultImpl(client.addEan(developerKey, session, ean, shareWith == ShareWith.PUBLIC, shareWith != ShareWith.PRIVATE)); } @Override public String getAvatarPath(String session) throws BmsTransportException, BmsApiException { Document document = client.getAvatarPath(developerKey, session); return BmsRawHttpApiClient.getTextContent(document, "avatar", "path"); } /** * The raw HTTP implementation of the BMS API. * * Makes requests and returns {@link Document}s containing the response, or * throws exceptions if the request could not be performed for any reason. */ // VisibleForTesting static class BmsRawHttpApiClient { private final DocumentBuilder documentBuilder; private final BmsHttpClient httpClient; BmsRawHttpApiClient(BmsHttpClient httpClient) { this.httpClient = httpClient; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setIgnoringComments(true); try { documentBuilder = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new AssertionError("Couldn't construct a default DocumentBuilder"); } } /** * Constructs a BeepMyStuff RPC request from the given verb and parameters. * * @param verb action verb, e.g. "login" or "addean". * @param repeatable whether the request should be repeated on error (a GET) * or not (a POST). * @param params a Map of parameters to supply. * @return the HTTP request to use. */ private HttpUriRequest createRequest(String verb, boolean repeatable, Map<String, String> params) { Uri.Builder builder = new Uri.Builder() .scheme("http") .authority(HOST_NAME) .path("api/" + verb); for (Map.Entry<String, String> param : params.entrySet()) { builder.appendQueryParameter(param.getKey(), param.getValue()); } return (repeatable) ? new HttpGet(builder.toString()) : new HttpPost(builder.toString()); } /** * Extract the text content from an element in a Document given a path to * walk. * * e.g. given a valid XHTML document, passing in a path of "head", "title" * would return the document's title, or throw an exception if the document * had no title. If the document had an explicit blank title, would return * the empty string. * * Taking the same example document, a path of "body", "h1" would return the * value of an H1 element, or throw if the document had none, or more than * one. A path of "body" would also throw , since there are other elements * beneath BODY (i.e. it's a mixed-content node). * * @param document the document. * @param path the element names to walk in order, excluding the root * element. * @return the element's text content, or a blank string if the element is * present but empty (or has no content). Never returns null. * @throws BmsTransportException if the element is not present, is present * more than once, or has mixed content. */ // VisibleForTesting static String getTextContent(Document document, String... path) throws BmsTransportException { Element element = document.getDocumentElement(); for (String elementName : path) { Element childElement = null; NodeList childNodes = element.getChildNodes(); for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE && childNode.getNodeName().equals(elementName)) { if (childElement != null) { throw new BmsClientException(String.format( "Document has more than one '%s' child in path %s", elementName, Arrays.toString(path))); } childElement = (Element) childNode; } } if (childElement == null) { throw new BmsClientException(String.format( "Document has no '%s' child in path %s", elementName, Arrays.toString(path))); } element = childElement; } // We have a target element now. Check that it's not mixed content, // and return the child #text node, or nodes. (While the XML parser // we're using ignores comments, it won't combine #text (or CDATA) nodes // separated by e.g. a comment.) NodeList childNodes = element.getChildNodes(); if (childNodes.getLength() == 1) { // Optimise for the common case. Node childNode = childNodes.item(0); if (childNode.getNodeType() == Node.TEXT_NODE) { return childNode.getNodeValue(); } // Otherwise, we'll handle using the more general code below. } StringBuilder sb = new StringBuilder(); for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); switch (childNode.getNodeType()) { case Node.TEXT_NODE: case Node.CDATA_SECTION_NODE: sb.append(childNode.getNodeValue()); break; default: // This unfortunately also catches character entity references, // which the Android parser seems determined not to replace :-/. throw new BmsClientException( String.format("Mixed-content element (type %s) at path %s", childNode.getNodeType(), Arrays.toString(path))); } } return sb.toString(); } /** * Internal function to make an RPC request. Note that the request can be * made successfully (i.e. this method returns without throwing) even though * the request itself failed (i.e. an application-level error was set in the * response). * * @param verb the action to perform on the BeepMyStuff server (e.g. "login") * @param repeatable whether the action is idempotent and so can be repeated * in the case of a transient (i.e. I/O) error. * @param params a map of parameters to supply to the server * @return the XML document returned by the server. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ // VisibleForTesting Document makeRpc(String verb, boolean repeatable, Map<String, String> params) throws BmsTransportException, BmsApiException { HttpUriRequest request = createRequest(verb, repeatable, params); Document document = parse(httpClient.getResponseBodyAsString(request)); // Extract the errorcode and message. String errorCodeString = getTextContent(document, "error", "errorcode"); BmsApiException.ErrorCode errorCode; try { errorCode = BmsApiException.ErrorCode.valueOf(Integer.parseInt(errorCodeString)); } catch (NumberFormatException e) { throw new BmsClientException( String.format("Error parsing result: errorcode '%s' unparsable", errorCodeString)); } if (errorCode == null) { throw new BmsClientException( String.format("Error parsing result: errorcode %s unknown", errorCodeString)); } if (errorCode != BmsApiException.ErrorCode.SUCCESS) { throw new BmsApiException(errorCode, getTextContent(document, "error", "string")); } return document; } /** * Parse an XML string and return the Document. * * @throws BmsTransportException if the string is unparseable. */ // VisibleForTesting Document parse(String response) throws AssertionError { Document document; try { document = documentBuilder.parse(new InputSource(new StringReader(response))); } catch (IOException e) { throw new AssertionError("IOException parsing an in-memory XML string?"); } catch (SAXException e) { throw new BmsClientException("Error parsing result: " + e.getMessage(), e); } // Plain text is perfectly valid XML - it's a #text node. // We don't want that, though, since it's confusing and wrong. if (document.getDocumentElement() == null) { throw new BmsClientException("Error parsing result: no document element"); } return document; } /** * Log a user in to to Beep My Stuff to get a valid session. The session * code returned by this call is needed for all authenticated API calls. * * @param apikey the application unique API Key * @param nickname the nickname of the user who wants to login * @param password the API password for the user * @return the XML document returned by the server. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public Document login(String apikey, String nickname, String password) throws BmsTransportException, BmsApiException { Map<String, String> params = new LinkedHashMap<String, String>(); params.put("apikey", apikey); params.put("username", nickname); params.put("password", password); return makeRpc("login", true, params); } /** * Add an EAN to the user's library. * * @param apikey the application unique API Key * @param session the session ID returned by the login call * @param ean a valid EAN or UPC * @param isPublic should the item be publicly visible in the user's library * @param isShared should the item be visible to the user's friends. * @return the XML document returned by the server. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public Document addEan(String apikey, String session, String ean, boolean isPublic, boolean isShared) throws BmsTransportException, BmsApiException { Map<String, String> params = new LinkedHashMap<String, String>(); params.put("apikey", apikey); params.put("session", session); params.put("ean", ean); params.put("public", isPublic ? "true" : "false"); params.put("share", isShared ? "true" : "false"); return makeRpc("addean", false, params); } /** * Get the path to the user's avatar icon. * * @param apikey the application unique API Key * @param session the session ID returned by the login call * @return the XML document returned by the server. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ public Document getAvatarPath(String apikey, String session) throws BmsTransportException, BmsApiException { Map<String, String> params = new LinkedHashMap<String, String>(); params.put("apikey", apikey); params.put("session", session); return makeRpc("getavatarpath", true, params); } } }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; /** * The low-level Beep My Stuff HTTP API, documented at * http://www.beepmystuff.com/static/apidocs/index.html. * * @see DefaultBmsLowLevelClient * @see BmsClient */ public interface BmsLowLevelClient { /** * Log a user in to to Beep My Stuff to get a valid session token. The session * token returned by this call is needed for all authenticated API calls. * * @param nickname the nickname of the user who wants to login * @param password the API password for the user * @return the result of this call * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ BmsClient.LoginResult login(String nickname, String password) throws BmsTransportException, BmsApiException; /** * Add an EAN to the user's library. * * @param session the session token returned by the login call * @param ean a valid EAN or UPC * @param shareWith who the item should be shared with * @return the result of this call * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ BmsClient.AddEanResult addEan(String session, String ean, BmsClient.ShareWith shareWith) throws BmsTransportException, BmsApiException; /** * Returns the path to the user's avatar icon. * * @param session the session token returned by the login call * @return the path to the icon. * * @throws BmsTransportException if the request could not be made, or if the * response was unexpected or unintelligible. * @throws BmsApiException if an application-level error occurred. */ String getAvatarPath(String session) throws BmsTransportException, BmsApiException; }
Java
/* * Copyright 2009 Google Inc. * * 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.google.beepmystuff; import com.google.beepmystuff.BmsClient.ShareWith; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; import android.text.TextUtils; import android.util.Log; /** * Holds the details of pending and recent scans. * Data is backed in a sqlite3 database, holding the EAN, the current state of * the item (pending add, waiting for graphics etc), and the item's details for * a successful scan. The item's image is cached here too. * * Instances of this class are thread-safe. * TODO: Or at least, should be. Determine if that's true. */ public class ScanRegistry { private SQLiteDatabase db; private static final String TAG = "ScanRegistry"; private static final String DEFAULT_DB_NAME = "scan.db"; private static final int DB_VERSION = 6; private static final String SCAN_TABLE_NAME = "scans"; public static final String FIELD_EAN = "EAN"; public static final String FIELD_STATE = "STATE"; public static final String FIELD_STATUS = "STATUS"; public static final String FIELD_TITLE = "TITLE"; public static final String FIELD_IMAGE_URL = "IMGURL"; public static final String FIELD_IMAGE_DATA = "IMGDATA"; private static final int MAX_IMAGE_DATA_SIZE = 8192; public static final String FIELD_SCANNED_DATE = "SCANDATE"; public static final String FIELD_UPDATED_DATE = "LASTUPDATE"; public static final String FIELD_LAST_NETWORK_ATTEMPT = "LASTNETWORK"; public static final String FIELD_SHARE_WITH = "SHAREWITH"; private static final int STATE_PENDING_ADD = 0; private static final int STATE_ADD_FAILED = 1; private static final int STATE_PENDING_IMAGE = 2; private static final int STATE_COMPLETE = 3; private static final long MIN_RETRY_TIME_MS = 5 * 60 * 1000; /** * An interface used to supply clock information to the database. Can be used * to mock out the time source during testing. */ public interface Clock { /** * Gets the time "now", measured in milliseconds since some epoch. * @return milliseconds since the epoch */ long now(); } /** * An interface which receives notifications when the underlying data * changes. */ public interface Listener { /** * Notifies the listener that the scan registry has changed. */ void notifyChanged(); } /** * Internal private class used to create or upgrade the sqlite3 database * as necessary. */ private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context, String dbName) { super(context, dbName, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + SCAN_TABLE_NAME + " (" + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + FIELD_EAN + " TEXT NOT NULL," + FIELD_STATE + " INTEGER NOT NULL," + FIELD_STATUS + " TEXT," + FIELD_TITLE + " TEXT," + FIELD_IMAGE_URL + " TEXT," + FIELD_IMAGE_DATA + " BLOB(" + MAX_IMAGE_DATA_SIZE + ")," + FIELD_SCANNED_DATE + " INTEGER," + FIELD_UPDATED_DATE + " INTEGER," + FIELD_SHARE_WITH + " INTEGER, " + FIELD_LAST_NETWORK_ATTEMPT + " INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + SCAN_TABLE_NAME); onCreate(db); } } private Clock clock; private List<Listener> listeners = new ArrayList<Listener>(); /** * Constructs a ScanRegistry with the given global context. * The clock is taken to be one which uses the System's currentTimeMillis(). * @param context global context of the application */ public ScanRegistry(Context context) { this(context, new Clock() { public long now() { return System.currentTimeMillis(); } }, DEFAULT_DB_NAME); } /** * Constructs a ScanRegistry from a global context, using the given Clock, * and database filename. * @param context global application context * @param clock clock to use for times * @param databaseFilename name of the database file to use, or null for a * temporary in-memory database. */ public ScanRegistry(Context context, Clock clock, String databaseFilename) { DatabaseHelper helper = new DatabaseHelper(context, databaseFilename); db = helper.getWritableDatabase(); this.clock = clock; } /** * Adds a listener to the list of objects to notify when the data in the * ScanRegistry changed. * @param listener listener to add */ public void addListener(Listener listener) { listeners.add(listener); } /** * Removes a previous added listener. * If the listener wasn't previously added, this function does nothing. * @param listener to remove */ public void removeListener(Listener listener) { listeners.remove(listener); } /** * Closes the ScanRegistry. * Calling any methods after this has undefined behaviour. */ public void close() { db.close(); db = null; } /** * Walks the list of listeners, and notifies them that a change has occurred. */ private void notifyChanged() { for (Listener listener : listeners) { listener.notifyChanged(); } } /** * Adds an EAN to the scan registry. * The EAN is not a unique key, ie the same item can be scanned multiple times. * The EAN's state is marked as "pending add" * @param ean EAN to add, as a string. * @param shareWith who to share this item with * @return unique id of this EAN's instance */ public long addEan(String ean, ShareWith shareWith) { ContentValues values = new ContentValues(); values.put(FIELD_EAN, ean); values.put(FIELD_STATE, STATE_PENDING_ADD); values.put(FIELD_STATUS, "Queued"); Long now = clock.now(); values.put(FIELD_SCANNED_DATE, now); values.put(FIELD_UPDATED_DATE, now); values.put(FIELD_SHARE_WITH, shareWith.ordinal()); long id = db.insert(SCAN_TABLE_NAME, FIELD_EAN, values); if (id < 0) { throw new SQLException("Unable to add ean"); } notifyChanged(); return id; } /** * An Item holds information about an existing entry in the ScanRegistry. * It is mutable, and operations performed on it are reflected in the * registry. */ public class Item { private final long id; private final String ean; private final String imageUrl; private final ShareWith shareWith; /** * Create an Item from the given unique id, EAN, image URL (which may be * null or empty), and sharing options. */ private Item(long id, String ean, String imageUrl, ShareWith shareWith) { this.id = id; this.ean = ean; this.imageUrl = imageUrl; this.shareWith = shareWith; } /** * Returns the EAN associated with this Item. */ public String getEan() { return ean; } /** * Returns the image URL associated with this Item. This may be empty or * null if the image information has not yet been fetched, or if there is * no image for this Item. */ public String getImageUrl() { return imageUrl; } /** Returns who this item is to be shared with. */ public ShareWith shareWith() { return shareWith; } /** * Helper function used to update the database, filling in common fields * like updated time and last failed network attempt. * @param values a set of values to update * @param failedAttempt true if this update was a failed network attempt */ private void updateDatabase(ContentValues values, boolean failedAttempt) { Long now = clock.now(); values.put(FIELD_LAST_NETWORK_ATTEMPT, failedAttempt ? now : 0); values.put(FIELD_UPDATED_DATE, now); db.update(SCAN_TABLE_NAME, values, BaseColumns._ID + " == ?", new String[] { Long .toString(id) }); notifyChanged(); } /** * Note that adding this Item to the BeepMyStuff server failed. * @param reason the human-readable information on why the operation * failed. * @param fatal true if this was a fatal failure and should not be retried. */ public void addFailed(String reason, boolean fatal) { ContentValues values = new ContentValues(); if (fatal) { values.put(FIELD_STATE, STATE_ADD_FAILED); } values.put(FIELD_TITLE, "Unknown"); values.put(FIELD_STATUS, reason); updateDatabase(values, true); } /** * Note that this Item was successfully added to the BeepMyStuff server. * @param message message returned by the server * @param title title of the added item * @param imageUrl URL of any image data. May be empty or null if there is * no image associated with this Item. */ public void addSucceeded(String message, String title, String imageUrl) { ContentValues values = new ContentValues(); if (TextUtils.isEmpty(imageUrl)) { values.put(FIELD_STATE, STATE_COMPLETE); } else { values.put(FIELD_STATE, STATE_PENDING_IMAGE); values.put(FIELD_IMAGE_URL, imageUrl); } values.put(FIELD_STATUS, message); values.put(FIELD_TITLE, title); updateDatabase(values, false); } /** * Note that fetching an image for this item failed. * @param fatal true if the fetch failure was fatal and no further fetches * should be performed. */ public void imageFetchFailed(boolean fatal) { ContentValues values = new ContentValues(); if (fatal) { values.put(FIELD_STATE, STATE_COMPLETE); } updateDatabase(values, true); } /** * Note that an image fetch has succeeded. * @param imageData the raw image data */ public void imageFetchSucceeded(byte[] imageData) { ContentValues values = new ContentValues(); values.put(FIELD_STATE, STATE_COMPLETE); values.put(FIELD_IMAGE_DATA, imageData); updateDatabase(values, false); } /** * Returns the unique identifier of this Item. */ public long getId() { return id; } } /** * Wraps an entry in the registry (determined by a Cursor) in an Item * instance. * @param cursor cursor representing the Item. * @return an Item wrapping the entry */ public Item createItemFromCursor(Cursor cursor) { int idColumn = cursor.getColumnIndexOrThrow(BaseColumns._ID); int eanColumn = cursor.getColumnIndexOrThrow(FIELD_EAN); int imageColumn = cursor.getColumnIndexOrThrow(FIELD_IMAGE_URL); int shareWithColumn = cursor.getColumnIndexOrThrow(FIELD_SHARE_WITH); return new Item( cursor.getLong(idColumn), cursor.getString(eanColumn), cursor.getString(imageColumn), ShareWith.values()[cursor.getInt(shareWithColumn)]); } /** * Returns the next Item to add to the BeepMyStuff server. * The next Item is the most recently added Item which hasn't yet been * fetched, or the most recently non-fatally failed item that hasn't been * retried within the MIN_RETRY_TIME_MS period. * @return an Item that requires being added to BeepMyStuff, or null if none */ public Item getNextItemToAdd() { long cutOffTime = clock.now() - MIN_RETRY_TIME_MS; String selection = FIELD_STATE + " == " + STATE_PENDING_ADD + " AND (" + FIELD_LAST_NETWORK_ATTEMPT + " IS NULL OR " + FIELD_LAST_NETWORK_ATTEMPT + " < ? )"; Cursor cursor = db.query(SCAN_TABLE_NAME, null, selection, new String[] { Long.toString(cutOffTime) }, null, null, FIELD_UPDATED_DATE, "1"); Item item = null; if (cursor.moveToNext()) { item = createItemFromCursor(cursor); } cursor.close(); return item; } /** * Returns a sqlite3 Cursor object suitable for displaying the information in * the ScanRegistry. */ public Cursor getDisplayCursor() { Cursor cursor = db.query(SCAN_TABLE_NAME, null, null, null, null, null, FIELD_SCANNED_DATE + " DESC"); return cursor; } /** * Returns the next Item whose image requires fetching. * The next Item is determined similarly to the logic in getNextItemAdd. * @return the next Item to fetch the image for, or null if none */ public Item getNextItemToGetImage() { long cutOffTime = clock.now() - MIN_RETRY_TIME_MS; String selection = FIELD_STATE + " == " + STATE_PENDING_IMAGE + " AND (" + FIELD_LAST_NETWORK_ATTEMPT + " IS NULL OR " + FIELD_LAST_NETWORK_ATTEMPT + " < ? )"; Cursor cursor = db.query(SCAN_TABLE_NAME, null, selection, new String[] { Long.toString(cutOffTime) }, null, null, FIELD_UPDATED_DATE, "1"); Item item = null; if (cursor.moveToNext()) { item = createItemFromCursor(cursor); } cursor.close(); return item; } /** * Returns whether an item is awaiting an image, based on its status code and * its image url. */ public static boolean isStatePendingImage(int state) { return state == STATE_PENDING_ADD || state == STATE_PENDING_IMAGE; } }
Java
import java.sql.*; import java.io.*; import oracle.sql.*; import oracle.jdbc.driver.*; /************************************************************************* * Filename: Script.Java * Company: 1186 Entertainment * Last Modified: 3-20-06 * * Description: * This class provides a script runner for an oracle database * The class can read in an ASCII text file and then execute the * sequential SQL statements with the database * * TODO: * * Change Log: * * @author Ben Johnson * *************************************************************************/ public class Script { /** * Executes the SQL statements found in "file".<br> * This method breaks the provided SQL file in executable statements * on a semicolon on the end of the line, like in:<br> * <code>SELECT * FROM table<br>...<br>ORDER BY id<b>;</b></code><br> * The semicolon will be skipped (causes error in JDBC), but it's * needed by the command line clients; * * @param connection the Connection object to the Oracle database * @param file The ASCII script file with the Oracle syntax * @param log A log file to display the actions performed * */ public void executeScript(Connection connection, File file, PrintWriter log) throws IOException, SQLException { log.println("Reading from file " + file.getAbsolutePath()); System.out.println("Reading from file " + file.getAbsolutePath()); Statement stmt = connection.createStatement(); BufferedReader reader = new BufferedReader(new FileReader(file)); StringBuffer sqlBuf = new StringBuffer(); String line; boolean statementReady = false; int count = 0; while ((line = reader.readLine()) != null) { //loop thru lines in the file // different continuation for oracle and postgres line = line.trim(); if(line.indexOf("#") != -1)line = line.substring(0,line.indexOf("#")); if (line.equals("--/exe/--")) //execute finished statement for postgres { sqlBuf.append(' '); statementReady = true; } else if (line.equals("/")) //execute finished statement for oracle { sqlBuf.append(' '); statementReady = true; } else if (line.startsWith("#") || line.startsWith("--") || line.length() == 0) // comment or empty { continue; } else if (line.endsWith(";")) { sqlBuf.append(' '); sqlBuf.append(line.substring(0, line.length() - 1) + "\n"); statementReady = true; } else { sqlBuf.append(' '); sqlBuf.append(line + "\n"); statementReady = false; } if (statementReady) { if (sqlBuf.length() == 0) continue; System.out.println("exe: " + sqlBuf.toString()); try{ stmt.executeQuery(sqlBuf.toString().replaceAll("\n","")); } catch(SQLException e) { System.out.println(e); } count ++; sqlBuf.setLength(0); } } log.println("" + count + " statements processed"); log.println("Import done sucessfully"); System.out.println("" + count + " statements processed"); System.out.println("Import done sucessfully"); }//end executeScript() }//end of class
Java
/* * Author: Brett Rettura, Natalie * Company: 1186 Entertainment * Date Modified: 3/14/07 * Filename: Login.java */ import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; public class Login extends JPanel implements ActionListener { public ClientApplet CA; //declare some components JLabel lblHeading; JLabel lblUserName; JLabel lblUserPwd; JLabel lblImg; String DELIM = "&"; String usrName; char[] usrPwd; JTextField txtUserName; JPasswordField txtUsrPwd; Font f; Color r; JButton btnLogin; JButton btnGuest; JButton btnRegister; public Login(ClientApplet CA1) { CA = CA1; JPanel logPanel = new JPanel(new BorderLayout()); this.setLayout(new BorderLayout()); JPanel panel = new JPanel(new GridLayout(4, 1)); lblHeading=new JLabel("Login or Register"); Font f = new Font("Dialog" , Font.BOLD , 14); lblHeading.setFont(f); Color c=new Color(10,102,255); lblHeading.setForeground(c); lblHeading.setVerticalAlignment(SwingConstants.TOP); // logPanel.add(lblHeading, BorderLayout.NORTH); //CONSTRUCT FIELDS lblUserName = new JLabel("Enter Username"); panel.add(lblUserName); txtUserName=new JTextField(15); panel.add(txtUserName); lblUserPwd=new JLabel("Enter Password "); panel.add(lblUserPwd); txtUsrPwd = new JPasswordField(15); panel.add(txtUsrPwd); //ADD FIELDS logPanel.add(panel, BorderLayout.CENTER); //CONSTRUCT BUTTONS JPanel btnPanel=new JPanel(); btnLogin=new JButton("Login"); btnPanel.add(btnLogin); btnLogin.addActionListener(this); //add listener to the Login button btnGuest=new JButton("Guest"); btnPanel.add(btnGuest); btnGuest.addActionListener(this); //add listener to the Guest button btnRegister=new JButton("Register"); btnPanel.add(btnRegister); btnRegister.addActionListener(this); //ADD BUTTONS logPanel.add(btnPanel, BorderLayout.SOUTH); //CONSTRUCT IMAGE JPanel panelL = new JPanel(); ImageIcon icon = new ImageIcon(CA.getImage(CA.getDocumentBase(), "files/login_people.jpg")); //ImageIcon icon = new ImageIcon("files/login_people.jpg"); JLabel label = new JLabel(); label.setIcon(icon); panelL.add(label); // this.add(panelL, BorderLayout.EAST); this.add(logPanel, BorderLayout.WEST); //set background white this.setBackground(Color.WHITE); logPanel.setBackground(Color.WHITE); panelL.setBackground(Color.WHITE); btnPanel.setBackground(Color.WHITE); panel.setBackground(Color.WHITE); txtUserName.transferFocus(); setSize(500,500); setVisible(true); }//end or Login() public void actionPerformed(ActionEvent e1) { JButton button=(JButton)e1.getSource(); //get the source of the event if(button.equals(btnGuest)) { //CA.processMessage("13"+DELIM); CA.send("13"); CA.loadPanel(new GameSelect(CA)); } else if(button.equals(btnRegister)) { //CA.processMessage("9"+DELIM); CA.loadPanel(new Register(CA)); } else if(e1.getSource().equals(btnLogin)) { if(valid()) { try { usrName = txtUserName.getText(); usrPwd = txtUsrPwd.getPassword(); CA.send("1"+ DELIM + usrName + DELIM + new String(usrPwd)); } catch(Exception e) { System.out.println("Exception "+e); } }//end of if } else if(e1.getSource().equals(txtUserName)) { txtUsrPwd.transferFocus(); } else if(e1.getSource().equals(txtUsrPwd)) { btnLogin.transferFocus(); } }//end of actionPerformed() boolean valid() //test the validity of the user information { try { usrName=txtUserName.getText(); usrPwd=txtUsrPwd.getPassword(); String strUsrPwd=new String(usrPwd); if(usrName.length() == 0 || strUsrPwd.length() == 0) { JOptionPane.showMessageDialog(this,"Please provide a username and password.", "Message", JOptionPane.ERROR_MESSAGE); return false; } }//end of try catch(Exception e) { System.out.println("error in valid"+e); }//end of catch return true; }//end of valid() //error msg- User Exists void showUsrExists() { JOptionPane.showMessageDialog(this,"User exists.", "Message", JOptionPane.ERROR_MESSAGE); } int flg=0; //error msg- Incorrect Entry void showErrordlg() { JOptionPane.showMessageDialog(this,"Incorrect entry.", "Message", JOptionPane.ERROR_MESSAGE); } //error msg- Incorrect Age entered void showErrordlgInt() { JOptionPane.showMessageDialog(this,"Age incorrect.", "Message", JOptionPane.ERROR_MESSAGE); } //public static void main(String args[]) //{ // new Login(); //} }//end of class
Java
interface Forfeitable { public void receiveForfeit(); public void sendForfeit(); }
Java
/* * Author: Don Koenig * Company: 1186 Entertainment * Date Modified: 3/13/07 * Filename: ClientApplet.java */ import java.awt.*; import java.applet.*; import java.net.*; import java.awt.event.*; import javax.swing.*; import java.util.Date; import java.lang.Object; import java.util.*; import java.lang.Thread.*; import java.io.*; import java.net.*; import java.text.*; public class ClientApplet extends Applet implements Runnable { enum PanelType{ LOGINPANE, REGISTERPANE, GAMESELECTPANE, LOBBY, ROOM} public static String DELIM = "&"; public JPanel currPane; public PanelType currPaneType; public BufferedReader fromServer; public PrintWriter toServer; public int PORT = 33456; private Socket sock; String serverName; private boolean running; private String playerName; private String loginName; private String gameName; private char [] inputBuff; public void init() { try { running = true; inputBuff = new char[128]; try { serverName = "67.171.65.100"; //I am Don's Desktop IP System.out.println("Server name: " + serverName); InetAddress addr = InetAddress.getByName(serverName); System.out.println("Connecting..."); sock = new Socket(addr, PORT); // Connect to server System.out.println("Connected"); fromServer = new BufferedReader( new InputStreamReader( sock.getInputStream())); // Get Reader and Writer toServer = new PrintWriter( new BufferedWriter( new OutputStreamWriter(sock.getOutputStream())), true); Thread outputThread = new Thread(this); // Thread is to receive strings outputThread.setPriority(2); outputThread.start(); // from Server } catch (Exception e) { System.out.println("Exception durring initialization: " + e); JOptionPane.showMessageDialog(this,"Error Connecting to Server", "Message", JOptionPane.ERROR_MESSAGE); } setLayout(new FlowLayout()); setBounds(0, 0, 800, 600); currPaneType = PanelType.LOGINPANE; currPane = new Login(this); //currPane = new GameSelect(this); add(currPane); } catch (Exception ex) { System.out.println("Exception durring add of Login: " + ex); } } public void run() { System.out.println("Running..."); while (running) { try { String currMsg = fromServer.readLine(); System.out.println("Received: "+ currMsg); if (currMsg != null) processMessage(currMsg); else running = false; } catch (Exception e) { System.out.println("Exception Receiving Message: " + e); running = false; } } System.exit(0); } public void loadPanel(JPanel pane) { try { System.out.println("loadPanel("+pane.getClass().getName()+")"); this.remove(currPane); //this.removeAll(); currPane = pane; this.add(pane); currPane.setVisible(true); this.setVisible(true); repaint(); this.validate(); } catch (Exception ex) { System.out.println("Exception Loading Panel: " + ex); } } public void send(String msg) { System.out.println("Sending: " + msg); //if (msg.startsWith("1") || msg.startsWith("3")) // loginName = msg.split(DELIM)[1]; toServer.println(msg); } public void destroy() { send("27" + DELIM); super.destroy(); } public String getPlayerName() { return playerName; } public void logout() { playerName = null; send("8"); loadPanel(new Login(this)); } /** Extract the data from the received Msg */ private void processMessage(String msg) { try { int type = Integer.parseInt(msg.substring(0, msg.indexOf(DELIM))); String[] msgParts; switch (type) { //case 1: //user Validation 1|username|password // break; case 2: //isValid (user login) "2DELIMvalid try { if (msg.split(DELIM)[1].equals("valid")) { //send("4" + DELIM + "0"); playerName = loginName; loginName = null; System.out.println("username is valid. Loading game select"); loadPanel(new GameSelect(this)); } else { System.out.println("invalid user login/registration"); JOptionPane.showMessageDialog(this,"Invalid username/password", "Message", JOptionPane.ERROR_MESSAGE); } } catch (Exception ex) { System.out.println(ex); } break; //user Registration 3|.... //Select GameLobby 4|gameID case 5: msgParts = msg.split(DELIM); //String allPlayers1[] = msgParts[1].split(","); //String topPlayers1[] = msgParts[2].split(","); String allPlayers1[] = msgParts[3].split(","); String topPlayers1[] = msgParts[4].split(","); ClientApplet ca = this; //String lobbyName1 = "Reversi"; //String playerName1 = "ME!"; String lobbyName1 = msgParts[1]; String playerName1 = msgParts[2]; playerName = playerName1; int topScores1[] = { 56, 48, 39, 33, 21 }; //GameLobby lobby = new GameLobby(ca, lobbyName1, playerName1, allPlayers1, topPlayers1); loadPanel(new GameLobby(ca, lobbyName1, playerName1, allPlayers1, topPlayers1)); //loadPanel(new GameSelect()); break; //# Request profile information of given user id (view profile) //* 6 //* <String>username case 7: //view profile response //username gender age rank viewProfile(msg); break; //case 8: //who put this here? this isnt right // loadPanel(new Login(this)); // break; case 9: System.out.println("Loading registration"); loadPanel(new Register(this)); break; case 10: System.out.println("Received Challenge"); if (receiveChallenge(msg)) send("11" + DELIM + msg.substring(msg.indexOf(DELIM) + 1) + DELIM + "accept"); else send("11" + DELIM + msg.substring(msg.indexOf(DELIM) + 1) + DELIM + "decline"); JOptionPane challengePane = new JOptionPane("User has challenged you", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION); //JOptionPane.showMessageDialog(this, "Age incorrect.", "Message", JOptionPane.YES_NO_MESSAGE); //send #11 break; case 11: //accept/decline -- if i receive this, it was a decline, otherwise the msg would be 12 JOptionPane.showMessageDialog(this, "Challenge Declined", "Message", JOptionPane.ERROR_MESSAGE); break; case 12: //start new game newGame(msg); break; case 16: //edit profile msgParts = msg.split(DELIM); JFrame editProfile = new EditProfile(this, msgParts); editProfile.setTitle("Edit Your Profile"); editProfile.setVisible(true); break; case 19: updatePlayers(msg); break; case 21: updateTopPlayers(msg); break; case 22: try { ((ReversiGameRoom)currPane).board.processMove(msg); } catch (Exception ex) { System.out.println("Exception processing move: " + ex); } break; case 24://receive chat message receiveChatMsg(msg); break; case 25: //receive forfeit message ((Forfeitable)currPane).receiveForfeit(); break; case 26: //you got kick!!! Kicked! Kicked Kicked Kicked.... JOptionPane.showMessageDialog(this, "You got kicked! \nSomeone else logged in with your username.", "Message", JOptionPane.ERROR_MESSAGE); loadPanel(new Login(this)); break; default: System.out.println("Received illegal message type: " + type); } } catch (Exception ex) { System.out.println("Exception Processing Message: " + ex); ex.printStackTrace(); } } public void receiveChatMsg(String msg) { String [] parts = msg.split(DELIM); ((Chatable)currPane).receiveMsg(parts[1], parts[2]); } public boolean receiveChallenge(String msg) { int reply = -1; String[] parts = msg.split(DELIM); try { reply = JOptionPane.showConfirmDialog(this, new JLabel("You have been challenged by: "+parts[1]), "You have been challenged by: "+parts[1], JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); } catch (Exception ex) { System.out.println(ex); } if (reply == JOptionPane.YES_OPTION) { System.out.println("Accepted"); return true; } else { System.out.println("reply: " + reply); return false; } } public void viewProfile(String msg) { String [] msgParts = msg.split(DELIM); JFrame profile = new JFrame(msgParts[1] + "\'s Profile"); Container pane = profile.getContentPane(); pane.setLayout(new BorderLayout()); JPanel titlePane = new JPanel(); GridLayout grid = new GridLayout(5, 1); grid.setHgap(10); grid.setVgap(10); JPanel profilePane = new JPanel(grid); JLabel title = new JLabel(msgParts[1] + "\'s Profile"); Font f = new Font("Monospaced", Font.BOLD, 18); Font f2 = new Font("SansSerif", Font.PLAIN, 14); title.setFont(f); //Color c = new Color(0, 200, 0); title.setForeground(new Color(131, 25, 38)); titlePane.add(title); JLabel lblName = new JLabel("Username: " + msgParts[1]); JLabel lblEmail = new JLabel("Email: " + msgParts[5]); JLabel lblGender = new JLabel("Gender: " + msgParts[2]); JLabel lblAge = new JLabel("Age: " + msgParts[3]); JLabel lblPoints = new JLabel("Total Points: " + msgParts[4]); lblName.setFont(f2); lblEmail.setFont(f2); lblGender.setFont(f2); lblAge.setFont(f2); lblPoints.setFont(f2); profilePane.add(lblName); profilePane.add(lblEmail); profilePane.add(lblGender); profilePane.add(lblAge); profilePane.add(lblPoints); pane.add(titlePane, BorderLayout.NORTH); pane.add(profilePane, BorderLayout.CENTER); profile.setBounds(0, 0, 250, 300); profile.setVisible(true); } public void newGame(String msg) { String[] parts = msg.split(DELIM); loadPanel(new ReversiGameRoom(this,parts[1],Integer.parseInt(parts[2]),parts[3],Integer.parseInt(parts[4]))); } public void updatePlayers(String msg) { String[] parts = msg.split(DELIM); System.out.println("ClientApplet.updatePlayers: " + parts[1]); String [] players = parts[1].split(","); for (int i = 0; i < players.length; i++) { System.out.println(players[i]); } try { ((GameLobby)currPane).updatePlayers(players,null); } catch (Exception ex) { System.out.println("Exception processing updatePlayers msg: " + ex); } } public void updateTopPlayers(String msg) { String[] parts = msg.split(DELIM); System.out.println("ClientApplet.updateTopPlayers: " + parts[1]); String [] players = parts[1].split(","); for (int i = 0; i < players.length; i++) { System.out.println(players[i]); } try { ((GameLobby)currPane).updatePlayers(null,players); } catch (Exception ex) { System.out.println("Exception processing updateTopPlayers msg: " + ex); } } public void close() { try { running = false; fromServer.close(); toServer.close(); sock.close(); } catch (IOException io) { } } public void showRules(String game) { URL url = null; String url_str = getCodeBase() + game + "_Rules.html"; try{ url = new URL(url_str); } catch(MalformedURLException e){System.out.println("Error in show rules: " + e);} System.out.println("Attempting to open: "+url_str); getAppletContext().showDocument(url,"_blank"); } }
Java
/** * @author Don Koenig, Brett, Natalie * Company: 1186 Entertainment * Date Modified: 3/13/07 * Filename: ClientThread.java */ import java.awt.*; import java.applet.*; import java.net.*; import java.awt.event.*; import javax.swing.*; import java.util.Date; import java.lang.Object; import java.util.*; import java.lang.Thread.*; import java.io.*; import java.net.*; import java.text.*; public class GameSelect extends JPanel implements ActionListener { public static String DELIM = "&"; JPanel textPane, buttonPane; JButton playReversiButton, logoutButton; ClientApplet ca; public GameSelect(ClientApplet client_applet) { ca = client_applet; Font f = new Font("Dialog" , Font.BOLD , 14); Color c=new Color(10,102,255); playReversiButton = new JButton("Play Reversi"); playReversiButton.addActionListener(this); logoutButton = new JButton("Logout"); logoutButton.addActionListener(this); //top panel JPanel topPanel = new JPanel(); JLabel lblSelect = new JLabel("Select a game to play or "); lblSelect.setFont(f); lblSelect.setForeground(c); topPanel.add(lblSelect); topPanel.add(logoutButton); //reversi panel JPanel revPanel = new JPanel(new BorderLayout()); //set picture ImageIcon iconRev = new ImageIcon(ca.getImage(ca.getDocumentBase(), "files/reversi.jpg")); //ImageIcon iconRev = new ImageIcon("files/reversi.jpg"); JLabel picRev = new JLabel(); picRev.setIcon(iconRev); //add revPanel.add(picRev, BorderLayout.NORTH); revPanel.add(playReversiButton); String[] comSoon = {"files/hangman.jpg", "files/tictac.jpg"}; int i = 0; JPanel[] gamPanel = new JPanel[comSoon.length]; ImageIcon[] iconGam = new ImageIcon[comSoon.length]; JLabel[] picGam = new JLabel[comSoon.length]; JLabel[] lblGam = new JLabel[comSoon.length]; for(i=0; i<comSoon.length; i++) { //game panel gamPanel[i] = new JPanel(new BorderLayout()); //set picture iconGam[i] = new ImageIcon(ca.getImage(ca.getDocumentBase(),comSoon[i])); picGam[i] = new JLabel(); picGam[i].setIcon(iconGam[i]); //add gamPanel[i].add(picGam[i], BorderLayout.NORTH); lblGam[i] = new JLabel("Coming soon!"); gamPanel[i].setBackground(Color.WHITE); gamPanel[i].add(lblGam[i]); } JPanel midPanel = new JPanel(); //top, left, bottom, right midPanel.setBorder(BorderFactory.createEmptyBorder(0,10,0,10)); midPanel.add(revPanel); for(i=0; i<comSoon.length; i++) { midPanel.add(gamPanel[i]); } //add to this panel this.setLayout(new BorderLayout()); this.add(topPanel, BorderLayout.NORTH); this.add(midPanel, BorderLayout.SOUTH); //set background to white this.setBackground(Color.WHITE); topPanel.setBackground(Color.WHITE); revPanel.setBackground(Color.WHITE); midPanel.setBackground(Color.WHITE); playReversiButton.transferFocus(); setSize(800, 600); setVisible(true); } public void actionPerformed(ActionEvent ae) { String msg; JButton button=(JButton)ae.getSource(); //get the source of the event if(button.equals(playReversiButton)) { ca.send("4" + DELIM + "0"); //ca.loadPanel(new GameLobby()); } else if(button.equals(logoutButton)) { //msg = "8"; //ca.send(msg); //go back to login screen System.out.println("Logout Pressed. Switching to Login Screen."); //ca.loadPanel(new Login(ca)); ca.logout(); } } }
Java
/* * Author: Ben Johnson * Company: 1186 Entertainment * Date Modified: 3/14/07 * Filename: EditProfile.java */ import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; public class EditProfile extends JFrame implements ActionListener { public ClientApplet CA; //declare components JLabel lblUserName; JLabel lblUserPwd; JLabel lblCnfUserPwd; JLabel lblEmail; JLabel lblGender; JLabel lblBirth; JTextField txtUserName; JPasswordField txtUsrPwd; JPasswordField txtCnfUsrPwd; JTextField txtEmail; JComboBox lstGender; JTextField txtGender; JTextField txtBirth; JButton btnSave; JButton btnCancel; String DELIM = "&"; String username; String usrPwd; String cnfPwd; String email; String gender; String birth; public EditProfile(ClientApplet CA1, String[] data) { String oldUserName = data[1].trim(); String oldPassword = data[2].trim(); String oldEmail = data[3].trim(); String oldGender = data[4].trim(); String oldBirth = data[5].trim(); CA = CA1; //apply the layout int rows = 7; int cols = 2; JPanel panel = new JPanel(new GridLayout(rows, cols)); int top, left, bottom, right; top = left = bottom = right = 20; panel.setBorder(BorderFactory.createEmptyBorder (top,left,bottom,right)); //initialize all the labels and fields lblUserName = new JLabel("Username: "); panel.add(lblUserName); txtUserName = new JTextField(oldUserName); txtUserName.setEditable(false); panel.add(txtUserName); lblUserPwd = new JLabel("Enter Password "); panel.add(lblUserPwd); txtUsrPwd = new JPasswordField(15); txtUsrPwd.setText(oldPassword); panel.add(txtUsrPwd); lblCnfUserPwd=new JLabel("Confirm Password "); panel.add(lblCnfUserPwd); txtCnfUsrPwd = new JPasswordField(15); txtCnfUsrPwd.setText(oldPassword); panel.add(txtCnfUsrPwd); lblEmail = new JLabel("E-Mail "); panel.add(lblEmail); txtEmail = new JTextField(oldEmail); panel.add(txtEmail); lblGender = new JLabel("Gender"); panel.add(lblGender); //String[] genderlist = {"male", "female"}; //JComboBox lstGender = new JComboBox(genderlist); lstGender = new JComboBox(); lstGender.addItem("male"); lstGender.addItem("female"); if(oldGender.equals("male")) { lstGender.setSelectedIndex(0); System.out.println("lstGender.setSelectedIndex = "+lstGender.getSelectedIndex()); } else { lstGender.setSelectedIndex(1); System.out.println("lstGender.setSelectedIndex = "+lstGender.getSelectedIndex()); } panel.add(lstGender); lstGender.addActionListener(this); //txtGender = new JTextField(oldGender); //txtGender.setEditable(false); //panel.add(txtGender); gender = oldGender; lblBirth = new JLabel("Birthdate (YYYY-MM-DD)"); panel.add(lblBirth); txtBirth = new JTextField(oldBirth); panel.add(txtBirth); btnSave=new JButton("Update"); btnSave.addActionListener(this); //add listener to the Submit button panel.add(btnSave); btnCancel=new JButton("Cancel"); btnCancel.addActionListener(this); //add listener to the Cancel button panel.add(btnCancel); add(panel); panel.setVisible(true); setSize(500,300); setVisible(true); }//end constructor public void actionPerformed(ActionEvent e1) { Object src = e1.getSource(); if(src == btnCancel) { this.dispose(); } else if(src == btnSave) { if(verify()) { try { CA.send("17"+ DELIM + username + DELIM + new String(usrPwd) + DELIM + email + DELIM + gender + DELIM + birth); } catch(Exception e) { System.out.println("Exception "+e); } this.dispose(); } } else if(src == lstGender) { if(lstGender.getSelectedIndex() == 0) gender = "male"; if(lstGender.getSelectedIndex() == 1) gender = "female"; System.out.println("Gender was changed to "+ gender); } }//end of actionPerformed() public boolean verify() //test the validity of the user information { boolean valid = true; int intAge=0; try { username = txtUserName.getText().trim(); char[] chrusrPwd = txtUsrPwd.getPassword(); usrPwd = new String(chrusrPwd).trim(); char[] chrcnfPwd = txtCnfUsrPwd.getPassword(); cnfPwd = new String(chrcnfPwd).trim(); email = txtEmail.getText().trim(); if(lstGender == null) System.out.println("lstGender is null"); System.out.println("lstGender.selectedIndex = "+lstGender.getSelectedIndex()); if(lstGender.getSelectedIndex() == 0){gender = "male";} else {gender = "female";} //gender = txtGender.getText(); birth = txtBirth.getText().trim(); // Check form completion if( username == null || usrPwd == null || cnfPwd == null || email == null || gender == null || birth == null) { JOptionPane.showMessageDialog(this,"Incomplete form.", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } // Check passwords if(!usrPwd.equals(cnfPwd)) { JOptionPane.showMessageDialog(this,"Passwords are not the same", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } if(usrPwd.length() < 4) { JOptionPane.showMessageDialog(this,"Password must be at least 4 characters.", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } if(gender.length() > 6) { JOptionPane.showMessageDialog(this,"Gender Field must be less than 7 characters.", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } // Check birthday String birthParts[] = birth.trim().split("-"); if( birthParts != null ) { int intYear = (int)Integer.parseInt(birthParts[0]); int intMonth = (int)Integer.parseInt(birthParts[1]); int intDay = (int)Integer.parseInt(birthParts[2]); if(intYear < 1900 || intYear > 2007) { JOptionPane.showMessageDialog(this,"Invalid Year", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } if(intMonth < 1 || intMonth > 12) { JOptionPane.showMessageDialog(this,"Invalid Month", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } if(intDay < 0 || intDay > 31) { JOptionPane.showMessageDialog(this,"Invalid Day", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } } else { JOptionPane.showMessageDialog(this,"Invalid birthday. Use YYYY-MM-DD format.", "Invalid Form", JOptionPane.ERROR_MESSAGE); return false; } }//end of try catch(Exception e) { System.out.println("error in verify:"); e.printStackTrace(); JOptionPane.showMessageDialog(this,"Error on form.", "Message", JOptionPane.ERROR_MESSAGE); return false; }//end of catch return true; }//end of verify() }//end of class
Java
import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.GraphicsConfiguration; import java.awt.Transparency; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; public class MyPanel extends JPanel { public final static int CENTERED = 0; public final static int STRETCHED = 1; public final static int TILED = 2; private BufferedImage backgroundImage; private int backgroundPosition; private BufferedImage stretchedImage; private static final int TOP = 0; private static final int LEFT = 0; private static final int CENTER = -1; private static final int BOTTOM = -2; private static final int RIGHT = -2; private Color gradientColor1; private Color gradientColor2; private int gradientX1 = 0; private int gradientX2 = 0; private int gradientY1 = 0; private int gradientY2 = 0; private boolean cyclic = false; public void setBackgroundImage(BufferedImage image) { backgroundImage = image; stretchedImage = null; } public void setBackgroundImage(String path) /*throws IOException */{ try { setBackgroundImage(ImageIO.read(new File(System.getProperty("user.dir") + path))); } catch (IOException e) { e.printStackTrace(); } } public void setBackgroundPosition(int position) { backgroundPosition = position; } public void setBackgroundGradient(Color color1, Color color2) { setBackgroundGradient(color1, CENTER, TOP, color2, CENTER, BOTTOM, true); } public void setBackgroundGradient(Color color1, int x1, int y1, Color color2, int x2, int y2, boolean cyclic) { setBackgroundImage((BufferedImage) null); gradientColor1 = color1; gradientColor2 = color2; gradientX1 = x1; gradientY1 = y1; gradientX2 = x2; gradientY2 = y2; this.cyclic = cyclic; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; if (backgroundImage != null) { switch (backgroundPosition) { case CENTERED: paintCenteredImage(g2); break; case STRETCHED: paintStretchedImage(g2); break; case TILED: paintTiledImage(g2); break; } } else if ((gradientColor1 != null) && (gradientColor2 != null)) { paintGradient(g2); } } private void paintGradient(Graphics2D g2) { int x1 = gradientX1; if (x1 == CENTER) x1 = getWidth() / 2; if (x1 == RIGHT) x1 = getWidth(); int y1 = gradientY1; if (y1 == CENTER) y1 = getHeight() / 2; if (y1 == BOTTOM) y1 = getHeight(); int x2 = gradientX2; if (x2 == CENTER) x2 = getWidth() / 2; if (x2 == RIGHT) x2 = getWidth(); int y2 = gradientY2; if (y2 == CENTER) y2 = getHeight() / 2; if (y2 == BOTTOM) y2 = getHeight(); g2.setPaint(new GradientPaint(x1, y1, gradientColor1, x2, y2, gradientColor2, cyclic)); g2.fillRect(0, 0, getWidth(), getHeight()); } private void paintCenteredImage(Graphics2D g2) { int x = (getWidth() - backgroundImage.getWidth()) / 2; int y = (getHeight() - backgroundImage.getHeight()) / 2; g2.drawImage(backgroundImage, null, x, y); } private void paintTiledImage(Graphics2D g2) { int tileWidth = backgroundImage.getWidth(); int tileHeight = backgroundImage.getHeight(); for (int x = 0; x < getWidth(); x += tileWidth) { for (int y = 0; y < getHeight(); y += tileHeight) { g2.drawImage(backgroundImage, null, x, y); } } } private void paintStretchedImage(Graphics2D g2) { if (stretchedImage == null) { // If it's the first time the image is streched. stretchedImage = createScaledImage(); } else if ((stretchedImage.getWidth() != getWidth()) || (stretchedImage.getHeight() != getHeight())) { // If the size of the panel has changed the image has to be streched // again. stretchedImage = createScaledImage(); } g2.drawImage(stretchedImage, null, 0, 0); } private BufferedImage createScaledImage() { GraphicsConfiguration gc = getGraphicsConfiguration(); BufferedImage newImage = gc.createCompatibleImage(getWidth(), getHeight(), Transparency.TRANSLUCENT); Graphics g = newImage.getGraphics(); int width = backgroundImage.getWidth(); int height = backgroundImage.getHeight(); g.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), 0, 0, width, height, null); g.dispose(); return newImage; } /* public static void main(String[] args) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); MyPanel panel = new MyPanel(); try { panel.setBackgroundImage("lh0.gif"); } //catch (IOException e) { e.printStackTrace(); } panel.setBackgroundPosition(MyPanel.STRETCHED); // panel.setBackgroundGradient(Color.green, Color.white); panel.setLayout(new FlowLayout()); panel.setPreferredSize(new Dimension(400, 400)); frame.getContentPane().add(panel); frame.pack(); frame.setVisible(true); }*/ }
Java
//describes information for a player import java.util.Date; public class PlayerInfo { public int id; public String username; public String email; public String password; public String gender; public String birth; //YYYY-MM-DD public GameStats[] gameStats; public String toString() { String out = "id="+id+";username="+username+";email="+email+";password="+password+";gender="+gender+";birth="+birth+";gameStats="; if(gameStats != null) { for(int i = 0;i<gameStats.length;i++) { out += "\n" + gameStats[i]; } } return out; } }
Java
/* * Author: Brett Rettura, Natalie * Company: 1186 Entertainment * Date Modified: 3/26/07 * Filename: Register.java */ import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; public class Register extends JPanel implements ActionListener { public ClientApplet CA; //declare components JLabel lblHeading; JLabel lblUserName; JLabel lblUserPwd; JLabel lblCnfUserPwd; JLabel lblEmail; JLabel lblBirth; JLabel lblSex; String DELIM = "&"; String usrName; char[] usrPwd; char[] cnfPwd; String email; String birth; String gender; JComboBox lstSex; JTextField txtUserName; JPasswordField txtUsrPwd; JPasswordField txtCnfUsrPwd; JTextField txtEmail; JTextField txtBirth; Font f; Color r; JButton btnSubmit; JButton btnBack; public Register(ClientApplet CA1) { CA = CA1; //apply the layout this.setLayout(new BorderLayout()); JPanel panel = new JPanel(new GridLayout(6, 2)); //place the components lblHeading=new JLabel("Registration Info"); Font f = new Font("Dialog" , Font.BOLD , 14); lblHeading.setFont(f); Color c=new Color(10,102,255); lblHeading.setForeground(c); lblHeading.setVerticalAlignment(SwingConstants.TOP); this.add(lblHeading, BorderLayout.NORTH); //CONSTRUCT FIELDS lblUserName = new JLabel("Enter Username"); panel.add(lblUserName); txtUserName=new JTextField(15); panel.add(txtUserName); lblUserPwd=new JLabel("Enter Password"); panel.add(lblUserPwd); txtUsrPwd = new JPasswordField(15); panel.add(txtUsrPwd); lblCnfUserPwd=new JLabel("Confirm Password"); panel.add(lblCnfUserPwd); txtCnfUsrPwd=new JPasswordField(15); panel.add(txtCnfUsrPwd); lblEmail=new JLabel("Email"); panel.add(lblEmail); txtEmail=new JTextField(15); panel.add(txtEmail); lblBirth=new JLabel("Birthday:"); panel.add(lblBirth); txtBirth=new JTextField(15); txtBirth.setText("yyyy-mm-dd"); panel.add(txtBirth); lblSex=new JLabel("Sex"); panel.add(lblSex); String[] sex= {"male", "female"}; lstSex=new JComboBox(sex); lstSex.setSelectedIndex(0); panel.add(lstSex); this.add(panel, BorderLayout.CENTER); //CONTRUCT BUTTONS JPanel btnPanel=new JPanel(); btnSubmit=new JButton("Register"); btnPanel.add(btnSubmit); btnSubmit.addActionListener(this); //add listener to the Submit button btnBack=new JButton("Back"); btnPanel.add(btnBack); btnBack.addActionListener(this); //add listener to the Cancel button this.add(btnPanel, BorderLayout.SOUTH); //set background white this.setBackground(Color.WHITE); btnPanel.setBackground(Color.WHITE); panel.setBackground(Color.WHITE); setSize(500,500); setVisible(true); }//end or Register() public void actionPerformed(ActionEvent e1) { JButton button=(JButton)e1.getSource(); //get the source of the event if(button.equals(btnBack)) { CA.loadPanel(new Login(CA)); } else { int ver=verify(); //call the verify() if(ver==1) { try { CA.send("3"+ DELIM + usrName + DELIM + new String(usrPwd) + DELIM + usrName + DELIM + email + DELIM + gender + DELIM + birth); }//end of try catch(Exception e) { System.out.println("Exception "+e); } }//end of if }//end of else }//end of actionPerformed() int verify() //test the validity of the user information { int ctr=0; try { usrName=txtUserName.getText(); usrPwd=txtUsrPwd.getPassword(); cnfPwd=txtCnfUsrPwd.getPassword(); email=txtEmail.getText(); birth=txtBirth.getText(); String strUsrPwd=new String(usrPwd); String strCnfPwd=new String(cnfPwd); System.out.println("Does it make it here?"); if(lstSex.getSelectedIndex() == 0) { gender = "male"; } else { gender = "female"; } if(strUsrPwd.equals(strCnfPwd) == false) { showErrordlgMsg("Confirmation password does not match password."); } try { String [] birthParts = birth.trim().split("-"); int intYear = (int)Integer.parseInt(birthParts[0]); int intMonth = (int)Integer.parseInt(birthParts[1]); int intDay = (int)Integer.parseInt(birthParts[2]); } catch(Exception e) { System.out.println(e); showErrordlgInt(); } if((usrName.length()>0)&&(strUsrPwd.length()>0)&&(strCnfPwd.length()>0)&&(email.length()>0)&&(birth.length()>0)&&(strUsrPwd.equals(strCnfPwd))) { System.out.println("done"); ctr=1; return ctr; } else { showErrordlg(); }//end of else }//end of try catch(Exception e) { e.printStackTrace(); System.out.println("exception thrown "+e); }//end of catch return ctr; }//end of verify() //error msg- User Exists void showUsrExists() { JOptionPane.showMessageDialog(this,"User exists.", "Message", JOptionPane.ERROR_MESSAGE); } int flg=0; //error msg- Incorrect Entry void showErrordlg() { JOptionPane.showMessageDialog(this,"Incorrect entry.", "Message", JOptionPane.ERROR_MESSAGE); } //error msg- Incorrect Age entered void showErrordlgInt() { JOptionPane.showMessageDialog(this,"Birthday incorrect.", "Message", JOptionPane.ERROR_MESSAGE); } //error msg void showErrordlgMsg(String myMsg) { JOptionPane.showMessageDialog(this,myMsg, "Message", JOptionPane.ERROR_MESSAGE); } //public static void main(String args[]) //{ //new Register(); //} }//end of class
Java
interface Chatable { public void sendMsg(String text); public void receiveMsg(String sender, String text); }
Java
//describes the wins, losses, and forfeits for a game type public class GameStats { public String gameName; public int wins; public int losses; public int forfeits; public String toString() { return "gameName="+gameName+";wins="+wins+";losses="+losses+";forfeits="+forfeits; } public int getRank() { return (wins - losses - forfeits); } }
Java
/* CoE 1186 1186 Entertainment Reversi Game ReversiGameRoom.java ----------------------------------------- ReversiGameRoom - Abstract or Concrete: Concrete - List of Superclasses: GameRoom - List of Subclasses: N/A - Purpose: GUI pane representing a Reversi Game Room screen - Collaborations: Loaded by the ClientApplet, sends commands to Server through the ClientApplet --------------------- - Attributes: - ReversiGameBoard board -> Reversi implementation of GameBoard abstract class. Handles all moves and manages the rules; including win/lose conditions. --------------------- - Operations: - void paint(Graphics g) -> Paints any custom graphics. --------------------- - Constraints: N/A ----------------------------------------- */ import java.awt.*; import javax.swing.*; import java.awt.event.*; //Game room GUI where the game takes place public class ReversiGameRoom extends GameRoom { ReversiGameBoard board; JPanel boardPane, gameMessagePane; JLabel gamePieceLbl, statusLbl; JTextField gamePieceFld, statusFld; int p1id, p2id; boolean i_forfeit; public ReversiGameRoom(ClientApplet ca1, String player1, int player1id, String player2, int player2id) { super(ca1, "Reversi Game Room", player1, player1id, player2, player2id, "View Rules", "Forfeit Game", "Reversi"); setBoardPane(); setPreferredSize(new Dimension(700,500)); setMessagePane(); i_forfeit = false; } public void setBoardPane() { boardPane = new JPanel(new FlowLayout()); board = new ReversiGameBoard(ca,this,p1id,p2id); boardPane.add(board); this.add(boardPane, BorderLayout.CENTER); } public void setMessagePane() { gamePieceLbl = new JLabel("Your game piece color:"); statusLbl = new JLabel("Status: "); gamePieceFld = new JTextField(); gamePieceFld.setBackground(this.getBackground()); gamePieceFld.setBorder(BorderFactory.createEmptyBorder()); gamePieceFld.setEditable(false); statusFld = new JTextField(); statusFld.setBackground(this.getBackground()); statusFld.setBorder(BorderFactory.createEmptyBorder()); statusFld.setEditable(false); gameMessagePane = new JPanel(new GridLayout(4,1)); //top, left, bottom, right gameMessagePane.setBorder(BorderFactory.createEmptyBorder(0,0,15,0)); gameMessagePane.add(gamePieceLbl); gameMessagePane.add(gamePieceFld); gameMessagePane.add(statusLbl); gameMessagePane.add(statusFld); sidePane.add(gameMessagePane, BorderLayout.NORTH); } public void setGamePieceText(String text) { gamePieceFld.setText(text); } public void setStatusText(String text) { statusFld.setText(text); } public void setGameEnd() { forfeitBtn.setText("Close Game"); } public void receiveGameForfeit() { if( i_forfeit ) { // register a forfeit ca.send("23" + DELIM + myId + DELIM + "3"); } else { // display message and register as a win JOptionPane.showMessageDialog(this,"Your opponent has forfeited the game.", "Message", JOptionPane.PLAIN_MESSAGE); ca.send("23" + DELIM + myId + DELIM + "1"); } ca.send("4" + DELIM + "0"); } public void sendGameForfeit() { i_forfeit = true; ca.send("25"+DELIM); } /* public static void main(String [] args) { JFrame mainFrame = new JFrame("Reversi Game Room"); ClientApplet ca1 = new ClientApplet(); String p1="Player 1"; String p2="Player 2"; ReversiGameRoom roomPane = new ReversiGameRoom(ca1,p1,p2); roomPane.setGamePieceText("white"); roomPane.setStatusText("It is Player2's turn."); mainFrame.add(roomPane); mainFrame.setSize(700,500); mainFrame.setVisible(true); mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } */ } //end of ReversiGameRoom class
Java
/* * Author: Natalie Schneider * Company: 1186 Entertainment * Date Modified: 3/25/07 * Filename: ClientThread.java */ import java.util.*; import java.io.*; import java.net.*; import java.lang.*; //ClientThread class public class ClientThread extends Thread { public BufferedReader fromClient; //output stream from client public PrintWriter toClient; //input stream to client private Room currRoom; //current room status which Game Lobby or Room user is in private String username; //user's unique username or temporarily unique guest name (Guest##) public boolean isGuest; //whether client is guest private boolean running = true; //for thread public Socket client; //client private Server serverApp = null; // backref to server //constructor public ClientThread(Server server1, Socket c1) { serverApp = server1; //set server client = c1; //set client username = ""; //set username to blank currRoom = null; //set initial room status to null isGuest = false; try { //set input and output streams of clients fromClient = new BufferedReader(new InputStreamReader(client.getInputStream())); toClient = new PrintWriter(new BufferedWriter(new OutputStreamWriter(client.getOutputStream())), true); //send any initialization messages //start this client thread Thread outputThread = new Thread(this); // Thread is to receive strings //outputThread.setPriority(2); outputThread.start(); // from Server } catch(Exception e) { System.out.println("Problem initializing client thread: " + e); } }//end constructor //run function of client thread public void run() { String inMsg; try { //runs until thread dies while(running == true) { //receive messages from client and process accordingly inMsg = receive(); if(inMsg.length() > 0) { serverApp.processMessage(inMsg, this); //process the message } //sleep thread for 100ms Thread.sleep(100); } } catch(Exception e) { System.out.println("Error with thread: " + e); } }//end run //send messages to client public void send(String outMsg) { //send message to client try { System.out.println("Server attempting to send: " + outMsg); toClient.println(outMsg); System.out.println("Server sent: " + outMsg); } catch(Exception e) { System.out.println("Problem sending message to client: " + e); } } //receive messages from client public String receive() { //receive message from client String msg = ""; try { msg = fromClient.readLine(); System.out.println("Server received: " + msg); } catch(Exception e) { System.out.println("Problem receiving message from client: " + e); System.out.println("Removing client from server"); serverApp.removeClosedClient(this); msg = ""; } return msg; } //returns username of client public void setUsername(String uname1) { username = uname1; } //returns int id of current room public void setCurrentRoom(Room rm1) { currRoom = rm1; } //returns username of client public String getUsername() { return username; } //returns int id of current room public Room getCurrentRoom() { return currRoom; } public void leaveRoom() { //remove this client from the room it's in (if it is in one) if(currRoom != null) { currRoom.roomies.remove(this); //update all the users in this room serverApp.sendUpdatedUsersToRoomies(currRoom); } currRoom = null; } public void enterRoom(Room rm1) { //remove this client from the room it's in (if it is in one) leaveRoom(); //add to new room's roomies rm1.roomies.add(this); //set this as current room currRoom = rm1; //update all the users in this room serverApp.sendUpdatedUsersToRoomies(currRoom); } /** Closes the ClientThread */ public void close() { try { System.out.println("Closing the ClientThread."); running = false; fromClient.close(); toClient.close(); client.close(); } catch (Exception e) { System.out.println("Error while closing the ClientThread: " + e); } } }//end ClientThread class
Java
/* * Author: Ben Johnson * Company: 1186 Entertainment * Date Modified: 3/14/07 * Filename: EditProfile.java */ import java.io.*; import java.net.*; import javax.swing.*; import java.awt.event.*; import java.awt.*; import java.util.*; public class Rules extends JFrame implements ActionListener { public ClientApplet CA; JTextArea textArea; JScrollPane content; JButton btnClose; String lobbyName; public Rules(String lobbyName) { //apply the layout int rows = 7; int cols = 2; JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT)); int top, left, bottom, right; top = left = bottom = right = 20; panel.setBorder(BorderFactory.createEmptyBorder (top,left,bottom,right)); //initialize all the labels and fields String rulesText = "These are the Rules for Reversi\n\n...\n...\n...\n..."; textArea = new JTextArea(rulesText); content = new JScrollPane(textArea); panel.add(content); add(panel); panel.setVisible(true); setSize(500,300); setVisible(true); }//end constructor public void actionPerformed(ActionEvent e1) { JButton button=(JButton)e1.getSource(); //get the source of the event if(button.equals(btnClose)){this.dispose();} }//end of actionPerformed() }//end of class
Java