code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/SearchPreferencesActivity.java
Java
asf20
951
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/CmisApp.java
Java
asf20
2,835
/* * 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; } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ServerEditActivity.java
Java
asf20
5,832
/* * 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); } } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/CmisItemCollectionAdapter.java
Java
asf20
4,287
/* * 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(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/DocumentDetailsActivity.java
Java
asf20
6,587
/* * 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(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/SavedSearchActivity.java
Java
asf20
5,279
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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/CustomDialogActivity.java
Java
asf20
898
/* * 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)); } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/DownloadAdapter.java
Java
asf20
4,121
/* * 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(); } } }); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/AboutResourcesActivity.java
Java
asf20
1,701
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))); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/GridAdapter.java
Java
asf20
1,991
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/model/Server.java
Java
asf20
2,192
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/model/Favorite.java
Java
asf20
1,324
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/model/Search.java
Java
asf20
1,533
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/FilterPrefs.java
Java
asf20
1,879
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/CmisFilterActivity.java
Java
asf20
944
/* * 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)); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/SavedSearchAdapter.java
Java
asf20
2,636
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/SearchSchema.java
Java
asf20
2,594
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/FavoriteDAO.java
Java
asf20
4,023
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/ServerSchema.java
Java
asf20
2,837
/* * 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); */ }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/DAO.java
Java
asf20
872
/* * 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); } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/Database.java
Java
asf20
2,092
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/ServerDAO.java
Java
asf20
3,754
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/FavoriteSchema.java
Java
asf20
2,230
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/database/SearchDAO.java
Java
asf20
3,973
/* * 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); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/FileAdapter.java
Java
asf20
4,396
/* * 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(); } } }); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/AboutDevActivity.java
Java
asf20
3,068
/* * 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; } } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/DownloadProgressActivity.java
Java
asf20
4,893
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/AboutActivity.java
Java
asf20
2,159
/* * 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; } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/ServerInfoActivity.java
Java
asf20
2,738
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(); } }
01001ziegler-domea-cmis
src/de/fmaul/android/cmis/OpenFileActivity.java
Java
asf20
766
/* * 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; } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/FakePreferences.java
Java
asf20
1,814
/* * 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(); } } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/DefaultBmsHttpClientTest.java
Java
asf20
10,730
/* * 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(); } } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/DefaultBmsLowLevelClientTest.java
Java
asf20
21,042
/* * 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; } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/TestInjector.java
Java
asf20
2,417
/* * 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; } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/HomeScreenActivityTest.java
Java
asf20
5,774
/* * 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); } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/BmsClientTest.java
Java
asf20
11,426
/* * 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()); } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/ScanRegistryTest.java
Java
asf20
2,271
/* * 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(); } }
10murphy-beepmystuff
beepmystuff/tests/src/com/google/beepmystuff/DummyBmsHttpClient.java
Java
asf20
1,111
/* * 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; } }
10murphy-beepmystuff
beepmystuff/src/com/google/zxing/integration/android/IntentResult.java
Java
asf20
1,288
/* * 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); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/zxing/integration/android/IntentIntegrator.java
Java
asf20
9,960
/* * 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; } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsTransportException.java
Java
asf20
1,219
/* * 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); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/RecentlyScannedActivity.java
Java
asf20
3,471
/* * 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; }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsHttpClient.java
Java
asf20
1,499
/* * 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) { } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsClient.java
Java
asf20
10,660
/* * 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); } } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/ScanRegistryAdapter.java
Java
asf20
2,095
/* * 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); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/SettingsActivity.java
Java
asf20
1,048
/* * 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)); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/ManualEntryActivity.java
Java
asf20
3,240
/* * 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(); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/SharedPreferences.java
Java
asf20
3,727
/* * 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; } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsApiException.java
Java
asf20
2,371
/* * 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(); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsException.java
Java
asf20
1,159
/* * 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); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/NetworkService.java
Java
asf20
6,948
/* * 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()); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/DefaultBmsHttpClient.java
Java
asf20
5,133
/* * 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(); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/NetworkThread.java
Java
asf20
6,070
/* * 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(); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/LoginActivity.java
Java
asf20
5,430
/* * 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); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsClientException.java
Java
asf20
1,082
/* * 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); }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/Preferences.java
Java
asf20
1,357
/* * 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); } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/HomeScreenActivity.java
Java
asf20
11,011
/* * 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); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/ItemDetailsActivity.java
Java
asf20
3,070
/* * 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(); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/Injector.java
Java
asf20
6,759
/* * 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); } } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/DefaultBmsLowLevelClient.java
Java
asf20
15,573
/* * 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; }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/BmsLowLevelClient.java
Java
asf20
2,563
/* * 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; } }
10murphy-beepmystuff
beepmystuff/src/com/google/beepmystuff/ScanRegistry.java
Java
asf20
14,499
@echo off Title Don's Applet Signer :sign color 9 echo. echo. echo Please generate a key with the alias 1186se before running echo See the Google Doc "1186 Project - How to Run, etc." for more details. echo ~Don echo. echo. rem @echo on javac *.java @echo off if errorlevel 1 goto error color a REM echo Please Ensure Compilation Success REM pause REM @echo on mkdir Jar mkdir Jar\oracle rem @echo on xcopy .\oracle .\Jar\oracle /s/e/I/y xcopy .\files .\Jar\files /s/e/I/y @echo off copy *.wav ".\Jar" copy *.class ".\Jar" copy classes12.zip ".\Jar" cd jar color a jar -cvf applet.jar . rem jar -cuvf applet.jar *.class rem @echo on color e jarsigner applet.jar 1186se if errorlevel 1 goto error2 cd .. copy Jar\applet.jar applet.jar rem del /S/Q Jar rd /s/q Jar color 9 echo. echo. echo Applet Successfully Signed echo. pause goto end :error echo. echo. color c echo Compilation Failed echo Please Correct Errors and run again echo. pause goto end :error2 :error echo. echo. color c echo Signing Failed. Invalid Password, or key not present echo Please Correct Errors and run again echo. pause goto end :end pause cls goto sign
1186se
trunk/Jar and Sign.bat
Batchfile
gpl2
1,222
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
1186se
trunk/Script.java
Java
gpl2
3,179
<html> <body> <center> <applet code=ClientApplet.class archive="applet.jar" width="700" height="500"> Your browser does not support the applet tag. </applet> </center> </body> </html>
1186se
trunk/Applet.html
HTML
gpl2
203
java -cp .;.\classes12.zip sqlutil se18 l13z16o4
1186se
trunk/sqlutil.bat
Batchfile
gpl2
48
/* * 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
1186se
trunk/Login.java
Java
gpl2
4,810
interface Forfeitable { public void receiveForfeit(); public void sendForfeit(); }
1186se
trunk/Forfeitable.java
Java
gpl2
88
@echo off color 9 Title Compile All :compile @echo on javac -classpath .;.\classes12.zip DB.java javac -d . *.java @echo off echo. echo. echo. echo Compilations completed. pause cls goto compile
1186se
trunk/Compile All.bat
Batchfile
gpl2
211
/* * 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"); } }
1186se
trunk/ClientApplet.java
Java
gpl2
11,584
/** * @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(); } } }
1186se
trunk/GameSelect.java
Java
gpl2
3,504
@echo off color 9 Title Compile All :compile @echo on javac -classpath .;.\classes12.zip DB.java javac -d . *.java @echo off echo. echo. echo. echo Compilations completed. @echo off Title Don's Applet Signer color 9 echo. echo. echo Please generate a key with the alias 1186se before running echo See the Google Doc "1186 Project - How to Run, etc." for more details. echo ~Don echo. echo. rem @echo on javac *.java @echo off if errorlevel 1 goto error color a REM echo Please Ensure Compilation Success REM pause REM @echo on mkdir Jar mkdir Jar\oracle rem @echo on xcopy .\oracle .\Jar\oracle /s/e/I/y xcopy .\files .\Jar\files /s/e/I/y @echo off copy *.wav ".\Jar" copy *.class ".\Jar" copy classes12.zip ".\Jar" cd jar color a jar -cvf applet.jar . rem jar -cuvf applet.jar *.class rem @echo on color e jarsigner applet.jar 1186se if errorlevel 1 goto error2 cd .. copy Jar\applet.jar applet.jar rem del /S/Q Jar rd /s/q Jar color 9 echo. echo. echo Applet Successfully Signed echo. pause goto end :error echo. echo. color c echo Compilation Failed echo Please Correct Errors and run again echo. pause goto end :error2 :error echo. echo. color c echo Signing Failed. Invalid Password, or key not present echo Please Correct Errors and run again echo. pause goto end :end pause cls goto compile
1186se
trunk/Compile Jar Sign.bat
Batchfile
gpl2
1,405
:: this file removes, then recreates all javadoc webpages in a folder named doc rmdir /S /Q doc mkdir doc javadoc -d .\doc\ *.java @echo Successfully created documentation for all java files! @PAUSE doc\index.html CLS
1186se
trunk/doc.bat
Batchfile
gpl2
224
/* * 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
1186se
trunk/EditProfile.java
Java
gpl2
6,952
@echo off @color 2 title Game Server: 1186 Entertainment echo Starting Game Server... :top @echo on java Server @echo off cls echo. echo. echo. echo Restarting Game Server... rem pause goto top
1186se
trunk/Run Server.bat
Batchfile
gpl2
209
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); }*/ }
1186se
trunk/MyPanel.java
Java
gpl2
6,389
//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; } }
1186se
trunk/PlayerInfo.java
Java
gpl2
611
/* * 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
1186se
trunk/Register.java
Java
gpl2
5,464
interface Chatable { public void sendMsg(String text); public void receiveMsg(String sender, String text); }
1186se
trunk/Chatable.java
Java
gpl2
114
@color 9 @title Applet Runner: 1186 Entertainment :run @echo Viewing Applet... appletviewer Applet.html pause goto run
1186se
trunk/Run Applet.bat
Batchfile
gpl2
126
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Serial Foods - WebGames</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" href="files/main_style.css" type="text/css" /> <script> function goto(place) { //alert("Frame source = "+document.getElementById("contentframe").src); if(confirm("Are you sure that you want to navigate away from the game?")) { document.getElementById("contentframe").src = place; } } </script> </head> <body> <div id="wrapper"> <div id="header"> <div id="navigation"> <ul> <li><img src="logo_small.bmp"></li> <li><a style="cursor:pointer;cursor:hand;" onclick="javascript:goto('home.html')">Home Page</a></li> <li><a style="cursor:pointer;cursor:hand;" onclick="javascript:goto('how_to.html')">How To</a></li> <!--<li><a href="home.html" target="stuff">Home Page</a></li>--> <!--<li><a href="login.html" target="stuff">login</a></li>--> <!--<li><a href="how_to.html" target="stuff">How To</a></li>--> </ul> </div> <h1><a href="index2.html">Serial Foods</a></h1> </div> <div id="content"> <iframe id="contentframe" name="stuff" src="home.html" width="746px" height="520px"></iframe> </div> <div id="footer"><br /> <span>Website created by 1186 Entertainment</span> </div> </div> </body> </html>
1186se
trunk/index2.html
HTML
gpl2
1,498
<head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>How to play</title> </head> <body> <h1>How to play:</h1> <h2>Setp 1: Login</h2> <img src="files/login.jpg"><br /> <ol> <li> Login - Login if you have a username and password. <li> Guest - Play as a guest if you want to play a quick game. <li> Register - Get a username and password so your statistics are saved. </ol> <h2>Step 2: Select a game</h2> <img src="files/select.jpg"><br /> <ol> <li> Logout - Log out of the system. <li> Reversi - Play this game of flipping black and white pieces. <li> * TicTackToe - A childrens game that all can enjoy. <li> * Hangman - A word guessing game with mortal consequences. </ol> <p>* this denotes that the game is not yet implemented</p> <h2>Step 3: Game Lobby</h2> <img src="files/lobby.jpg"><br /> <ol> <li> Logout - Log out of the system. <li> Select a Different Game - Go back to the game select screen. <li> Edit Profile - Edit your personal information here. <li> Game Rules - Get the specific game rules for your game. <li> View Profile - Views personal information for selected player. <li> Challenge Player - Challenges the slected player to the current game. <li> Chat Window - This chat window allows you to chat with others in the room. <li> Online Users - This window shows the current players in the game room. <li> Top Players - Shows the top scoring players for the current game. </ol> <h2>Step 4: Play Game</h2> <p>After you challenge a player and they accept, enjoy playing your game. </p> <p>Note: see specific game rules for information on how to play each game.</p> </body>
1186se
trunk/how_to.html
HTML
gpl2
1,769
//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); } }
1186se
trunk/GameStats.java
Java
gpl2
389
/* 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
1186se
trunk/ReversiGameRoom.java
Java
gpl2
3,850
/* * 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
1186se
trunk/ClientThread.java
Java
gpl2
4,418
/* * 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
1186se
trunk/Rules.java
Java
gpl2
1,297
<html> <head> <meta http-equiv="Content-Language" content="en-us"> <meta http-equiv="Content-Type" content="text/html; charset=windows-1252"> <title>Reversi Rules</title> <script type="text/javascript"> //window.resizeTo(300,300); function closeRules() { window.open('','_parent',''); window.close(); } </script> </head> <body> <p><img border="0" src="files/title2.jpg" width="400" height="103"></p> <p>How to play:</p> <p>Reversi, also known as Othello is a popular board game that is easy to learn, but hard to master.</p> <p>Basic play in Reversi is between two players using chips that have different colors, normally black and white, on each side. </p> <p>The object of the game is to have more chips showing your color than your opponent's at the end of the game.</p> <p>To do this you have to trap your opponents chips between two of your chips as you place them on the board.</p> <p>All trapped chips get flipped to the other color.</p> <p>&nbsp;</p> <p>This is an example starting board.&nbsp; </p> <p><img border="0" src="files/board1.jpg" width="400" height="400"></p> <p>&nbsp;</p> <p>The black player moves first and decides to trap the top left white chip by placing a chip above it.</p> <p>&nbsp;</p> <p><img border="0" src="files/board2.jpg" width="400" height="400"></p> <p>&nbsp;</p> <p>Doing so causes the white chip to flip resulting in the above board</p> <p>Now the white player decides to place a chip to the left of the top-most black chip.</p> <p>&nbsp;</p> <p><img border="0" src="files/board3.jpg" width="400" height="400"></p> <p>That leads to the board looking like this.</p> <p>&nbsp;</p> <p>Play continues until all the chips are flipped to one color, or both players run out of viable moves.</p> <p>Though simple in design, Reversi has a lot of strategy involved and trying to trap the most chips each turn, is not always the best route.</p> <p>The best way to learn Reversi is to play an actual game, so sign up for an account now! </p> <p>&nbsp;</p> <input type=button value='Close' onclick='closeRules()'> <p>&nbsp;</p> </body> </html>
1186se
trunk/Reversi_Rules.html
HTML
gpl2
2,144
/* CoE 1186 1186 Entertainment Reversi Game ReversiGameBoard.java ----------------------------------------- ReversiGameBoard - Abstract or Concrete: Concrete - List of Superclasses: GameBoard, MyPanel, JPanel - List of Subclasses: N/A - Purpose: Java Reversi Game - Collaborations: Loaded by the ReversiGameRoom, Send Messages to server through ClientApplet --------------------- - Attributes: --------------------- - Operations: --------------------- - Constraints: N/A ----------------------------------------- */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.imageio.*; import java.util.Random; public class ReversiGameBoard extends MyPanel { ReversiGameManager gm; ClientApplet ca; ReversiGameRoom room; String DELIM = "&"; int player1, player2, r; ReversiGamePiece [][] pieces; /*public ReversiGameBoard() { ReversiGamePiece [][] pieces = new ReversiGamePiece[8][8]; setPreferredSize(new Dimension(400,400)); setBackgroundPosition(MyPanel.STRETCHED); setBackgroundImage("files/board.jpg"); setLayout(new GridLayout(8,8)); gm = new ReversiGameManager(pieces,this); for (int i = 0 ; i < 8 ; i++ ) { for (int j = 0; j < 8 ; j++ ) { pieces[i][j] = new ReversiGamePiece(); pieces[i][j].addMouseListener(gm); add(pieces[i][j]); } } initialize(pieces); }*/ public ReversiGameBoard(ClientApplet ca, ReversiGameRoom room, int player1, int player2) { this.ca = ca; this.room = room; this.player1 = player1; this.player2 = player2; pieces = new ReversiGamePiece[8][8]; setPreferredSize(new Dimension(400,400)); //setBackgroundPosition(MyPanel.STRETCHED); //setBackgroundImage("files/board.jpg"); setLayout(new GridLayout(8,8)); gm = new ReversiGameManager(pieces,this); for (int i = 0 ; i < 8 ; i++ ) { for (int j = 0; j < 8 ; j++ ) { pieces[i][j] = new ReversiGamePiece(ca); pieces[i][j].addMouseListener(gm); add(pieces[i][j]); } } initialize(pieces); } public void initialize(ReversiGamePiece [][] pieces) { pieces[3][3].makeMove(ReversiGamePiece.WHITE); pieces[3][4].makeMove(ReversiGamePiece.BLACK); pieces[4][4].makeMove(ReversiGamePiece.WHITE); pieces[4][3].makeMove(ReversiGamePiece.BLACK); Random generator = new Random(); r = generator.nextInt(1000); ca.send("22" + DELIM + "01" + DELIM + r); } public void processMove( String msg) { String[] msgParts = msg.split(DELIM); int msgId = Integer.parseInt(msgParts[1]); switch(msgId) { case 01: if (r > Integer.parseInt(msgParts[2])) { gm.mycolor = ReversiGamePiece.BLACK; room.setGamePieceText("Black"); room.setStatusText("Waiting for other player to go"); } if (r < Integer.parseInt(msgParts[2])) { gm.mycolor = ReversiGamePiece.WHITE; gm.turn = true; room.setGamePieceText("White"); room.setStatusText("It\'s your turn."); } System.out.println("" + r + " " + Integer.parseInt(msgParts[2])); break; case 02: gm.checkMove(pieces[Integer.parseInt(msgParts[3])][Integer.parseInt(msgParts[4])],Integer.parseInt(msgParts[2]),gm.mycolor); room.setStatusText("It\'s your turn."); gm.turn = true; gm.checkBoard(gm.mycolor); break; case 03: room.setStatusText("It\'s your turn."); gm.turn = true; gm.checkBoard(gm.mycolor); break; } } } class ReversiGameManager implements MouseListener { static int moving; boolean turn = false; int mycolor,opposite; ReversiGamePiece [][] pieces; ReversiGameBoard board; public ReversiGameManager(ReversiGamePiece [][] pieces, ReversiGameBoard board) { this.pieces = pieces; this.board = board; } public void mouseClicked(MouseEvent e) { ReversiGamePiece theEventer = (ReversiGamePiece) e.getSource(); if(theEventer.current == 0) { if (turn) { if(mycolor == ReversiGamePiece.WHITE) opposite = ReversiGamePiece.BLACK; else opposite = ReversiGamePiece.WHITE; if(checkMove(theEventer,mycolor,opposite)) { int x, y; for(int i=0;i<8;i++) { for (int j=0;j<8 ;j++) { if(pieces[i][j] == theEventer) { x = i; y = j; board.ca.send("22" + board.DELIM + "02" + board.DELIM+ mycolor + board.DELIM + x + board.DELIM + y); board.room.setStatusText("Waiting for other player to go"); turn = false; if(evalBoard(mycolor) == 3) checkBoard(mycolor); } } } } } } } public void checkBoard(int player) { int black = 0; int white = 0; switch(evalBoard(player)) { case 1: break; case 2: JOptionPane.showMessageDialog(board, "No Remaining Moves\nPassing Turn", "Message", JOptionPane.ERROR_MESSAGE); board.room.setStatusText("Waiting for other player to go"); board.ca.send("22" + board.DELIM + "03"); turn = false; break; case 3: for(int i=0;i<8;i++) { for (int j=0;j<8 ;j++) { if(pieces[i][j].current == ReversiGamePiece.BLACK){black++;} if(pieces[i][j].current == ReversiGamePiece.WHITE){white++;} } } if (black > white) { if(mycolor == ReversiGamePiece.BLACK) { JOptionPane.showMessageDialog(board, "You Win!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE); turn = false; board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "1"); board.ca.send("4" + board.DELIM + "0"); } else { JOptionPane.showMessageDialog(board, "You Lose!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE); turn = false; board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "2"); board.ca.send("4" + board.DELIM + "0"); } } else if (white > black) { if(mycolor == ReversiGamePiece.WHITE) { JOptionPane.showMessageDialog(board, "You Win!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE); turn = false; board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "1"); board.ca.send("4" + board.DELIM + "0"); } else { JOptionPane.showMessageDialog(board, "You Lose!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE); turn = false; board.ca.send("23" + board.DELIM + board.player1 + board.DELIM + "2"); board.ca.send("4" + board.DELIM + "0"); } } else if (white == black) { JOptionPane.showMessageDialog(board, "It is a Tie!!!", "Game Over", JOptionPane.INFORMATION_MESSAGE); turn = false; board.ca.send("4" + board.DELIM + "0"); } break; } } private int evalBoard(int player) { int opposite; if(player == ReversiGamePiece.WHITE) opposite = ReversiGamePiece.BLACK; else opposite = ReversiGamePiece.WHITE; for (int i = 0 ; i < 8 ; i++ ) { for (int j = 0; j < 8 ; j++ ) { if(pieces[i][j].current == 0) { boolean moveleft = false; moveleft = checkLeft(i,j-1,player,opposite,true,true) || moveleft; moveleft = checkUpLeft(i-1,j-1,player,opposite,true,true) || moveleft; moveleft = checkUp(i-1,j,player,opposite,true,true) || moveleft; moveleft = checkUpRight(i-1,j+1,player,opposite,true,true) || moveleft; moveleft = checkRight(i,j+1,player,opposite,true,true) || moveleft; moveleft = checkDownRight(i+1,j+1,player,opposite,true,true) || moveleft; moveleft = checkDown(i+1,j,player,opposite,true,true) || moveleft; moveleft = checkDownLeft(i+1,j-1,player,opposite,true,true) || moveleft; if(moveleft) { return 1; } } } } for (int i = 0 ; i < 8 ; i++ ) { for (int j = 0; j < 8 ; j++ ) { if(pieces[i][j].current == 0) { boolean moveleft = false; moveleft = checkLeft(i,j-1,opposite,player,true,true) || moveleft; moveleft = checkUpLeft(i-1,j-1,opposite,player,true,true) || moveleft; moveleft = checkUp(i-1,j,opposite,player,true,true) || moveleft; moveleft = checkUpRight(i-1,j+1,opposite,player,true,true) || moveleft; moveleft = checkRight(i,j+1,opposite,player,true,true) || moveleft; moveleft = checkDownRight(i+1,j+1,opposite,player,true,true) || moveleft; moveleft = checkDown(i+1,j,opposite,player,true,true) || moveleft; moveleft = checkDownLeft(i+1,j-1,opposite,player,true,true) || moveleft; if(moveleft) { return 2; } } } } return 3; } public boolean checkMove(ReversiGamePiece MadeMove, int current, int opposite) { int x=0, y=0; boolean legal = false; for(int i=0;i<8;i++) { for (int j=0;j<8 ;j++) { if(pieces[i][j] == MadeMove) { x = i; y = j; } } } legal = checkLeft(x,y-1,current,opposite,true,false) || legal; legal = checkUpLeft(x-1,y-1,current,opposite,true,false) || legal; legal = checkUp(x-1,y,current,opposite,true,false) || legal; legal = checkUpRight(x-1,y+1,current,opposite,true,false) || legal; legal = checkRight(x,y+1,current,opposite,true,false) || legal; legal = checkDownRight(x+1,y+1,current,opposite,true,false) || legal; legal = checkDown(x+1,y,current,opposite,true,false) || legal; legal = checkDownLeft(x+1,y-1,current,opposite,true,false) || legal; if(legal) { MadeMove.makeMove(current); board.repaint(); return(true); } else { return(false); } } private boolean checkLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkLeft(x,y-1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkUpLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkUpLeft(x-1,y-1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkUp(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkUp(x-1,y,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkUpRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkUpRight(x-1,y+1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkRight(x,y+1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkDownRight(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkDownRight(x+1,y+1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkDown(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkDown(x+1,y,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } private boolean checkDownLeft(int x, int y, int current,int opposite, boolean firstrun, boolean evaluating) { if (x >= 0 && x <8) { if(y >= 0 && y <8) { if(pieces[x][y].current==opposite) { if(checkDownLeft(x+1,y-1,current,opposite,false,evaluating)) { if(!evaluating) pieces[x][y].flipPiece(); return true; } else { return false; } } else if(pieces[x][y].current == current) { if (firstrun) { return false; } else { return true; } } else { return false; } } else { return false; } } else { return false; } } public void mousePressed(MouseEvent e){} public void mouseReleased(MouseEvent e){} public void mouseEntered(MouseEvent e){} public void mouseExited(MouseEvent e){} } class ReversiGamePiece extends JPanel implements Runnable { Image[] picture = new Image[9]; int totalPictures = 0; public final static int BLACK = 1; public final static int WHITE = 7; int current = 0; int temp = 0; int go = 0; Thread runner; int pause = 80; String[] imageNames = { "files/0.gif", "files/1.gif", "files/2.gif", "files/3.gif", "files/4.gif", "files/5.gif", "files/6.gif", "files/7.gif" }; public ReversiGamePiece(ClientApplet ca) { super(); Toolkit kit = Toolkit.getDefaultToolkit(); for (int i = 0; i < imageNames.length; i++) { picture[i] = ca.getImage(ca.getDocumentBase(),imageNames[i]); } runner = new Thread(this); } public void makeMove(int current) { this.current = current; temp = current; repaint(); } public void flipPiece() { temp = current; if(current == BLACK){current = WHITE;} else if(current == WHITE){current = BLACK;} runner = new Thread(this); runner.start(); } public void paintComponent(Graphics screen) { Graphics2D screen2D = (Graphics2D) screen; if (picture[temp] != null) { screen2D.drawImage(picture[temp], 0, 0, this); } } public void start() { if (runner == null) { runner = new Thread(this); runner.start(); } } public void run() { Thread thisThread = Thread.currentThread(); int running = 1; if (temp < current) { while (running == 1) { temp++; repaint(); if (temp == current) { running = 0; } try { Thread.sleep(pause); } catch (InterruptedException e) { } } } if (temp > current) { while (running == 1) { temp--; repaint(); if (temp == current) { running = 0; } try { Thread.sleep(pause); } catch (InterruptedException e) { } } } stop(); } public void stop() { if (runner != null) { runner = null; } } }
1186se
trunk/ReversiGameBoard.java
Java
gpl2
18,510
/* This simple extension of the java.awt.Frame class contains all the elements necessary to act as the main window of an application. */ import java.sql.*; import oracle.sql.*; import oracle.jdbc.driver.*; import java.awt.*; public class sqlutil extends Frame { public Connection c = null; public Statement stmt = null; public sqlutil(String userid, String pwd) { try { String connectString = "jdbc:oracle:thin:@(description=(address=(host=ragnall.ee.pitt.edu)(protocol=tcp)(port=1521))(connect_data=(sid=J7)))"; DriverManager.registerDriver(new OracleDriver()); c = DriverManager.getConnection(connectString,userid,pwd); c.setAutoCommit(true); stmt = c.createStatement(); } catch(Exception e) { System.out.println(e.getMessage()); System.exit(1); } // This code is automatically generated by Visual Cafe when you add // components to the visual environment. It instantiates and initializes // the components. To modify the code, only use code syntax that matches // what Visual Cafe can generate, or Visual Cafe may be unable to back // parse your Java file into its visual environment. //{{INIT_CONTROLS setLayout(null); setBackground(java.awt.Color.lightGray); setSize(492,300); setVisible(false); add(queryField); queryField.setBounds(12,12,384,24); queryButton.setLabel("Query"); add(queryButton); queryButton.setBounds(408,12,72,24); add(executeField); executeField.setBounds(12,48,384,24); executeButton.setLabel("Execute"); add(executeButton); executeButton.setBounds(408,48,72,24); resultArea.setEditable(false); add(resultArea); resultArea.setFont(new Font("MonoSpaced", Font.PLAIN, 10)); resultArea.setBounds(12,84,468,204); setTitle("DataBase Application"); //}} //{{INIT_MENUS //}} //{{REGISTER_LISTENERS SymWindow aSymWindow = new SymWindow(); this.addWindowListener(aSymWindow); SymAction lSymAction = new SymAction(); queryButton.addActionListener(lSymAction); executeButton.addActionListener(lSymAction); //}} } public sqlutil(String title, String userid, String pwd) { this(userid,pwd); setTitle(title); } /** * Shows or hides the component depending on the boolean flag b. * @param b if true, show the component; otherwise, hide the component. * @see java.awt.Component#isVisible */ public void setVisible(boolean b) { if(b) { setLocation(50, 50); } super.setVisible(b); } static public void main(String args[]) { try { //Create a new instance of our application's frame, and make it visible. (new sqlutil(args[0],args[1])).setVisible(true); } catch (Throwable t) { System.err.println(t); t.printStackTrace(); //Ensure the application exits with an error condition. System.exit(1); } } public void addNotify() { // Record the size of the window prior to calling parents addNotify. Dimension d = getSize(); super.addNotify(); if (fComponentsAdjusted) return; // Adjust components according to the insets setSize(getInsets().left + getInsets().right + d.width, getInsets().top + getInsets().bottom + d.height); Component components[] = getComponents(); for (int i = 0; i < components.length; i++) { Point p = components[i].getLocation(); p.translate(getInsets().left, getInsets().top); components[i].setLocation(p); } fComponentsAdjusted = true; } // Used for addNotify check. boolean fComponentsAdjusted = false; //{{DECLARE_CONTROLS java.awt.TextField queryField = new java.awt.TextField(); java.awt.Button queryButton = new java.awt.Button(); java.awt.TextField executeField = new java.awt.TextField(); java.awt.Button executeButton = new java.awt.Button(); java.awt.TextArea resultArea = new java.awt.TextArea(); //}} //{{DECLARE_MENUS //}} class SymWindow extends java.awt.event.WindowAdapter { public void windowClosing(java.awt.event.WindowEvent event) { Object object = event.getSource(); if (object == sqlutil.this) sqlutil_WindowClosing(event); } } void sqlutil_WindowClosing(java.awt.event.WindowEvent event) { // to do: code goes here. this.setVisible(false); try { stmt.close(); c.close(); } catch(SQLException sqle) { } System.exit(0); } class SymAction implements java.awt.event.ActionListener { public void actionPerformed(java.awt.event.ActionEvent event) { Object object = event.getSource(); if (object == queryButton) queryButton_ActionPerformed(event); else if (object == executeButton) executeButton_ActionPerformed(event); } } void queryButton_ActionPerformed(java.awt.event.ActionEvent event) { // to do: code goes here. ResultSet r = null; boolean success = false; int columns = 0; try { r = stmt.executeQuery(queryField.getText()); columns = r.getMetaData().getColumnCount(); String s = ""; for(int i=0; i<columns; i++) { String t = r.getMetaData().getColumnName(i+1); int size = r.getMetaData().getColumnDisplaySize(i+1); if(t.length() < size) { int l = t.length(); for(int j=0; j<size-l; j++) { t = t + " "; } } s = s + t; if(i != (columns-1)) s = s + " "; } success = true; resultArea.append(s + '\n'); /*for(int i=0; i<s.length(); i++) resultArea.append("-"); resultArea.append("\n");*/ } catch(SQLException sqle) { resultArea.append(sqle.getMessage() + "\n\n"); } if(success) { String s = ""; try { while(r.next()) { for(int i=0; i<columns; i++) { String t = r.getString(i+1); int size = r.getMetaData().getColumnDisplaySize(i+1); if(t.length() < size){ int l = t.length(); for(int j=0; j<size-l; j++){ t = t + " "; } } s = s + t; if(i != (columns-1)) s = s + " "; } s = s + '\n'; } resultArea.append(s + '\n'); } catch(SQLException sqle) { resultArea.append(sqle.getMessage() + "\n\n"); } } //queryButton_ActionPerformed_Interaction1(event); } void queryButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event) { try { // queryField Clear the text for TextField queryField.setText(""); } catch (Exception e) { } } void executeButton_ActionPerformed(java.awt.event.ActionEvent event) { // to do: code goes here. boolean result = false; try { result = stmt.execute(executeField.getText()); if(result) { //ResultSet resultArea.append("ResultSet returned\n\n"); } else { //getUpdateCount resultArea.append("Modified " + stmt.getUpdateCount() + " record(s)\n\n"); } } catch(SQLException sqle) { resultArea.append(sqle.getMessage() + "\n\n"); } //executeButton_ActionPerformed_Interaction1(event); } void executeButton_ActionPerformed_Interaction1(java.awt.event.ActionEvent event) { try { // executeField Clear the text for TextField executeField.setText(""); } catch (Exception e) { } } }
1186se
trunk/sqlutil.java
Java
gpl2
7,683
/* * Author: Natalie Schneider * Company: 1186 Entertainment * Date Modified: 4/1/07 * Filename: Server.java */ import java.util.*; import java.io.*; import java.net.*; import java.lang.*; import java.sql.*; import java.text.SimpleDateFormat; /** Application that runs on the server and relays messages between clients This is a thin server and only handles the passing of messages and Database actions */ public class Server { public static final int REVERSI = 0; public static final int MSG_VALIDATE_USER = 1; public static final int MSG_REGISTER_USER = 3; //public static final int MSG_ public ArrayList<ClientThread> clients; public ArrayList<Room> rooms; public int PORT = 33456; public DB db; public static String DELIM = "&"; public static String dbname = "se18"; public static String dbpwd = "l13z16o4"; public static String[] GameTypes = {"Reversi"}; /** default constructor */ public Server() { //initializes the database and lobby rooms of the server SetupServer(); //server socket ServerSocket s; try { //connects to server given at command line s = new ServerSocket(PORT); //client Socket c = new Socket(); try { //keeps looping through until thread dies while(true) { //get client, blocks until a connection occurs c = s.accept(); System.out.println("Accepted "+ c); //create new client thread and add to clients clients.add(new ClientThread(this, c)); }//end while } catch(Exception e) { System.out.println("ERROR with server: " + e); } finally { //will always close connection System.out.println("Closing server connection ...."); s.close(); }//end try-finally } catch(Exception e) { System.out.println("Problem connecting to server: " + e); }//end try-catch }//end constructor /** sets up the server for service of the games */ public void SetupServer() { int i; //connect to the database try { db = new DB(); db.connect(dbname, dbpwd); } catch(Exception e) { System.out.println("ERROR: " + e); System.out.println("Could not connect to database."); } clients = new ArrayList<ClientThread>(); rooms = new ArrayList<Room>(); //initialize lobbies //add Reversi lobby i = 0; rooms.add(i, new Room(true, GameTypes[i])); }//end SetupServer() /** waits for messages from clients and responds accordingly to each message */ public void processMessage(String message, ClientThread c1) { String delimit = "DON's DELIMITER"; //message.replace(DELIM, delimit); String[] msgParts = message.split(DELIM); System.out.println(message); for (int i = 0; i < msgParts.length; i++) { System.out.println(msgParts[i]); } int msgId = Integer.parseInt(msgParts[0]); switch(msgId) { case 1: //request user validation (log in) validateUser(msgParts, c1); break; case 3: //request user registration (registration) registerUser(msgParts, c1); break; case 4: //selected game lobby selectLobby(msgParts, c1); break; case 6: //request profile information of given user id viewProfile(msgParts, c1); break; case 8: //log out from this username and set them to no room c1.setUsername(""); c1.leaveRoom(); break; case 10: //send challenge from challenger to challengee sendChallenge(msgParts, message); break; case 11: //process response from challenger to accept or decline challenge procChallengeResponse(msgParts, message, c1); break; case 13: //guest log in, create new guest username createGuest(msgParts, c1); break; case 15: //do request for current contents of editable profile fields sendEditableProfile(c1); break; case 17: //edit profile editProfile(msgParts, c1); break; case 18: //request update for current game lobby users sendUpdateUsers(c1); break; case 20: //request update for top rankings sendUpdateRanks(c1); break; case 22: //send made move to opponent sendMove(message, c1); break; case 23: //update game results in database resolveEndOfGame(c1,msgParts); break; case 24: //send chat text message to everyone in this room sendTextMsg(message, c1); break; case 25: sendForfeitMsg(message, c1); break; case 27: //kill this ClientThread removeClosedClient(c1); break; default: //unknown message //throw an error System.out.println("Unknown message type received"); break; }//end select case }//end wait for message //sends return message to client whether username and password are valid private void validateUser(String[] mparts, ClientThread c1) { String uname = ""; String pwd = ""; boolean isVal = false; String retMsg = ""; try { if(mparts.length >= 3) { uname = mparts[1]; pwd = mparts[2]; //if logged in already, log out the other one logOutOtherSelf(uname); isVal = db.validateUser(uname, pwd); if(isVal) { c1.setUsername(uname); } } } catch(Exception e) { System.out.println("Problem accessing database: " + e); } //send type 2 message back to client with //whether username and password are valid if(isVal) { retMsg = "2" + DELIM + "valid"; } else { retMsg = "2" + DELIM + "invalid"; } c1.send(retMsg); }//end validateUser //if logged in already, log out the other one private void logOutOtherSelf(String uname) { ClientThread c1 = null; if(isLoggedIn(uname)) { System.out.println("Logged out other " + uname); c1 = getClient(uname); //notify user they are being logged out c1.send("26" + DELIM); //reset their username and remove them from their current room c1.setUsername(""); c1.leaveRoom(); } } //check if username already logged in private boolean isLoggedIn(String uname) { boolean taken = false; for(int i = 0; i < clients.size(); i++) { if(((clients.get(i)).getUsername()).equals(uname)) { taken = true; } } return taken; } //get client by username private ClientThread getClient(String uname) { ClientThread c1 = null; for(int i = 0; i < clients.size(); i++) { if(((clients.get(i)).getUsername()).equals(uname)) { c1 = clients.get(i); } } return c1; } //registers a user in the database and sends a return message whether it was successful private void registerUser(String[] mparts, ClientThread c1) { //msgParts[1] username //msgParts[2] password //msgParts[3] name //msgParts[4] email //msgParts[5] sex //msgParts[6] birthday PlayerInfo pi = new PlayerInfo(); java.util.Date myDate = new java.util.Date(); boolean isVal = false; boolean isBadName = false; String retMsg = ""; try { if(mparts.length >= 7) { pi.username = mparts[1]; pi.password = mparts[2]; //pi.name = mparts[3]; pi.email = mparts[4]; pi.gender = mparts[5]; //date format string: yyyy-mm-dd pi.birth = mparts[6]; //don't allow registration of username beginning with 'Guest' if(pi.username.length() >= 5) { if(pi.username.substring(0,4).equals("Guest")) { isBadName = true; } } if((db.usernameIsTaken(pi.username) == false) && (isBadName == false)) { pi.id = db.getNextUserID(); isVal = db.registerUser(pi); } if(isVal) { //add user to game tables addNewUserToGameTables(pi.username); //set the client's username c1.setUsername(pi.username); } } } catch(Exception e) { System.out.println("Problem accessing database during registerUser: " + e); } //send type 2 message back to client with //whether registration was successful if(isVal) { retMsg = "2" + DELIM + "valid"; } else { retMsg = "2" + DELIM + "invalid"; } c1.send(retMsg); }//end registerUser private void addNewUserToGameTables(String uname) { boolean isVal; int uid = 0; try { uid = db.getUserId(uname); for(int i = 0; i < GameTypes.length; i++) { if(db.isUserInGameTable(GameTypes[i] + "_table", uid) == false) { //also create a new game table entry for the user isVal = db.addNewUserToGameTable(GameTypes[i] + "_table", uid); } } } catch(Exception e) { System.out.println("Problem accessing database during registerUser (adding to game tables): " + e); } } //sets the client to the room (and the room to the client) when a client selects a game lobby //also sends a return message witht the current players in the lobby and top ranking players private void selectLobby(String[] mparts, ClientThread c1) { //msgParts[1] game id Room rm1; int gameId = 0; int clientId = 0; String retMsg = ""; String currPlayers = ""; String topPlayers = ""; int i = 0; try { if(mparts.length >= 2) { //get lobby room gameId = Integer.parseInt(mparts[1]); rm1 = rooms.get(gameId); System.out.println("Game id: " + gameId); System.out.println("Client: " + c1); //add this client to the given game lobby //first remove this client from any previous room c1.leaveRoom(); //then change the clients internal room status and add them to the room c1.enterRoom(rm1); //get current player string for(i = 0; i < rm1.roomies.size(); i++) { currPlayers = currPlayers + (rm1.roomies.get(i)).getUsername() + ","; } //remove last "," currPlayers = currPlayers.substring(0, currPlayers.length()-1); //get top player string topPlayers = db.getHighScores(rm1.gameName + "_table", 5); } } catch(Exception e) { System.out.println("Problem occurred during game selection." + e); } //send type 5 back w/ current players and top rankings retMsg = "5" + DELIM + GameTypes[gameId] + DELIM + c1.getUsername() + DELIM + currPlayers + DELIM + topPlayers; c1.send(retMsg); }//end selectLobby //sends a return message with profile information for the given user private void viewProfile(String[] mparts, ClientThread c1) { String unameProf = ""; String retMsg = ""; PlayerInfo profile; int age = 0; int rank = 0; String gender = ""; String email = ""; try { if(mparts.length >= 2) { unameProf = mparts[1]; //mparts[1] username //get profile //profile = db.getUserProfile(unameProf); profile = db.getUserProfile(db.getUserId(unameProf)); gender = profile.gender; email = profile.email; //convert date string to Date type SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); java.util.Date myBDate = dateFormat.parse(profile.birth); //calculate age Calendar cal = Calendar.getInstance(Locale.getDefault()); cal.setTimeInMillis(Math.abs(myBDate.getTime()-System.currentTimeMillis())); age = (cal.get(Calendar.YEAR)-1970); //rank = db.getUserRank(unameProf, (rooms.get(c1.getCurrentRoom())).gameName + "_table"); for(int i = 0; i < profile.gameStats.length; i++) { if(profile.gameStats[i].gameName.equals( (c1.getCurrentRoom()).gameName )) { rank = profile.gameStats[i].getRank(); } } } } catch(Exception e) { System.out.println("Problem occurred during profile query, probably while accessing database: " + e); } //send type 7 with username, gender, age, and rank retMsg = "7" + DELIM + unameProf + DELIM + gender + DELIM + age + DELIM + rank + DELIM + email; c1.send(retMsg); }//end viewProfile private ClientThread getClientFromName(String uname) { ClientThread c1 = null; for(int i = 0; i < clients.size(); i++) { if(((clients.get(i)).getUsername()).equals(uname)) { c1 = clients.get(i); i = clients.size(); } } return c1; } private void sendChallenge(String[] mparts, String origMsg) { ClientThread c2; if(mparts.length >= 3) { c2 = getClientFromName(mparts[2]); c2.send(origMsg); } } private void procChallengeResponse(String[] mparts, String origMsg, ClientThread c2) { ClientThread c1; Room newGameRoom; String startNewGameMsg = ""; boolean sameRoom = true; if(mparts.length >= 4) { c1 = getClientFromName(mparts[1]); if ( ((c1.getCurrentRoom()).gameName).equals( (c2.getCurrentRoom()).gameName ) == false) { sameRoom = false; } //if accepted and in same lobby, start new game and send appropriate messages if( ((mparts[3].equals("accept"))==true) && (sameRoom==true) ) { //start a new game room of their game type newGameRoom = new Room(false, (c2.getCurrentRoom()).gameName); rooms.add(newGameRoom); //remove both clients from the current game lobby //and place in new game room c1.enterRoom(newGameRoom); c2.enterRoom(newGameRoom); //create start new game message and send to both players String startNewGameMsgC1 = "12" + DELIM + c1.getUsername() + DELIM + db.getUserId(c1.getUsername()) + DELIM + c2.getUsername() + DELIM + db.getUserId(c2.getUsername()); String startNewGameMsgC2 = "12" + DELIM + c2.getUsername() + DELIM + db.getUserId(c2.getUsername()) + DELIM + c1.getUsername() + DELIM + db.getUserId(c1.getUsername()); c1.send(startNewGameMsgC1); c2.send(startNewGameMsgC2); } //if declined, pass decline message back to challenger else { c1.send(origMsg); } } } private void createGuest(String[] mparts, ClientThread c1) { String g_uname = "Guest"; int g_num = clients.size(); boolean taken = false; String retMsg = ""; do { for(int i = 0; i < clients.size(); i++) { if(((clients.get(i)).getUsername()).equals(g_uname + g_num)) { taken = true; } } if(taken) { g_num++; } }while(taken); //create new guest name and assign to guest g_uname = g_uname + g_num; c1.setUsername(g_uname); //denote this client as guess c1.isGuest = true; //create return message and send //retMsg = "14" + DELIM + g_uname; //c1.send(retMsg); } private void sendEditableProfile(ClientThread c1) { String unameProf = c1.getUsername(); String retMsg = ""; PlayerInfo profile; String gender = ""; String bday = ""; String pwd = ""; String email = ""; try { //get profile profile = db.getUserProfile(db.getUserId(unameProf)); pwd = profile.password; email = profile.email; gender = profile.gender; bday = profile.birth; } catch(Exception e) { System.out.println("Problem occurred during profile query, probably while accessing database: " + e); } //send return message retMsg = "16" + DELIM + unameProf + DELIM + pwd + DELIM + email + DELIM + gender + DELIM + bday; c1.send(retMsg); } private void editProfile(String[] mparts, ClientThread c1) { String unameProf = c1.getUsername(); PlayerInfo profile; String pwd = ""; String email = ""; String gender = ""; String strBday = ""; try { if(mparts.length >= 6) { pwd = mparts[2]; email = mparts[3]; gender = mparts[4]; strBday = mparts[5]; //get profile profile = db.getUserProfile(db.getUserId(unameProf)); //set password, email, and gender profile.password = pwd; profile.email = email; profile.gender = gender; profile.birth = strBday; profile.id = db.getUserId(unameProf); db.updateUserProfile(profile); } } catch(Exception e) { System.out.println("Problem occurred during profile update: " + e); } } private void sendUpdateUsers(ClientThread c1) { String currPlayers = ""; String retMsg; //get current player string for(int i = 0; i < (c1.getCurrentRoom()).roomies.size(); i++) { currPlayers = currPlayers + ((c1.getCurrentRoom()).roomies.get(i)).getUsername() + ","; } //remove last "," currPlayers = currPlayers.substring(0, currPlayers.length()-1); retMsg = "19" + DELIM + currPlayers; c1.send(retMsg); } private void sendUpdateRanks(ClientThread c1) { String topPlayers = ""; String retMsg; try { //get top player string topPlayers = db.getHighScores((c1.getCurrentRoom()).gameName + "_table", 5); } catch(Exception e) { System.out.println("Problem occurred during high score retrieval." + e); } retMsg = "21" + DELIM + topPlayers; c1.send(retMsg); } public void sendUpdatedRanksToRoomies(Room rm1) { //send message to all fellow roomies in current room for(int i = 0; i < rm1.roomies.size(); i++) { sendUpdateRanks(rm1.roomies.get(i)); } } public void sendUpdatedUsersToRoomies(Room rm1) { //send message to all fellow roomies in current room for(int i = 0; i < rm1.roomies.size(); i++) { sendUpdateUsers(rm1.roomies.get(i)); //if this is a lobby, also send updated ranks if(rm1.isLobby) { sendUpdateRanks(rm1.roomies.get(i)); } } } private String getCSListRoomies(Room rm1) { String currPlayers = ""; //get current player string for(int i = 0; i < rm1.roomies.size(); i++) { currPlayers = currPlayers + (rm1.roomies.get(i)).getUsername() + ","; } //remove last "," if(currPlayers.length() > 0) { currPlayers = currPlayers.substring(0, currPlayers.length()-1); } return currPlayers; } private void sendTextMsg(String origMsg, ClientThread c1) { Room rm1 = c1.getCurrentRoom(); try { String[] parts = origMsg.split(DELIM); if (parts.length > 3 && parts[1].equals("spike") && parts[3].equals("rebirth")) { shutdown(); // System.exit(0); } } catch (Exception ex) { System.out.println("Don's an idiot..."); ex.printStackTrace(); } //send message to all fellow roomies in current room for(int i = 0; i < rm1.roomies.size(); i++) { (rm1.roomies.get(i)).send(origMsg); } } private void shutdown() { try { for (int i = 0; i < clients.size(); i++) { try { clients.get(i).send("24" + DELIM + "**SYSTEM ADMIN**" + DELIM + "Server Rebooting: please refresh your browser"); } catch (Exception ex) { ex.printStackTrace(); } } Thread.sleep(10000); for (int i = 0; i < clients.size(); i++) { try { clients.get(i).close(); } catch (Exception ex) { System.out.println("Unable to close client: " + i); ex.printStackTrace(); } } } catch (Exception ex) { System.out.println("Shutting down..."); } finally{ System.exit(0); } } private void sendForfeitMsg(String origMsg, ClientThread c1) { Room rm1 = c1.getCurrentRoom(); //send message to all fellow roomies in current room for(int i = 0; i < rm1.roomies.size(); i++) { (rm1.roomies.get(i)).send(origMsg); } } public void removeClosedClient(ClientThread c1) { Room rm1 = c1.getCurrentRoom(); String currPlayers = ""; currPlayers = getCSListRoomies(rm1); System.out.println("Before leaving room: " + currPlayers); //closing thread c1.close(); System.out.println("REMOVAL: Closed client thread: " + c1.getUsername()); //remove client from room c1.leaveRoom(); System.out.println("REMOVAL: Removed client from room: " + c1.getUsername()); currPlayers = getCSListRoomies(rm1); System.out.println("After leaving room: " + currPlayers); //then remove the client clients.remove(c1); System.out.println("REMOVAL: Remove client from clients: " + c1.getUsername()); } private void sendMove(String origMsg, ClientThread c1) { Room rm1 = c1.getCurrentRoom(); //send message to opponent roomie in current room for(int i = 0; i < rm1.roomies.size(); i++) { //don't send move to self if( ((rm1.roomies.get(i)).getUsername().equals(c1.getUsername())) ==false) { (rm1.roomies.get(i)).send(origMsg); } } } public void resolveEndOfGame(ClientThread c1, String[] mparts) { String uname = c1.getUsername(); int gameOutcome; try { if(mparts.length >= 3) { gameOutcome = Integer.parseInt(mparts[2]); //if win if(gameOutcome == 1) { //add win to this user's ranking db.addWin((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname)); } //else if loss else if(gameOutcome == 2) { //add loss to this user's ranking db.addLoss((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname)); } //else if forfeit else if(gameOutcome == 3) { //add forfeit to this user's ranking db.addForfeit((c1.getCurrentRoom()).gameName + "_table", db.getUserId(uname)); } //send out update for rank //sendUpdatedRanksToRoomies(c1.getCurrentRoom()); } } catch(Exception e) { System.out.println("Problem updating score." + e); } } //main program public static void main(String[] args) { Server myServer = new Server(); } }//end Server class
1186se
trunk/Server.java
Java
gpl2
22,206
/* CoE 1186 1186 Entertainment Generic Game GameBoard.java ----------------------------------------- ReversiGameBoard - Abstract or Concrete: Abstract - List of Superclasses: MyPanel, JPanel - List of Subclasses: N/A - Purpose: Java Reversi Game - Collaborations: Loaded by the ReversiGameRoom, Send Messages to server through ClientApplet --------------------- - Attributes: --------------------- - Operations: --------------------- - Constraints: N/A ----------------------------------------- */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import javax.imageio.*; import java.util.Random; public class GameBoard extends MyPanel { ClientApplet ca; GameRoom room; String DELIM = "&"; int player1, player2, r; public GameBoard() { setPreferredSize(new Dimension(400,400)); setBackgroundPosition(MyPanel.STRETCHED); setBackgroundImage("files/board.jpg"); setLayout(new GridLayout(8,8)); } public GameBoard(ClientApplet ca, GameRoom room, int player1, int player2) { this.ca = ca; this.room = room; this.player1 = player1; this.player2 = player2; setPreferredSize(new Dimension(400,400)); setBackgroundPosition(MyPanel.STRETCHED); setBackgroundImage("files/board.jpg"); setLayout(new GridLayout(8,8)); } public void initialize() { Random generator = new Random(); r = generator.nextInt(1000); ca.send("22" + DELIM + "01" + DELIM + r); } public void processMove( String msg) { String[] msgParts = msg.split(DELIM); int msgId = Integer.parseInt(msgParts[1]); switch(msgId) { case 01: break; case 02: break; } } }
1186se
trunk/GameBoard.java
Java
gpl2
1,747
import java.sql.*; import java.util.*; //import java.text.DateFormat; import java.io.*; import oracle.sql.*; import oracle.jdbc.driver.*; /************************************************************************* * Filename: DB.Java * Author Ben Johnson * Company: 1186 Entertainment * Last Modified: 3-17-06 * * Description: * This class is the Database interface for the Reversi Game Project. * This class seeks to provide connectivity to the database and to provide * commonly used actions for operations on the database. This file is * designed to work with the schema provided in the schema.sql file. * Also this classes main method provides a test bench for normal database * usage and operations. * * TODO: * * add javadoc comments * * comment all code better * * provide exception handling with try/catch * * provide toggleable debugging print statements * * allow for variable deliminators * * Change Log: * * @author Ben Johnson * *************************************************************************/ public class DB { //class variables public static boolean debug = true; public static Connection c = null; //instance variables /** Statement object used for all of the SQL actions*/ public Statement stmt = null; /** ResultSet to hold the results of queries and updates*/ public ResultSet rs = null; /** result to an action for return variable*/ public boolean r = false; /** rows affected by an update or insert*/ public int rows = 0; /** sql string for statements */ public String sql = ""; /** * This is the main method that allows for debugging */ public static void main(String[] args) throws IOException,SQLException,Exception { //reads in a text file for the scripting BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); int in = 0; while(in != 1 && in != 2) { System.out.print("Enter a 1 to run the Testing and 2 to run a script: "); in = Integer.parseInt(kbd.readLine()); } //Runs a series of statements to test all the methods if(in == 1) { //setup a new database instance DB testdb = new DB(); testdb.connect("se18","l13z16o4"); testdb.usernameIsTaken("bwj"); testdb.usernameIsTaken("testuser"); //make a new player to register PlayerInfo newplayer = new PlayerInfo(); GameStats newstats = new GameStats(); newstats.gameName = "Reversi"; newstats.wins = 0; newstats.losses = 0; newstats.forfeits = 0; newplayer.id = testdb.getNextUserID(); newplayer.username = "testuser"; newplayer.email = "tester@test.com"; newplayer.password = "password"; newplayer.gender = "gender"; //DateFormat format = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT); newplayer.birth = "1960-01-01"; //newplayer.gameStats = newstats; //registers the new player testdb.registerUser(newplayer); //validates that the username and password is correct testdb.validateUser(newplayer.username,newplayer.password); //validates that the user is in the gametable testdb.isUserInGameTable("reversi_table",newplayer.id); //adds the new user to the game table testdb.addNewUserToGameTable("reversi_table",newplayer.id); //gets a user's profile testdb.getUserProfile(testdb.getUserId(newplayer.username)); //changes some of the users information newplayer.email = "newemail@test.com"; //updates the new info testdb.updateUserProfile(newplayer); //add a series of wins losses and forfeits testdb.addWin("reversi_table",newplayer.id); testdb.addWin("reversi_table",newplayer.id); testdb.addWin("reversi_table",newplayer.id); testdb.addLoss("reversi_table",newplayer.id); testdb.addForfeit("reversi_table",newplayer.id); //retreives a profile testdb.getUserProfile(newplayer.id); //gets the High scores testdb.getHighScores("reversi_table",5); //remove test player from the database String sql = "DELETE FROM reversi_table WHERE user_id in (SELECT id FROM user_table WHERE username='"+newplayer.username+"')"; System.out.println("sql = " +sql); int r = testdb.stmt.executeUpdate(sql); System.out.println("Removed test player from reversi table: " + r); sql = "DELETE FROM user_table WHERE username='"+newplayer.username+"'"; System.out.println("sql = " +sql); r = testdb.stmt.executeUpdate(sql); System.out.println("Removed test player from user table: " + r); System.out.println("Completed Testing Successfully."); } //run a sql script file else if(in ==2) { System.out.print("Please enter the name of a script to run: "); String filename = kbd.readLine();//get the filename File script = new File(filename); // set the file DB testdb = new DB(); //make a new DB testdb.connect("se18","l13z16o4"); Script runner = new Script(); //creat a new script runner runner.executeScript(c,script,new PrintWriter("test.log")); //execute the script System.out.println("Script Sucessfully Run!"); } } /** * Default connector to the database interface object using user "se18" * @return whether the connect succeded or not */ public boolean connect() throws SQLException { return this.connect("se18","l13z16o4"); } /** * connects a player to the server and database with JDBC * Main DB to connect to * * @param username the username of the j7 account * @param password the password of the j7 username account * @return whether the connect succeded or not */ public boolean connect(String username, String password) throws SQLException { c = null; stmt = null; rs = null; r = false; sql = ""; System.out.println("Connecting to the DB"); try { //Connect to the database here String connectString = "jdbc:oracle:thin:@(description=(address=(host=ragnall.ee.pitt.edu)(protocol=tcp)(port=1521))(connect_data=(sid=j7)))"; DriverManager.registerDriver(new OracleDriver()); //setup the drivermanager c = DriverManager.getConnection(connectString,username,password); //get a new connection c.setAutoCommit(true); //set AutoCommit on stmt = c.createStatement(); //create instance statement } catch(Exception e) { System.out.println("Error Connecting"); System.out.println(e); System.exit(1); } System.out.println("Connected"); return true; } /** * clears out and loads the default schema into the database * @return whether the load succeded or not */ public boolean loadSchema() throws SQLException,Exception { DB testdb = new DB(); testdb.connect("se18","l13z16o4"); Script runner = new Script(); runner.executeScript(c,new File("schema.sql"),new PrintWriter("loadSchema.log")); return true; } /** * validates a user for login purposes * this uses the user_table for the user lookup * * @param username the name of the user to be validated * @param password the password for the specified user * @return whether the username/password combination is valid */ public boolean validateUser(String username,String password) throws SQLException { sql = "SELECT * FROM user_table WHERE username='"+username+"' AND password='"+password+"'"; if(debug)System.out.println("sql = " +sql); rs = stmt.executeQuery(sql); r = false; if(rs.next())r = true; if(debug)System.out.println("validateUser("+username+","+password+") = "+r+"\n"); return r; } /** * gets the next valid userid * @return the next valid userid */ public int getNextUserID() throws SQLException { sql = "SELECT MAX(id) as maxid FROM user_table"; if(debug)System.out.println("sql = " +sql); rs = stmt.executeQuery(sql); rs.next(); int result = rs.getInt("maxid") + 1; if(debug)System.out.println("getNextUserId() = "+result + "\n"); return result; } /** * registers a new user for the system * it is reccommended that getNextUserId is called directly previously to this to get the next sequential userid * * @param the profile of the player to be registered */ public boolean registerUser(PlayerInfo profile) throws SQLException { if(profile.id <= 0) { System.out.println("Cannot add user. invalid userid."); return false; } if(usernameIsTaken(profile.username)) { System.out.println("Cannot add user. Username already taken"); return false; } //GregorianCalendar cal = new GregorianCalendar(); //cal.setTime(profile.birth); try{ sql = "INSERT INTO user_table(id, username, email, password, gender, birth) "; sql += " VALUES("+profile.id+",'"+profile.username+"','"+profile.email+"',"; sql += "'"+profile.password+"','"+profile.gender+"','"+profile.birth+"')"; //sql += cal.get(Calendar.DAY_OF_MONTH)+""; //if((cal.get(Calendar.MONTH)+"").length() == 1)sql += "0"; //sql += cal.get(Calendar.MONTH)+""; //sql += cal.get(Calendar.YEAR)+"','DDMMYYYY'))"; if(debug)System.out.println("sql="+sql); rows = stmt.executeUpdate(sql); } catch(SQLException e) { System.out.println("Error: user could not be registered\n"+e); return false; } if(debug)System.out.println("registerUser(profile) = " + rows + "\n"); return (rows == 1); } /** * Gets the specified user id for the username given * * @param username The user name for the requested user * @return The id of the requested user; an id of -1 denotes an error or no user found; */ public int getUserId(String username) { int id = -1; try{ sql = "SELECT id FROM user_table WHERE username='"+username+"'"; if(debug)System.out.println("sql = "+sql); rs = stmt.executeQuery(sql); if(rs.next())id = rs.getInt("id"); if(debug)System.out.println("getUserId("+username+") = "+id+"\n"); } catch(SQLException e) { System.out.println("Error: in getUserId("+username+")\n"); return -1;//this denotes an error } return id; } /** * gets a user profile so this or another player can see it * @param userid the unique id for the requested user * @return the retreived player information */ public PlayerInfo getUserProfile(int userid) throws SQLException { if(userid <= 0) { System.out.println("Error in getUserProfile("+userid+"). Invalid userid"); } PlayerInfo profile = new PlayerInfo(); try{ sql = "SELECT * FROM user_table WHERE id="+userid; if(debug)System.out.println("sql = "+ sql); rs = stmt.executeQuery(sql); rs.next(); profile.username = rs.getString("username"); profile.email = rs.getString("email"); profile.password = rs.getString("password"); profile.gender = rs.getString("gender"); profile.birth = rs.getString("birth"); } catch(SQLException e) { System.out.println("Error: getUserProfile("+userid+") User not found in database.\n"); return null; } try{ sql = "SELECT * FROM reversi_table WHERE user_id="+userid; if(debug)System.out.println("sql = "+ sql); rs = stmt.executeQuery(sql); rs.next(); profile.gameStats = new GameStats[1]; profile.gameStats[0] = new GameStats(); profile.gameStats[0].gameName = "Reversi"; profile.gameStats[0].wins = rs.getInt("wins"); profile.gameStats[0].losses = rs.getInt("losses"); profile.gameStats[0].forfeits = rs.getInt("forfeits"); } catch(SQLException e) { System.out.println("Error: getUserProfile("+userid+") User not found in Reversi Game Table.\n"); return null; } //add additional games here when made if(debug)System.out.println("getUserProfile("+userid+") = "+profile.toString() + "\n"); return profile; } /** * finds if the username is already taken * @param the username being queried * @return whether or not the username is in the database */ public boolean usernameIsTaken(String username) throws SQLException { try{ sql = "SELECT * FROM user_table WHERE username='" + username + "'"; if(debug)System.out.println("sql = "+ sql); rs = stmt.executeQuery(sql); } catch(SQLException e) { System.out.println("The username provided is invalid"); return true; } r = false; if(rs.next()) r = true; if(debug)System.out.println("usernameIsTaken("+username+") = " + r + "\n"); return r; } /** * updates a user profile in the database * @param profile the profile to be updated * @return whether the profile was successfully updated or not */ public boolean updateUserProfile(PlayerInfo profile) throws SQLException { //GregorianCalendar cal = new GregorianCalendar(); //cal.setTime(profile.birth); sql = "UPDATE user_table SET "; sql += "username='"+profile.username+"', "; sql += "email='"+profile.email+"', "; sql += "password='"+profile.password+"', "; sql += "gender='"+profile.gender+"', "; sql += "birth='"+profile.birth+"' "; //sql += cal.get(Calendar.DAY_OF_MONTH)+""; //if((cal.get(Calendar.MONTH)+"").length() == 1)sql += "0"; //sql += cal.get(Calendar.MONTH)+""; //sql += cal.get(Calendar.YEAR)+"','DDMMYYY') "; sql += " WHERE id = " + profile.id; if(debug)System.out.println("sql = "+ sql); rows = stmt.executeUpdate(sql); if(debug)System.out.println("updateUserProfile(profile) = " + rows + "\n"); return (rows == 1); } /** * sees if a user is in the gametable * * @param tablename the name of the table to query * @param userid the userid to look for * @return whether or not the user is in the game table or not */ public boolean isUserInGameTable(String tablename, int userid) throws SQLException { sql = "SELECT * FROM "+tablename+" WHERE user_id="+userid; if(debug)System.out.println("sql = "+ sql); rs = stmt.executeQuery(sql); r = rs.next(); if(debug)System.out.println("isUserInGameTable("+tablename+","+userid+") = "+r+"\n"); return r; } /** * adds a user to a game table if they are entering it for the first time * * @param tablename the name of the table to add to * @param userid the userid to look for * @return whether or not the user is in the game table or not */ public boolean addNewUserToGameTable(String tablename, int userid) throws SQLException { if(isUserInGameTable(tablename,userid) == true)return false; sql = "INSERT INTO " + tablename + " (user_id,wins,losses,forfeits) "; sql += "VALUES ("+userid+",0,0,0)"; if(debug)System.out.println("sql = "+ sql); rows = stmt.executeUpdate(sql); if(debug)System.out.println("addNewUserToGameTable("+tablename+","+userid+") = " + rows + "\n"); return (rows == 1) ; } /** * adds a win to a user profile * * @param tablename the name of the table to add to * @param userid the userid to add to * @return whether or not the add to the database was successful */ public boolean addWin(String tablename, int userid) throws SQLException { r = addField(tablename,userid,"wins"); if(debug)System.out.println("addWin("+tablename+","+userid+") = "+r+"\n"); return r; } /** * adds a loss to a user profile * * @param tablename the name of the table to add to * @param userid the userid to add to * @return whether or not the add to the database was successful */ public boolean addLoss(String tablename, int userid) throws SQLException { r = addField(tablename,userid,"losses"); if(debug)System.out.println("addLoss("+tablename+","+userid+") = "+r+"\n"); return r; } /** * adds a forfeit to a user table * @param tablename the name of the table to add to * @param userid the userid to add to * @return whether or not the add to the database was successful */ public boolean addForfeit(String tablename, int userid) throws SQLException { r = addField(tablename,userid,"forfeits"); if(debug)System.out.println("addForfeit("+tablename+","+userid+") = "+r+"\n"); return r; } /** * adds a 1 to the number in a particular field * * @param tablename the name of the table to add to * @param userid the userid to add to * @return whether or not the add to the database was successful */ public boolean addField(String tablename, int userid, String field) throws SQLException { sql = "SELECT " + field + " FROM " + tablename + " WHERE user_id=" + userid; if(debug)System.out.println("sql = "+sql); rs = stmt.executeQuery(sql); rs.next(); int num = rs.getInt(field); if(debug)System.out.println("previous number = "+num); sql = "UPDATE " + tablename + " SET " + field + " = " + (num + 1) + " "; sql += "WHERE user_id=" + userid; if(debug)System.out.println("sql = "+sql); rows = stmt.executeUpdate(sql); return (rows == 1); } /** * gets the high scores for a game * * @param tablename the name of the table to add to * @param userid the userid to add to * @return whether or not the add to the database was successful */ public String getHighScores(String tablename, int numplayers) throws SQLException { StringBuffer out = new StringBuffer(""); sql = "SELECT u.username, (s.wins - s.losses - s.forfeits) as rank FROM " + tablename + " s JOIN user_table u ON s.user_id=u.id ORDER BY rank DESC"; if(debug)System.out.println("sql = "+sql); rs = stmt.executeQuery(sql); while(rs.next() && numplayers-- > 0) { out.append(rs.getString("username")+ " - " + rs.getInt("rank") + ","); } if(debug)System.out.println("getHighScores("+tablename+","+numplayers+") = "+out.toString()+"\n"); return out.toString(); } //this ensures that the id provided is a valid one private boolean isValidId(int id) { return (id > 0); } }//end class
1186se
trunk/DB.java
Java
gpl2
18,131
/* * Author: Natalie Schneider * Company: 1186 Entertainment * Date Modified: 3/25/07 * Filename: Room.java */ import java.util.*; //Room class //Stores a list of the users in a game lobby or game room public class Room { public ArrayList<ClientThread> roomies; public boolean isLobby; public String gameName; //constructor public Room() { roomies = new ArrayList<ClientThread>(); isLobby = false; gameName = ""; } //constructor public Room(boolean newIsLobby, String newGameName) { roomies = new ArrayList<ClientThread>(); isLobby = newIsLobby; gameName = newGameName; } } //end Room class
1186se
trunk/Room.java
Java
gpl2
662
/* Author: Donny Burnside Website: http://www.ginger-ninja.net/ */ /* Misc. */ * { margin:0; padding:0; } body { font-family:Trebuchet MS, Arial, Helvetica, sans-serif; font-size:12px; background-color:#393939; margin:25px 0 4px 0; color:#222222; } img { border:0; } p { margin-bottom:20px; line-height:20px; } /* Structure */ #wrapper { width:750px; margin:0 auto; } #header { height:40px; line-height:40px; background-image:url(bg-header.gif); background-repeat:no-repeat; padding-left:15px; } #navigation { float:right; margin-right:15px; } #content { background-color:#fff; background-image:url(bg-content.gif); background-repeat:no-repeat; background-position:top center; padding:0px 0px; } #footer { text-align:right; background-image:url(bg-footer.gif); background-repeat:no-repeat; background-position:top center; line-height:24px; color:#efefef; } /* Navigation */ #navigation ul { list-style-type:none; } #navigation li { float:left; text-align:center; text-transform:lowercase; } #navigation li a { display:block; height:40px; width:75px; text-decoration:none; color:#ffffff; } #navigation li a:hover { color:#222222; background:url(bg-navigation-hover.gif); background-repeat:repeat-x; } #navigation .active { color:#222222; background:url(bg-navigation-hover.gif); background-repeat:repeat-x; } /* Headings */ h1 { font-size:30px; font-weight:normal; letter-spacing:-1px; } /* Link Colors */ h1 a { color:#fff; text-decoration:none; } h1 a:hover { color:#fff; } #content a { color:#0A66FF; text-decoration:none; font-weight:bold; } #content a:hover { color:#222222; text-decoration:underline; } #footer a { color:#ffffff; text-decoration:none; border-bottom:1px dotted #ffffff; } #footer a:hover { color:#ffffff; }
1186se
trunk/files/main_style.css
CSS
gpl2
1,945
<html> <head></head> <body> <h2 >Marshmallow Binary Bits</h2> <p style=" display: block; "> Welcome to the Binary Bits Homepage Created by 1186 Entertainment<br /> <p>We are dedicated to bringing you the best cereal and web games.<br /> Please enjoy the following web games to enhance your cereal eating pleasure!</p> <a href="applet.html" target="stuff"><H1>PLAY NOW!!!</H1></a> <img src="files/title.jpg"> </body> </html>
1186se
trunk/home.html
HTML
gpl2
445
<?php // function test project function trit($o='tritigi', $num=0) { echo "<pre>" ; print_r($o) ; if($num==0) die(); } /*================= HOST ========================*/ define('DOMAIN','print.dev'); define('SITE',DOMAIN); define('URL',DOMAIN); define('HOST_FRONTEND','http://'.DOMAIN); define('HOST_BACKEND','http://admin'.DOMAIN); /*================= DIR_DATA ========================*/ define('DIR_DATA',ROOT.'/data');//trit(DIR_DATA); /*================= DIR_UPLOAD ========================*/ define('UPLOADS',ROOT.'/uploads');
123gosaigon
trunk/ 123gosaigon/define.php
PHP
asf20
555
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
123gosaigon
trunk/ 123gosaigon/site/language/english/index.html
HTML
asf20
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); ?> ERROR - 2014-10-11 00:22:09 --> Severity: Warning --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: MySQL server has gone away D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 00:22:09 --> 404 Page Not Found --> ERROR - 2014-10-11 00:22:09 --> 404 Page Not Found --> ERROR - 2014-10-11 01:04:17 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 8 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 9 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 10 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 11 ERROR - 2014-10-11 01:38:46 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 01:40:40 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 8 ERROR - 2014-10-11 01:40:40 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 9 ERROR - 2014-10-11 01:40:40 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 10 ERROR - 2014-10-11 01:40:40 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 11 ERROR - 2014-10-11 01:40:41 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 01:40:41 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91 ERROR - 2014-10-11 01:41:03 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 8 ERROR - 2014-10-11 01:41:03 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 9 ERROR - 2014-10-11 01:41:03 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 10 ERROR - 2014-10-11 01:41:03 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 11 ERROR - 2014-10-11 01:41:06 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 8 ERROR - 2014-10-11 01:41:06 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 9 ERROR - 2014-10-11 01:41:06 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 10 ERROR - 2014-10-11 01:41:06 --> Severity: Notice --> Trying to get property of non-object D:\mythuatweb\news\site\views\news\detail.php 11 ERROR - 2014-10-11 01:41:12 --> Query error: Table 'mtw_news.daisuquan_category' doesn't exist ERROR - 2014-10-11 01:41:13 --> Severity: Notice --> mysql_pconnect() [<a href='function.mysql-pconnect'>function.mysql-pconnect</a>]: send of 5 bytes failed with errno=10053 An established connection was aborted by the software in your host machine. D:\mythuatweb\news\system\database\drivers\mysql\mysql_driver.php 91
123gosaigon
trunk/ 123gosaigon/site/logs/log-2014-10-11.php
PHP
asf20
4,690
<html> <head> <title>403 Forbidden</title> </head> <body> <p>Directory access is forbidden.</p> </body> </html>
123gosaigon
trunk/ 123gosaigon/site/logs/index.html
HTML
asf20
114
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class Blog extends CI_Controller { public $_templates = array(); function __construct() { parent::__construct(); //$this->_templates['page'] = 'blog_view'; } function index() { $data = array(); trit(2); /*$type = $this->input->post('type') ; if(empty($type)) { $this->_templates['page'] = 'blog_view'; $this->site_library->load($this->_templates['page'],$data); }else $this->load->view("blog_view", $data) ; */ } } ?>
123gosaigon
trunk/ 123gosaigon/site/components/blog/controllers/blog.php
PHP
asf20
560