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 |
|---|---|---|---|---|---|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
ALLSPHINXOPTS = -d .build/doctrees -D latex_paper_size=$(PAPER) \
$(SPHINXOPTS) .
.PHONY: help clean html web htmlhelp latex changes linkcheck
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " web to make files usable by Sphinx.web"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview over all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
clean:
-rm -rf .build/*
html:
mkdir -p .build/html .build/doctrees
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) .build/html
@echo
@echo "Build finished. The HTML pages are in .build/html."
web:
mkdir -p .build/web .build/doctrees
$(SPHINXBUILD) -b web $(ALLSPHINXOPTS) .build/web
@echo
@echo "Build finished; now you can run"
@echo " python -m sphinx.web .build/web"
@echo "to start the server."
htmlhelp:
mkdir -p .build/htmlhelp .build/doctrees
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) .build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in .build/htmlhelp."
latex:
mkdir -p .build/latex .build/doctrees
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) .build/latex
@echo
@echo "Build finished; the LaTeX files are in .build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
mkdir -p .build/changes .build/doctrees
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) .build/changes
@echo
@echo "The overview file is in .build/changes."
linkcheck:
mkdir -p .build/linkcheck .build/doctrees
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) .build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in .build/linkcheck/output.txt."
| 0o2batodd-friendly | doc/sphinx/Makefile | Makefile | mit | 2,107 |
# -*- coding: utf-8 -*-
#
# pysqlite documentation build configuration file, created by
# sphinx-quickstart.py on Sat Mar 22 02:47:54 2008.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# The contents of this file are pickled, so don't put values in the namespace
# that aren't pickleable (module imports are okay, they're removed automatically).
#
# All configuration values have a default value; values that are commented out
# serve to show the default value.
import sys
# If your extensions are in another directory, add it here.
#sys.path.append('some/directory')
# General configuration
# ---------------------
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.addons.*') or your custom ones.
#extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['.templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The master toctree document.
master_doc = 'index'
# General substitutions.
project = 'pysqlite'
copyright = u'2008-2009, Gerhard Häring'
# The default replacements for |version| and |release|, also used in various
# other places throughout the built documents.
#
# The short X.Y version.
version = '2.6'
# The full version, including alpha/beta/rc tags.
release = '2.6.0'
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
today_fmt = '%B %d, %Y'
# List of documents that shouldn't be included in the build.
#unused_docs = []
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# Options for HTML output
# -----------------------
# The style sheet to use for HTML and HTML Help pages. A file of that name
# must exist either in Sphinx' static/ path, or in one of the custom paths
# given in html_static_path.
html_style = 'default.css'
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['.static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Content template for the index page.
#html_index = ''
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If true, the reST sources are included in the HTML build as _sources/<name>.
#html_copy_source = True
# Output file base name for HTML help builder.
htmlhelp_basename = 'pysqlitedoc'
# Options for LaTeX output
# ------------------------
# The paper size ('letter' or 'a4').
#latex_paper_size = 'letter'
# The font size ('10pt', '11pt' or '12pt').
#latex_font_size = '10pt'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, document class [howto/manual]).
#latex_documents = []
# Additional stuff for the LaTeX preamble.
#latex_preamble = ''
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_use_modindex = True
| 0o2batodd-friendly | doc/sphinx/conf.py | Python | mit | 4,030 |
from pysqlite2 import dbapi2 as sqlite3
FIELD_MAX_WIDTH = 20
TABLE_NAME = 'people'
SELECT = 'select * from %s order by age, name_last' % TABLE_NAME
con = sqlite3.connect("mydb")
cur = con.cursor()
cur.execute(SELECT)
# Print a header.
for fieldDesc in cur.description:
print fieldDesc[0].ljust(FIELD_MAX_WIDTH) ,
print # Finish the header with a newline.
print '-' * 78
# For each row, print the value of each field left-justified within
# the maximum possible width of that field.
fieldIndices = range(len(cur.description))
for row in cur:
for fieldIndex in fieldIndices:
fieldValue = str(row[fieldIndex])
print fieldValue.ljust(FIELD_MAX_WIDTH) ,
print # Finish the row with a newline.
| 0o2batodd-friendly | doc/includes/sqlite3/simple_tableprinter.py | Python | mit | 722 |
from pysqlite2 import dbapi2 as sqlite3
def progress():
print "Query still executing. Please wait ..."
con = sqlite3.connect(":memory:")
con.execute("create table test(x)")
# Let's create some data
con.executemany("insert into test(x) values (?)", [(x,) for x in xrange(300)])
# A progress handler, executed every 10 million opcodes
con.set_progress_handler(progress, 10000000)
# A particularly long-running query
killer_stament = """
select count(*) from (
select t1.x from test t1, test t2, test t3
)
"""
con.execute(killer_stament)
print "-" * 50
# Clear the progress handler
con.set_progress_handler(None, 0)
con.execute(killer_stament)
| 0o2batodd-friendly | doc/includes/sqlite3/progress.py | Python | mit | 674 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
SELECT = "select name_last, age from people order by age, name_last"
# 1. Iterate over the rows available from the cursor, unpacking the
# resulting sequences to yield their elements (name_last, age):
cur.execute(SELECT)
for (name_last, age) in cur:
print '%s is %d years old.' % (name_last, age)
# 2. Equivalently:
cur.execute(SELECT)
for row in cur:
print '%s is %d years old.' % (row[0], row[1])
| 0o2batodd-friendly | doc/includes/sqlite3/execsql_fetchonerow.py | Python | mit | 500 |
from pysqlite2 import dbapi2 as sqlite3
# Create a connection to the database file "mydb":
con = sqlite3.connect("mydb")
# Get a Cursor object that operates in the context of Connection con:
cur = con.cursor()
# Execute the SELECT statement:
cur.execute("select * from people order by age")
# Retrieve all rows as a sequence and print that sequence:
print cur.fetchall()
| 0o2batodd-friendly | doc/includes/sqlite3/execsql_printall_1.py | Python | mit | 375 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
| 0o2batodd-friendly | doc/includes/sqlite3/connect_db_1.py | Python | mit | 71 |
from pysqlite2 import dbapi2 as sqlite3
class MySum:
def __init__(self):
self.count = 0
def step(self, value):
self.count += value
def finalize(self):
return self.count
con = sqlite3.connect(":memory:")
con.create_aggregate("mysum", 1, MySum)
cur = con.cursor()
cur.execute("create table test(i)")
cur.execute("insert into test(i) values (1)")
cur.execute("insert into test(i) values (2)")
cur.execute("select mysum(i) from test")
print cur.fetchone()[0]
| 0o2batodd-friendly | doc/includes/sqlite3/mysumaggr.py | Python | mit | 495 |
# A minimal SQLite shell for experiments
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
con.isolation_level = None
cur = con.cursor()
buffer = ""
print "Enter your SQL commands to execute in SQLite."
print "Enter a blank line to exit."
while True:
line = raw_input()
if line == "":
break
buffer += line
if sqlite3.complete_statement(buffer):
try:
buffer = buffer.strip()
cur.execute(buffer)
if buffer.lstrip().upper().startswith("SELECT"):
print cur.fetchall()
except sqlite3.Error, e:
print "An error occurred:", e.args[0]
buffer = ""
con.close()
| 0o2batodd-friendly | doc/includes/sqlite3/complete_statement.py | Python | mit | 694 |
from pysqlite2 import dbapi2 as sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
con = sqlite3.connect(":memory:")
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]
| 0o2batodd-friendly | doc/includes/sqlite3/row_factory.py | Python | mit | 316 |
from pysqlite2 import dbapi2 as sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(d date, ts timestamp)")
today = datetime.date.today()
now = datetime.datetime.now()
cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
cur.execute("select d, ts from test")
row = cur.fetchone()
print today, "=>", row[0], type(row[0])
print now, "=>", row[1], type(row[1])
cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')
row = cur.fetchone()
print "current_date", row[0], type(row[0])
print "current_timestamp", row[1], type(row[1])
| 0o2batodd-friendly | doc/includes/sqlite3/pysqlite_datetime.py | Python | mit | 693 |
from pysqlite2 import dbapi2 as sqlite3
def authorizer_callback(action, arg1, arg2, dbname, source):
if action != sqlite3.SQLITE_SELECT:
return sqlite3.SQLITE_DENY
if arg1 == "private_table":
return sqlite3.SQLITE_DENY
return sqlite3.SQLITE_OK
con = sqlite3.connect(":memory:")
con.executescript("""
create table public_table(c1, c2);
create table private_table(c1, c2);
""")
con.set_authorizer(authorizer_callback)
try:
con.execute("select * from private_table")
except sqlite3.DatabaseError, e:
print "SELECT FROM private_table =>", e.args[0] # access ... prohibited
try:
con.execute("insert into public_table(c1, c2) values (1, 2)")
except sqlite3.DatabaseError, e:
print "DML command =>", e.args[0] # access ... prohibited
| 0o2batodd-friendly | doc/includes/sqlite3/authorizer.py | Python | mit | 796 |
from pysqlite2 import dbapi2 as sqlite3
# The shared cache is only available in SQLite versions 3.3.3 or later
# See the SQLite documentaton for details.
sqlite3.enable_shared_cache(True)
| 0o2batodd-friendly | doc/includes/sqlite3/shared_cache.py | Python | mit | 190 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
| 0o2batodd-friendly | doc/includes/sqlite3/connect_db_2.py | Python | mit | 75 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=? and age=?", (who, age))
print cur.fetchone()
| 0o2batodd-friendly | doc/includes/sqlite3/execute_1.py | Python | mit | 228 |
from __future__ import with_statement
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table person (id integer primary key, firstname varchar unique)")
# Successful, con.commit() is called automatically afterwards
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
# con.rollback() is called after the with block finishes with an exception, the
# exception is still raised and must be catched
try:
with con:
con.execute("insert into person(firstname) values (?)", ("Joe",))
except sqlite3.IntegrityError:
print "couldn't add Joe twice"
| 0o2batodd-friendly | doc/includes/sqlite3/ctx_manager.py | Python | mit | 632 |
from pysqlite2 import dbapi2 as sqlite3
import md5
def md5sum(t):
return md5.md5(t).hexdigest()
con = sqlite3.connect(":memory:")
con.create_function("md5", 1, md5sum)
cur = con.cursor()
cur.execute("select md5(?)", ("foo",))
print cur.fetchone()[0]
| 0o2batodd-friendly | doc/includes/sqlite3/md5func.py | Python | mit | 256 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select name_last, age from people")
for row in cur:
assert row[0] == row["name_last"]
assert row["name_last"] == row["nAmE_lAsT"]
assert row[1] == row["age"]
assert row[1] == row["AgE"]
| 0o2batodd-friendly | doc/includes/sqlite3/rowclass.py | Python | mit | 336 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
sqlite3.register_adapter(Point, adapt_point)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
| 0o2batodd-friendly | doc/includes/sqlite3/adapter_point_2.py | Python | mit | 363 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
# Create the table
con.execute("create table person(lastname, firstname)")
AUSTRIA = u"\xd6sterreich"
# by default, rows are returned as Unicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert row[0] == AUSTRIA
# but we can make pysqlite always return bytestrings ...
con.text_factory = str
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) == str
# the bytestrings will be encoded in UTF-8, unless you stored garbage in the
# database ...
assert row[0] == AUSTRIA.encode("utf-8")
# we can also implement a custom text_factory ...
# here we implement one that will ignore Unicode characters that cannot be
# decoded from UTF-8
con.text_factory = lambda x: unicode(x, "utf-8", "ignore")
cur.execute("select ?", ("this is latin1 and would normally create errors" + u"\xe4\xf6\xfc".encode("latin1"),))
row = cur.fetchone()
assert type(row[0]) == unicode
# pysqlite offers a builtin optimized text_factory that will return bytestring
# objects, if the data is in ASCII only, and otherwise return unicode objects
con.text_factory = sqlite3.OptimizedUnicode
cur.execute("select ?", (AUSTRIA,))
row = cur.fetchone()
assert type(row[0]) == unicode
cur.execute("select ?", ("Germany",))
row = cur.fetchone()
assert type(row[0]) == str
| 0o2batodd-friendly | doc/includes/sqlite3/text_factory.py | Python | mit | 1,370 |
from pysqlite2 import dbapi2 as sqlite3
class CountCursorsConnection(sqlite3.Connection):
def __init__(self, *args, **kwargs):
sqlite3.Connection.__init__(self, *args, **kwargs)
self.numcursors = 0
def cursor(self, *args, **kwargs):
self.numcursors += 1
return sqlite3.Connection.cursor(self, *args, **kwargs)
con = sqlite3.connect(":memory:", factory=CountCursorsConnection)
cur1 = con.cursor()
cur2 = con.cursor()
print con.numcursors
| 0o2batodd-friendly | doc/includes/sqlite3/countcursors.py | Python | mit | 480 |
from pysqlite2 import dbapi2 as sqlite3
def collate_reverse(string1, string2):
return -cmp(string1, string2)
con = sqlite3.connect(":memory:")
con.create_collation("reverse", collate_reverse)
cur = con.cursor()
cur.execute("create table test(x)")
cur.executemany("insert into test(x) values (?)", [("a",), ("b",)])
cur.execute("select x from test order by x collate reverse")
for row in cur:
print row
con.close()
| 0o2batodd-friendly | doc/includes/sqlite3/collation_reverse.py | Python | mit | 425 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.executescript("""
create table person(
firstname,
lastname,
age
);
create table book(
title,
author,
published
);
insert into book(title, author, published)
values (
'Dirk Gently''s Holistic Detective Agency',
'Douglas Adams',
1987
);
""")
| 0o2batodd-friendly | doc/includes/sqlite3/executescript.py | Python | mit | 444 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect(":memory:")
# enable extension loading
con.enable_load_extension(True)
# Load the fulltext search extension
con.execute("select load_extension('./fts3.so')")
# alternatively you can load the extension using an API call:
# con.load_extension("./fts3.so")
# disable extension laoding again
con.enable_load_extension(False)
# example from SQLite wiki
con.execute("create virtual table recipe using fts3(name, ingredients)")
con.executescript("""
insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes');
insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery');
insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour');
insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter');
""")
for row in con.execute("select rowid, name, ingredients from recipe where name match 'pie'"):
print row
| 0o2batodd-friendly | doc/includes/sqlite3/load_extension.py | Python | mit | 1,032 |
from pysqlite2 import dbapi2 as sqlite3
persons = [
("Hugo", "Boss"),
("Calvin", "Klein")
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table person(firstname, lastname)")
# Fill the table
con.executemany("insert into person(firstname, lastname) values (?, ?)", persons)
# Print the table contents
for row in con.execute("select firstname, lastname from person"):
print row
# Using a dummy WHERE clause to not let SQLite take the shortcut table deletes.
print "I just deleted", con.execute("delete from person where 1=1").rowcount, "rows"
| 0o2batodd-friendly | doc/includes/sqlite3/shortcut_methods.py | Python | mit | 590 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
locals())
print cur.fetchone()
| 0o2batodd-friendly | doc/includes/sqlite3/execute_3.py | Python | mit | 236 |
# Not referenced from the documentation, but builds the database file the other
# code snippets expect.
from pysqlite2 import dbapi2 as sqlite3
import os
DB_FILE = "mydb"
if os.path.exists(DB_FILE):
os.remove(DB_FILE)
con = sqlite3.connect(DB_FILE)
cur = con.cursor()
cur.execute("""
create table people
(
name_last varchar(20),
age integer
)
""")
cur.execute("insert into people (name_last, age) values ('Yeltsin', 72)")
cur.execute("insert into people (name_last, age) values ('Putin', 51)")
con.commit()
cur.close()
con.close()
| 0o2batodd-friendly | doc/includes/sqlite3/createdb.py | Python | mit | 616 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
who = "Yeltsin"
age = 72
cur.execute("select name_last, age from people where name_last=:who and age=:age",
{"who": who, "age": age})
print cur.fetchone()
| 0o2batodd-friendly | doc/includes/sqlite3/execute_2.py | Python | mit | 252 |
from pysqlite2 import dbapi2 as sqlite3
import datetime
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute('select ? as "x [timestamp]"', (datetime.datetime.now(),))
dt = cur.fetchone()[0]
print dt, type(dt)
| 0o2batodd-friendly | doc/includes/sqlite3/parse_colnames.py | Python | mit | 260 |
from pysqlite2 import dbapi2 as sqlite3
def char_generator():
import string
for c in string.letters[:26]:
yield (c,)
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
cur.executemany("insert into characters(c) values (?)", char_generator())
cur.execute("select c from characters")
print cur.fetchall()
| 0o2batodd-friendly | doc/includes/sqlite3/executemany_2.py | Python | mit | 367 |
from pysqlite2 import dbapi2 as sqlite3
con = sqlite3.connect("mydb")
cur = con.cursor()
newPeople = (
('Lebed' , 53),
('Zhirinovsky' , 57),
)
for person in newPeople:
cur.execute("insert into people (name_last, age) values (?, ?)", person)
# The changes will not be saved unless the transaction is committed explicitly:
con.commit()
| 0o2batodd-friendly | doc/includes/sqlite3/insert_more_people.py | Python | mit | 359 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.PrepareProtocol:
return "%f;%f" % (self.x, self.y)
con = sqlite3.connect(":memory:")
cur = con.cursor()
p = Point(4.0, -3.2)
cur.execute("select ?", (p,))
print cur.fetchone()[0]
| 0o2batodd-friendly | doc/includes/sqlite3/adapter_point_1.py | Python | mit | 384 |
from pysqlite2 import dbapi2 as sqlite3
class Point(object):
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return "(%f;%f)" % (self.x, self.y)
def adapt_point(point):
return "%f;%f" % (point.x, point.y)
def convert_point(s):
x, y = map(float, s.split(";"))
return Point(x, y)
# Register the adapter
sqlite3.register_adapter(Point, adapt_point)
# Register the converter
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
#########################
# 1) Using declared types
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES)
cur = con.cursor()
cur.execute("create table test(p point)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute("select p from test")
print "with declared types:", cur.fetchone()[0]
cur.close()
con.close()
#######################
# 1) Using column names
con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES)
cur = con.cursor()
cur.execute("create table test(p)")
cur.execute("insert into test(p) values (?)", (p,))
cur.execute('select p as "p [point]" from test')
print "with column names:", cur.fetchone()[0]
cur.close()
con.close()
| 0o2batodd-friendly | doc/includes/sqlite3/converter_point.py | Python | mit | 1,198 |
from pysqlite2 import dbapi2 as sqlite3
class IterChars:
def __init__(self):
self.count = ord('a')
def __iter__(self):
return self
def next(self):
if self.count > ord('z'):
raise StopIteration
self.count += 1
return (chr(self.count - 1),) # this is a 1-tuple
con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table characters(c)")
theIter = IterChars()
cur.executemany("insert into characters(c) values (?)", theIter)
cur.execute("select c from characters")
print cur.fetchall()
| 0o2batodd-friendly | doc/includes/sqlite3/executemany_1.py | Python | mit | 572 |
from pysqlite2 import dbapi2 as sqlite3
import apsw
apsw_con = apsw.Connection(":memory:")
apsw_con.createscalarfunction("times_two", lambda x: 2*x, 1)
# Create pysqlite connection from APSW connection
con = sqlite3.connect(apsw_con)
result = con.execute("select times_two(15)").fetchone()[0]
assert result == 30
con.close()
| 0o2batodd-friendly | doc/includes/sqlite3/apsw_example.py | Python | mit | 328 |
from pysqlite2 import dbapi2 as sqlite3
import datetime, time
def adapt_datetime(ts):
return time.mktime(ts.timetuple())
sqlite3.register_adapter(datetime.datetime, adapt_datetime)
con = sqlite3.connect(":memory:")
cur = con.cursor()
now = datetime.datetime.now()
cur.execute("select ?", (now,))
print cur.fetchone()[0]
| 0o2batodd-friendly | doc/includes/sqlite3/adapter_datetime.py | Python | mit | 328 |
@import url(docutils.css);
@import url(silvercity.css);
div.code-block{
margin-left: 2em ;
margin-right: 2em ;
background-color: #eeeeee;
font-family: "Courier New", Courier, monospace;
font-size: 10pt;
}
| 0o2batodd-friendly | doc/default.css | CSS | mit | 206 |
# Author: Paul Kippes <kippesp@gmail.com>
import unittest
from pysqlite2 import dbapi2 as sqlite
class DumpTests(unittest.TestCase):
def setUp(self):
self.cx = sqlite.connect(":memory:")
self.cu = self.cx.cursor()
def tearDown(self):
self.cx.close()
def CheckTableDump(self):
expected_sqls = [
"CREATE TABLE t1(id integer primary key, s1 text, " \
"t1_i1 integer not null, i2 integer, unique (s1), " \
"constraint t1_idx1 unique (i2));"
,
"INSERT INTO \"t1\" VALUES(1,'foo',10,20);"
,
"INSERT INTO \"t1\" VALUES(2,'foo2',30,30);"
,
"CREATE TABLE t2(id integer, t2_i1 integer, " \
"t2_i2 integer, primary key (id)," \
"foreign key(t2_i1) references t1(t1_i1));"
,
"CREATE TRIGGER trigger_1 update of t1_i1 on t1 " \
"begin " \
"update t2 set t2_i1 = new.t1_i1 where t2_i1 = old.t1_i1; " \
"end;"
,
"CREATE VIEW v1 as select * from t1 left join t2 " \
"using (id);"
]
[self.cu.execute(s) for s in expected_sqls]
i = self.cx.iterdump()
actual_sqls = [s for s in i]
expected_sqls = ['BEGIN TRANSACTION;'] + expected_sqls + \
['COMMIT;']
[self.assertEqual(expected_sqls[i], actual_sqls[i])
for i in xrange(len(expected_sqls))]
def suite():
return unittest.TestSuite(unittest.makeSuite(DumpTests, "Check"))
def test():
runner = unittest.TextTestRunner()
runner.run(suite())
if __name__ == "__main__":
test()
| 0o2batodd-friendly | lib/test/dump.py | Python | mit | 1,753 |
# Mimic the sqlite3 console shell's .dump command
# Author: Paul Kippes <kippesp@gmail.com>
def _iterdump(connection):
"""
Returns an iterator to the dump of the database in an SQL text format.
Used to produce an SQL dump of the database. Useful to save an in-memory
database for later restoration. This function should not be called
directly but instead called from the Connection method, iterdump().
"""
cu = connection.cursor()
yield('BEGIN TRANSACTION;')
# sqlite_master table contains the SQL CREATE statements for the database.
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type == 'table'
"""
schema_res = cu.execute(q)
for table_name, type, sql in schema_res.fetchall():
if table_name == 'sqlite_sequence':
yield('DELETE FROM sqlite_sequence;')
elif table_name == 'sqlite_stat1':
yield('ANALYZE sqlite_master;')
elif table_name.startswith('sqlite_'):
continue
# NOTE: Virtual table support not implemented
#elif sql.startswith('CREATE VIRTUAL TABLE'):
# qtable = table_name.replace("'", "''")
# yield("INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)"\
# "VALUES('table','%s','%s',0,'%s');" %
# qtable,
# qtable,
# sql.replace("''"))
else:
yield('%s;' % sql)
# Build the insert statement for each row of the current table
res = cu.execute("PRAGMA table_info('%s')" % table_name)
column_names = [str(table_info[1]) for table_info in res.fetchall()]
q = "SELECT 'INSERT INTO \"%(tbl_name)s\" VALUES("
q += ",".join(["'||quote(" + col + ")||'" for col in column_names])
q += ")' FROM '%(tbl_name)s'"
query_res = cu.execute(q % {'tbl_name': table_name})
for row in query_res:
yield("%s;" % row[0])
# Now when the type is 'index', 'trigger', or 'view'
q = """
SELECT name, type, sql
FROM sqlite_master
WHERE sql NOT NULL AND
type IN ('index', 'trigger', 'view')
"""
schema_res = cu.execute(q)
for name, type, sql in schema_res.fetchall():
yield('%s;' % sql)
yield('COMMIT;')
| 0o2batodd-friendly | lib/dump.py | Python | mit | 2,350 |
public class HelloWorldApp {
public static void main(String[] args) {
int n=0;
System.out.println("I Love Java");
}
}
| 102-s23 | trunk/Levis/src/HelloWorldApp.java | Java | gpl2 | 136 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.VenueActivity;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueActivityInstrumentationTestCase extends
ActivityInstrumentationTestCase2<VenueActivity> {
public VenueActivityInstrumentationTestCase() {
super("com.joelapenna.foursquared", VenueActivity.class);
}
@SmallTest
public void testOnCreate() {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra(Foursquared.EXTRA_VENUE_ID, "40450");
setActivityIntent(intent);
VenueActivity activity = getActivity();
activity.openOptionsMenu();
activity.closeOptionsMenu();
}
}
| 07806919d-a | tests/src/com/joelapenna/foursquared/test/VenueActivityInstrumentationTestCase.java | Java | asf20 | 944 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.test;
import com.joelapenna.foursquared.Foursquared;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquaredAppTestCase extends ApplicationTestCase<Foursquared> {
public FoursquaredAppTestCase() {
super(Foursquared.class);
}
@MediumTest
public void testLocationMethods() {
createApplication();
getApplication().getLastKnownLocation();
getApplication().getLocationListener();
}
@SmallTest
public void testPreferences() {
createApplication();
}
}
| 07806919d-a | tests/src/com/joelapenna/foursquared/test/FoursquaredAppTestCase.java | Java | asf20 | 770 |
#!/usr/bin/python2.6
#
# Simple http server to emulate api.playfoursquare.com
import logging
import shutil
import sys
import urlparse
import SimpleHTTPServer
import BaseHTTPServer
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""Handle playfoursquare.com requests, for testing."""
def do_GET(self):
logging.warn('do_GET: %s, %s', self.command, self.path)
url = urlparse.urlparse(self.path)
logging.warn('do_GET: %s', url)
query = urlparse.parse_qs(url.query)
query_keys = [pair[0] for pair in query]
response = self.handle_url(url)
if response != None:
self.send_200()
shutil.copyfileobj(response, self.wfile)
self.wfile.close()
do_POST = do_GET
def handle_url(self, url):
path = None
if url.path == '/v1/venue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/addvenue':
path = '../captures/api/v1/venue.xml'
elif url.path == '/v1/venues':
path = '../captures/api/v1/venues.xml'
elif url.path == '/v1/user':
path = '../captures/api/v1/user.xml'
elif url.path == '/v1/checkcity':
path = '../captures/api/v1/checkcity.xml'
elif url.path == '/v1/checkins':
path = '../captures/api/v1/checkins.xml'
elif url.path == '/v1/cities':
path = '../captures/api/v1/cities.xml'
elif url.path == '/v1/switchcity':
path = '../captures/api/v1/switchcity.xml'
elif url.path == '/v1/tips':
path = '../captures/api/v1/tips.xml'
elif url.path == '/v1/checkin':
path = '../captures/api/v1/checkin.xml'
elif url.path == '/history/12345.rss':
path = '../captures/api/v1/feed.xml'
if path is None:
self.send_error(404)
else:
logging.warn('Using: %s' % path)
return open(path)
def send_200(self):
self.send_response(200)
self.send_header('Content-type', 'text/xml')
self.end_headers()
def main():
if len(sys.argv) > 1:
port = int(sys.argv[1])
else:
port = 8080
server_address = ('0.0.0.0', port)
httpd = BaseHTTPServer.HTTPServer(server_address, RequestHandler)
sa = httpd.socket.getsockname()
print "Serving HTTP on", sa[0], "port", sa[1], "..."
httpd.serve_forever()
if __name__ == '__main__':
main()
| 07806919d-a | mock_server/playfoursquare.py | Python | asf20 | 2,253 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareCredentialsException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareCredentialsException(String message) {
super(message);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/error/FoursquareCredentialsException.java | Java | asf20 | 354 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareError extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareError(String message) {
super(message);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/error/FoursquareError.java | Java | asf20 | 324 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareParseException extends FoursquareException {
private static final long serialVersionUID = 1L;
public FoursquareParseException(String message) {
super(message);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/error/FoursquareParseException.java | Java | asf20 | 341 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class FoursquareException extends Exception {
private static final long serialVersionUID = 1L;
private String mExtra;
public FoursquareException(String message) {
super(message);
}
public FoursquareException(String message, String extra) {
super(message);
mExtra = extra;
}
public String getExtra() {
return mExtra;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/error/FoursquareException.java | Java | asf20 | 536 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.http.AbstractHttpApi;
import com.joelapenna.foursquare.http.HttpApi;
import com.joelapenna.foursquare.http.HttpApiWithBasicAuth;
import com.joelapenna.foursquare.http.HttpApiWithOAuth;
import com.joelapenna.foursquare.parsers.json.CategoryParser;
import com.joelapenna.foursquare.parsers.json.CheckinParser;
import com.joelapenna.foursquare.parsers.json.CheckinResultParser;
import com.joelapenna.foursquare.parsers.json.CityParser;
import com.joelapenna.foursquare.parsers.json.CredentialsParser;
import com.joelapenna.foursquare.parsers.json.FriendInvitesResultParser;
import com.joelapenna.foursquare.parsers.json.GroupParser;
import com.joelapenna.foursquare.parsers.json.ResponseParser;
import com.joelapenna.foursquare.parsers.json.SettingsParser;
import com.joelapenna.foursquare.parsers.json.TipParser;
import com.joelapenna.foursquare.parsers.json.TodoParser;
import com.joelapenna.foursquare.parsers.json.UserParser;
import com.joelapenna.foursquare.parsers.json.VenueParser;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.City;
import com.joelapenna.foursquare.types.Credentials;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquare.util.JSONUtils;
import com.joelapenna.foursquared.util.Base64Coder;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class FoursquareHttpApiV1 {
private static final Logger LOG = Logger
.getLogger(FoursquareHttpApiV1.class.getCanonicalName());
private static final boolean DEBUG = Foursquare.DEBUG;
private static final String DATATYPE = ".json";
private static final String URL_API_AUTHEXCHANGE = "/authexchange";
private static final String URL_API_ADDVENUE = "/addvenue";
private static final String URL_API_ADDTIP = "/addtip";
private static final String URL_API_CITIES = "/cities";
private static final String URL_API_CHECKINS = "/checkins";
private static final String URL_API_CHECKIN = "/checkin";
private static final String URL_API_USER = "/user";
private static final String URL_API_VENUE = "/venue";
private static final String URL_API_VENUES = "/venues";
private static final String URL_API_TIPS = "/tips";
private static final String URL_API_TODOS = "/todos";
private static final String URL_API_FRIEND_REQUESTS = "/friend/requests";
private static final String URL_API_FRIEND_APPROVE = "/friend/approve";
private static final String URL_API_FRIEND_DENY = "/friend/deny";
private static final String URL_API_FRIEND_SENDREQUEST = "/friend/sendrequest";
private static final String URL_API_FRIENDS = "/friends";
private static final String URL_API_FIND_FRIENDS_BY_NAME = "/findfriends/byname";
private static final String URL_API_FIND_FRIENDS_BY_PHONE = "/findfriends/byphone";
private static final String URL_API_FIND_FRIENDS_BY_FACEBOOK = "/findfriends/byfacebook";
private static final String URL_API_FIND_FRIENDS_BY_TWITTER = "/findfriends/bytwitter";
private static final String URL_API_CATEGORIES = "/categories";
private static final String URL_API_HISTORY = "/history";
private static final String URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL = "/findfriends/byphoneoremail";
private static final String URL_API_INVITE_BY_EMAIL = "/invite/byemail";
private static final String URL_API_SETPINGS = "/settings/setpings";
private static final String URL_API_VENUE_FLAG_CLOSED = "/venue/flagclosed";
private static final String URL_API_VENUE_FLAG_MISLOCATED = "/venue/flagmislocated";
private static final String URL_API_VENUE_FLAG_DUPLICATE = "/venue/flagduplicate";
private static final String URL_API_VENUE_PROPOSE_EDIT = "/venue/proposeedit";
private static final String URL_API_USER_UPDATE = "/user/update";
private static final String URL_API_MARK_TODO = "/mark/todo";
private static final String URL_API_MARK_IGNORE = "/mark/ignore";
private static final String URL_API_MARK_DONE = "/mark/done";
private static final String URL_API_UNMARK_TODO = "/unmark/todo";
private static final String URL_API_UNMARK_DONE = "/unmark/done";
private static final String URL_API_TIP_DETAIL = "/tip/detail";
private final DefaultHttpClient mHttpClient = AbstractHttpApi.createHttpClient();
private HttpApi mHttpApi;
private final String mApiBaseUrl;
private final AuthScope mAuthScope;
public FoursquareHttpApiV1(String domain, String clientVersion, boolean useOAuth) {
mApiBaseUrl = "https://" + domain + "/v1";
mAuthScope = new AuthScope(domain, 80);
if (useOAuth) {
mHttpApi = new HttpApiWithOAuth(mHttpClient, clientVersion);
} else {
mHttpApi = new HttpApiWithBasicAuth(mHttpClient, clientVersion);
}
}
void setCredentials(String phone, String password) {
if (phone == null || phone.length() == 0 || password == null || password.length() == 0) {
if (DEBUG) LOG.log(Level.FINE, "Clearing Credentials");
mHttpClient.getCredentialsProvider().clear();
} else {
if (DEBUG) LOG.log(Level.FINE, "Setting Phone/Password: " + phone + "/******");
mHttpClient.getCredentialsProvider().setCredentials(mAuthScope,
new UsernamePasswordCredentials(phone, password));
}
}
public boolean hasCredentials() {
return mHttpClient.getCredentialsProvider().getCredentials(mAuthScope) != null;
}
public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) {
if (DEBUG) {
LOG.log(Level.FINE, "Setting consumer key/secret: " + oAuthConsumerKey + " "
+ oAuthConsumerSecret);
}
((HttpApiWithOAuth) mHttpApi).setOAuthConsumerCredentials(oAuthConsumerKey,
oAuthConsumerSecret);
}
public void setOAuthTokenWithSecret(String token, String secret) {
if (DEBUG) LOG.log(Level.FINE, "Setting oauth token/secret: " + token + " " + secret);
((HttpApiWithOAuth) mHttpApi).setOAuthTokenWithSecret(token, secret);
}
public boolean hasOAuthTokenWithSecret() {
return ((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret();
}
/*
* /authexchange?oauth_consumer_key=d123...a1bffb5&oauth_consumer_secret=fec...
* 18
*/
public Credentials authExchange(String phone, String password) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
if (((HttpApiWithOAuth) mHttpApi).hasOAuthTokenWithSecret()) {
throw new IllegalStateException("Cannot do authExchange with OAuthToken already set");
}
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_AUTHEXCHANGE), //
new BasicNameValuePair("fs_username", phone), //
new BasicNameValuePair("fs_password", password));
return (Credentials) mHttpApi.doHttpRequest(httpPost, new CredentialsParser());
}
/*
* /addtip?vid=1234&text=I%20added%20a%20tip&type=todo (type defaults "tip")
*/
Tip addtip(String vid, String text, String type, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDTIP), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("text", text), //
new BasicNameValuePair("type", type), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* @param name the name of the venue
* @param address the address of the venue (e.g., "202 1st Avenue")
* @param crossstreet the cross streets (e.g., "btw Grand & Broome")
* @param city the city name where this venue is
* @param state the state where the city is
* @param zip (optional) the ZIP code for the venue
* @param phone (optional) the phone number for the venue
* @return
* @throws FoursquareException
* @throws FoursquareCredentialsException
* @throws FoursquareError
* @throws IOException
*/
Venue addvenue(String name, String address, String crossstreet, String city, String state,
String zip, String phone, String categoryId, String geolat, String geolong, String geohacc,
String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_ADDVENUE), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpPost, new VenueParser());
}
/*
* /cities
*/
@SuppressWarnings("unchecked")
Group<City> cities() throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CITIES));
return (Group<City>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CityParser()));
}
/*
* /checkins?
*/
@SuppressWarnings("unchecked")
Group<Checkin> checkins(String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CHECKINS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet,
new GroupParser(new CheckinParser()));
}
/*
* /checkin?vid=1234&venue=Noc%20Noc&shout=Come%20here&private=0&twitter=1
*/
CheckinResult checkin(String vid, String venue, String geolat, String geolong, String geohacc,
String geovacc, String geoalt, String shout, boolean isPrivate, boolean tellFollowers,
boolean twitter, boolean facebook) throws FoursquareException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_CHECKIN), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("venue", venue), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("shout", shout), //
new BasicNameValuePair("private", (isPrivate) ? "1" : "0"), //
new BasicNameValuePair("followers", (tellFollowers) ? "1" : "0"), //
new BasicNameValuePair("twitter", (twitter) ? "1" : "0"), //
new BasicNameValuePair("facebook", (facebook) ? "1" : "0"), //
new BasicNameValuePair("markup", "android")); // used only by android for checkin result 'extras'.
return (CheckinResult) mHttpApi.doHttpRequest(httpPost, new CheckinResultParser());
}
/**
* /user?uid=9937
*/
User user(String uid, boolean mayor, boolean badges, boolean stats, String geolat, String geolong,
String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_USER), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("mayor", (mayor) ? "1" : "0"), //
new BasicNameValuePair("badges", (badges) ? "1" : "0"), //
new BasicNameValuePair("stats", (stats) ? "1" : "0"), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (User) mHttpApi.doHttpRequest(httpGet, new UserParser());
}
/**
* /venues?geolat=37.770900&geolong=-122.43698
*/
@SuppressWarnings("unchecked")
Group<Group<Venue>> venues(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String query, int limit) throws FoursquareException, FoursquareError,
IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUES), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("q", query), //
new BasicNameValuePair("l", String.valueOf(limit)));
return (Group<Group<Venue>>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new GroupParser(new VenueParser())));
}
/**
* /venue?vid=1234
*/
Venue venue(String vid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_VENUE), //
new BasicNameValuePair("vid", vid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Venue) mHttpApi.doHttpRequest(httpGet, new VenueParser());
}
/**
* /tips?geolat=37.770900&geolong=-122.436987&l=1
*/
@SuppressWarnings("unchecked")
Group<Tip> tips(String geolat, String geolong, String geohacc, String geovacc,
String geoalt, String uid, String filter, String sort, int limit) throws FoursquareException,
FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIPS), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("filter", filter), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Tip>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TipParser()));
}
/**
* /todos?geolat=37.770900&geolong=-122.436987&l=1&sort=[recent|nearby]
*/
@SuppressWarnings("unchecked")
Group<Todo> todos(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt, boolean recent, boolean nearby, int limit)
throws FoursquareException, FoursquareError, IOException {
String sort = null;
if (recent) {
sort = "recent";
} else if (nearby) {
sort = "nearby";
}
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TODOS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt), //
new BasicNameValuePair("sort", sort), //
new BasicNameValuePair("l", String.valueOf(limit)) //
);
return (Group<Todo>) mHttpApi.doHttpRequest(httpGet, new GroupParser(
new TodoParser()));
}
/*
* /friends?uid=9937
*/
@SuppressWarnings("unchecked")
Group<User> friends(String uid, String geolat, String geolong, String geohacc, String geovacc,
String geoalt) throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIENDS), //
new BasicNameValuePair("uid", uid), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/requests
*/
@SuppressWarnings("unchecked")
Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FRIEND_REQUESTS));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/*
* /friend/approve?uid=9937
*/
User friendApprove(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_APPROVE), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/deny?uid=9937
*/
User friendDeny(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_DENY), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/*
* /friend/sendrequest?uid=9937
*/
User friendSendrequest(String uid) throws FoursquareException, FoursquareCredentialsException,
FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FRIEND_SENDREQUEST), //
new BasicNameValuePair("uid", uid));
return (User) mHttpApi.doHttpRequest(httpPost, new UserParser());
}
/**
* /findfriends/byname?q=john doe, mary smith
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByName(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_NAME), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /findfriends/byphone?q=555-5555,555-5556
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByPhone(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/byfacebook?q=friendid,friendid,friendid
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByFacebook(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_FACEBOOK), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpPost, new GroupParser(new UserParser()));
}
/**
* /findfriends/bytwitter?q=yourtwittername
*/
@SuppressWarnings("unchecked")
public Group<User> findFriendsByTwitter(String text) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_FIND_FRIENDS_BY_TWITTER), //
new BasicNameValuePair("q", text));
return (Group<User>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new UserParser()));
}
/**
* /categories
*/
@SuppressWarnings("unchecked")
public Group<Category> categories() throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_CATEGORIES));
return (Group<Category>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CategoryParser()));
}
/**
* /history
*/
@SuppressWarnings("unchecked")
public Group<Checkin> history(String limit, String sinceid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_HISTORY),
new BasicNameValuePair("l", limit),
new BasicNameValuePair("sinceid", sinceid));
return (Group<Checkin>) mHttpApi.doHttpRequest(httpGet, new GroupParser(new CheckinParser()));
}
/**
* /mark/todo
*/
public Todo markTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* This is a hacky special case, hopefully the api will be updated in v2 for this.
* /mark/todo
*/
public Todo markTodoVenue(String vid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_TODO), //
new BasicNameValuePair("vid", vid));
return (Todo) mHttpApi.doHttpRequest(httpPost, new TodoParser());
}
/**
* /mark/ignore
*/
public Tip markIgnore(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_IGNORE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /mark/done
*/
public Tip markDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_MARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/todo
*/
public Tip unmarkTodo(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_TODO), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /unmark/done
*/
public Tip unmarkDone(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_UNMARK_DONE), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpPost, new TipParser());
}
/**
* /tip/detail?tid=1234
*/
public Tip tipDetail(String tid) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpGet httpGet = mHttpApi.createHttpGet(fullUrl(URL_API_TIP_DETAIL), //
new BasicNameValuePair("tid", tid));
return (Tip) mHttpApi.doHttpRequest(httpGet, new TipParser());
}
/**
* /findfriends/byphoneoremail?p=comma-sep-list-of-phones&e=comma-sep-list-of-emails
*/
public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_FIND_FRIENDS_BY_PHONE_OR_EMAIL), //
new BasicNameValuePair("p", phones),
new BasicNameValuePair("e", emails));
return (FriendInvitesResult) mHttpApi.doHttpRequest(httpPost, new FriendInvitesResultParser());
}
/**
* /invite/byemail?q=comma-sep-list-of-emails
*/
public Response inviteByEmail(String emails) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_INVITE_BY_EMAIL), //
new BasicNameValuePair("q", emails));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /settings/setpings?self=[on|off]
*/
public Settings setpings(boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair("self", on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /settings/setpings?uid=userid
*/
public Settings setpings(String userid, boolean on) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_SETPINGS), //
new BasicNameValuePair(userid, on ? "on" : "off"));
return (Settings) mHttpApi.doHttpRequest(httpPost, new SettingsParser());
}
/**
* /venue/flagclosed?vid=venueid
*/
public Response flagclosed(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_CLOSED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagmislocated?vid=venueid
*/
public Response flagmislocated(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_MISLOCATED), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/flagduplicate?vid=venueid
*/
public Response flagduplicate(String venueId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_FLAG_DUPLICATE), //
new BasicNameValuePair("vid", venueId));
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
/**
* /venue/prposeedit?vid=venueid&name=...
*/
public Response proposeedit(String venueId, String name, String address, String crossstreet,
String city, String state, String zip, String phone, String categoryId, String geolat,
String geolong, String geohacc, String geovacc, String geoalt) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
HttpPost httpPost = mHttpApi.createHttpPost(fullUrl(URL_API_VENUE_PROPOSE_EDIT), //
new BasicNameValuePair("vid", venueId), //
new BasicNameValuePair("name", name), //
new BasicNameValuePair("address", address), //
new BasicNameValuePair("crossstreet", crossstreet), //
new BasicNameValuePair("city", city), //
new BasicNameValuePair("state", state), //
new BasicNameValuePair("zip", zip), //
new BasicNameValuePair("phone", phone), //
new BasicNameValuePair("primarycategoryid", categoryId), //
new BasicNameValuePair("geolat", geolat), //
new BasicNameValuePair("geolong", geolong), //
new BasicNameValuePair("geohacc", geohacc), //
new BasicNameValuePair("geovacc", geovacc), //
new BasicNameValuePair("geoalt", geoalt) //
);
return (Response) mHttpApi.doHttpRequest(httpPost, new ResponseParser());
}
private String fullUrl(String url) {
return mApiBaseUrl + url + DATATYPE;
}
/**
* /user/update
* Need to bring this method under control like the rest of the api methods. Leaving it
* in this state as authorization will probably switch from basic auth in the near future
* anyway, will have to be updated. Also unlike the other methods, we're sending up data
* which aren't basic name/value pairs.
*/
public User userUpdate(String imagePathToJpg, String username, String password)
throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException {
String BOUNDARY = "------------------319831265358979362846";
String lineEnd = "\r\n";
String twoHyphens = "--";
int maxBufferSize = 8192;
File file = new File(imagePathToJpg);
FileInputStream fileInputStream = new FileInputStream(file);
URL url = new URL(fullUrl(URL_API_USER_UPDATE));
HttpURLConnection conn = mHttpApi.createHttpURLConnectionPost(url, BOUNDARY);
conn.setRequestProperty("Authorization", "Basic " + Base64Coder.encodeString(username + ":" + password));
// We are always saving the image to a jpg so we can use .jpg as the extension below.
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + BOUNDARY + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image,jpeg\";filename=\"" + "image.jpeg" +"\"" + lineEnd);
dos.writeBytes("Content-Type: " + "image/jpeg" + lineEnd);
dos.writeBytes(lineEnd);
int bytesAvailable = fileInputStream.available();
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
int totalBytesRead = bytesRead;
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
totalBytesRead = totalBytesRead + bytesRead;
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + BOUNDARY + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
dos.close();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder response = new StringBuilder();
String responseLine = "";
while ((responseLine = in.readLine()) != null) {
response.append(responseLine);
}
in.close();
try {
return (User)JSONUtils.consume(new UserParser(), response.toString());
} catch (Exception ex) {
throw new FoursquareParseException(
"Error parsing user photo upload response, invalid json.");
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/FoursquareHttpApiV1.java | Java | asf20 | 35,320 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface HttpApi {
abstract public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException;
abstract public String doHttpPost(String url, NameValuePair... nameValuePairs)
throws FoursquareCredentialsException, FoursquareParseException, FoursquareException,
IOException;
abstract public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs);
abstract public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs);
abstract public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary)
throws IOException;
}
| 07806919d-a | main/src/com/joelapenna/foursquare/http/HttpApi.java | Java | asf20 | 1,501 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;
import oauth.signpost.signature.SignatureMethod;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class HttpApiWithOAuth extends AbstractHttpApi {
protected static final Logger LOG = Logger.getLogger(HttpApiWithOAuth.class.getCanonicalName());
protected static final boolean DEBUG = Foursquare.DEBUG;
private OAuthConsumer mConsumer;
public HttpApiWithOAuth(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
}
public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
try {
if (DEBUG) LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI());
if (DEBUG) LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", "
+ mConsumer.getConsumerSecret());
if (DEBUG) LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", "
+ mConsumer.getTokenSecret());
mConsumer.sign(httpRequest);
} catch (OAuthMessageSignerException e) {
if (DEBUG) LOG.log(Level.FINE, "OAuthMessageSignerException", e);
throw new RuntimeException(e);
} catch (OAuthExpectationFailedException e) {
if (DEBUG) LOG.log(Level.FINE, "OAuthExpectationFailedException", e);
throw new RuntimeException(e);
}
return executeHttpRequest(httpRequest, parser);
}
public String doHttpPost(String url, NameValuePair... nameValuePairs) throws FoursquareError,
FoursquareParseException, IOException, FoursquareCredentialsException {
throw new RuntimeException("Haven't written this method yet.");
}
public void setOAuthConsumerCredentials(String key, String secret) {
mConsumer = new CommonsHttpOAuthConsumer(key, secret, SignatureMethod.HMAC_SHA1);
}
public void setOAuthTokenWithSecret(String token, String tokenSecret) {
verifyConsumer();
if (token == null && tokenSecret == null) {
if (DEBUG) LOG.log(Level.FINE, "Resetting consumer due to null token/secret.");
String consumerKey = mConsumer.getConsumerKey();
String consumerSecret = mConsumer.getConsumerSecret();
mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret,
SignatureMethod.HMAC_SHA1);
} else {
mConsumer.setTokenWithSecret(token, tokenSecret);
}
}
public boolean hasOAuthTokenWithSecret() {
verifyConsumer();
return (mConsumer.getToken() != null) && (mConsumer.getTokenSecret() != null);
}
private void verifyConsumer() {
if (mConsumer == null) {
throw new IllegalStateException(
"Cannot call method without setting consumer credentials.");
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/http/HttpApiWithOAuth.java | Java | asf20 | 4,071 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.AuthState;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import java.io.IOException;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class HttpApiWithBasicAuth extends AbstractHttpApi {
private HttpRequestInterceptor preemptiveAuth = new HttpRequestInterceptor() {
@Override
public void process(final HttpRequest request, final HttpContext context)
throws HttpException, IOException {
AuthState authState = (AuthState)context.getAttribute(ClientContext.TARGET_AUTH_STATE);
CredentialsProvider credsProvider = (CredentialsProvider)context
.getAttribute(ClientContext.CREDS_PROVIDER);
HttpHost targetHost = (HttpHost)context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
// If not auth scheme has been initialized yet
if (authState.getAuthScheme() == null) {
AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
// Obtain credentials matching the target host
org.apache.http.auth.Credentials creds = credsProvider.getCredentials(authScope);
// If found, generate BasicScheme preemptively
if (creds != null) {
authState.setAuthScheme(new BasicScheme());
authState.setCredentials(creds);
}
}
}
};
public HttpApiWithBasicAuth(DefaultHttpClient httpClient, String clientVersion) {
super(httpClient, clientVersion);
httpClient.addRequestInterceptor(preemptiveAuth, 0);
}
public FoursquareType doHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
return executeHttpRequest(httpRequest, parser);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/http/HttpApiWithBasicAuth.java | Java | asf20 | 2,833 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.http;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.util.JSONUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
abstract public class AbstractHttpApi implements HttpApi {
protected static final Logger LOG = Logger.getLogger(AbstractHttpApi.class.getCanonicalName());
protected static final boolean DEBUG = Foursquare.DEBUG;
private static final String DEFAULT_CLIENT_VERSION = "com.joelapenna.foursquare";
private static final String CLIENT_VERSION_HEADER = "User-Agent";
private static final int TIMEOUT = 60;
private final DefaultHttpClient mHttpClient;
private final String mClientVersion;
public AbstractHttpApi(DefaultHttpClient httpClient, String clientVersion) {
mHttpClient = httpClient;
if (clientVersion != null) {
mClientVersion = clientVersion;
} else {
mClientVersion = DEFAULT_CLIENT_VERSION;
}
}
public FoursquareType executeHttpRequest(HttpRequestBase httpRequest,
Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException,
FoursquareParseException, FoursquareException, IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
HttpResponse response = executeHttpRequest(httpRequest);
if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: "
+ httpRequest.getURI().toString());
int statusCode = response.getStatusLine().getStatusCode();
switch (statusCode) {
case 200:
String content = EntityUtils.toString(response.getEntity());
return JSONUtils.consume(parser, content);
case 400:
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 400");
throw new FoursquareException(
response.getStatusLine().toString(),
EntityUtils.toString(response.getEntity()));
case 401:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 401");
throw new FoursquareCredentialsException(response.getStatusLine().toString());
case 404:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 404");
throw new FoursquareException(response.getStatusLine().toString());
case 500:
response.getEntity().consumeContent();
if (DEBUG) LOG.log(Level.FINE, "HTTP Code: 500");
throw new FoursquareException("Foursquare is down. Try again later.");
default:
if (DEBUG) LOG.log(Level.FINE, "Default case for status code reached: "
+ response.getStatusLine().toString());
response.getEntity().consumeContent();
throw new FoursquareException("Error connecting to Foursquare: " + statusCode + ". Try again later.");
}
}
public String doHttpPost(String url, NameValuePair... nameValuePairs)
throws FoursquareCredentialsException, FoursquareParseException, FoursquareException,
IOException {
if (DEBUG) LOG.log(Level.FINE, "doHttpPost: " + url);
HttpPost httpPost = createHttpPost(url, nameValuePairs);
HttpResponse response = executeHttpRequest(httpPost);
if (DEBUG) LOG.log(Level.FINE, "executed HttpRequest for: " + httpPost.getURI().toString());
switch (response.getStatusLine().getStatusCode()) {
case 200:
try {
return EntityUtils.toString(response.getEntity());
} catch (ParseException e) {
throw new FoursquareParseException(e.getMessage());
}
case 401:
response.getEntity().consumeContent();
throw new FoursquareCredentialsException(response.getStatusLine().toString());
case 404:
response.getEntity().consumeContent();
throw new FoursquareException(response.getStatusLine().toString());
default:
response.getEntity().consumeContent();
throw new FoursquareException(response.getStatusLine().toString());
}
}
/**
* execute() an httpRequest catching exceptions and returning null instead.
*
* @param httpRequest
* @return
* @throws IOException
*/
public HttpResponse executeHttpRequest(HttpRequestBase httpRequest) throws IOException {
if (DEBUG) LOG.log(Level.FINE, "executing HttpRequest for: "
+ httpRequest.getURI().toString());
try {
mHttpClient.getConnectionManager().closeExpiredConnections();
return mHttpClient.execute(httpRequest);
} catch (IOException e) {
httpRequest.abort();
throw e;
}
}
public HttpGet createHttpGet(String url, NameValuePair... nameValuePairs) {
if (DEBUG) LOG.log(Level.FINE, "creating HttpGet for: " + url);
String query = URLEncodedUtils.format(stripNulls(nameValuePairs), HTTP.UTF_8);
HttpGet httpGet = new HttpGet(url + "?" + query);
httpGet.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
if (DEBUG) LOG.log(Level.FINE, "Created: " + httpGet.getURI());
return httpGet;
}
public HttpPost createHttpPost(String url, NameValuePair... nameValuePairs) {
if (DEBUG) LOG.log(Level.FINE, "creating HttpPost for: " + url);
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader(CLIENT_VERSION_HEADER, mClientVersion);
try {
httpPost.setEntity(new UrlEncodedFormEntity(stripNulls(nameValuePairs), HTTP.UTF_8));
} catch (UnsupportedEncodingException e1) {
throw new IllegalArgumentException("Unable to encode http parameters.");
}
if (DEBUG) LOG.log(Level.FINE, "Created: " + httpPost);
return httpPost;
}
public HttpURLConnection createHttpURLConnectionPost(URL url, String boundary)
throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setConnectTimeout(TIMEOUT * 1000);
conn.setRequestMethod("POST");
conn.setRequestProperty(CLIENT_VERSION_HEADER, mClientVersion);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
return conn;
}
private List<NameValuePair> stripNulls(NameValuePair... nameValuePairs) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
for (int i = 0; i < nameValuePairs.length; i++) {
NameValuePair param = nameValuePairs[i];
if (param.getValue() != null) {
if (DEBUG) LOG.log(Level.FINE, "Param: " + param);
params.add(param);
}
}
return params;
}
/**
* Create a thread-safe client. This client does not do redirecting, to allow us to capture
* correct "error" codes.
*
* @return HttpClient
*/
public static final DefaultHttpClient createHttpClient() {
// Sets up the http part of the service.
final SchemeRegistry supportedSchemes = new SchemeRegistry();
// Register the "http" protocol scheme, it is required
// by the default operator to look up socket factories.
final SocketFactory sf = PlainSocketFactory.getSocketFactory();
supportedSchemes.register(new Scheme("http", sf, 80));
supportedSchemes.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
// Set some client http client parameter defaults.
final HttpParams httpParams = createHttpParams();
HttpClientParams.setRedirecting(httpParams, false);
final ClientConnectionManager ccm = new ThreadSafeClientConnManager(httpParams,
supportedSchemes);
return new DefaultHttpClient(ccm, httpParams);
}
/**
* Create the default HTTP protocol parameters.
*/
private static final HttpParams createHttpParams() {
final HttpParams params = new BasicHttpParams();
// Turn off stale checking. Our connections break all the time anyway,
// and it's not worth it to pay the penalty of checking every time.
HttpConnectionParams.setStaleCheckingEnabled(params, false);
HttpConnectionParams.setConnectionTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSoTimeout(params, TIMEOUT * 1000);
HttpConnectionParams.setSocketBufferSize(params, 8192);
return params;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/http/AbstractHttpApi.java | Java | asf20 | 10,639 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import com.joelapenna.foursquare.util.ParcelUtils;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @date March 6, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Category implements FoursquareType, Parcelable {
/** The category's id. */
private String mId;
/** Full category path name, like Nightlife:Bars. */
private String mFullPathName;
/** Simple name of the category. */
private String mNodeName;
/** Url of the icon associated with this category. */
private String mIconUrl;
/** Categories can be nested within one another too. */
private Group<Category> mChildCategories;
public Category() {
mChildCategories = new Group<Category>();
}
private Category(Parcel in) {
mChildCategories = new Group<Category>();
mId = ParcelUtils.readStringFromParcel(in);
mFullPathName = ParcelUtils.readStringFromParcel(in);
mNodeName = ParcelUtils.readStringFromParcel(in);
mIconUrl = ParcelUtils.readStringFromParcel(in);
int numCategories = in.readInt();
for (int i = 0; i < numCategories; i++) {
Category category = in.readParcelable(Category.class.getClassLoader());
mChildCategories.add(category);
}
}
public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() {
public Category createFromParcel(Parcel in) {
return new Category(in);
}
@Override
public Category[] newArray(int size) {
return new Category[size];
}
};
public String getId() {
return mId;
}
public void setId(String id) {
mId = id;
}
public String getFullPathName() {
return mFullPathName;
}
public void setFullPathName(String fullPathName) {
mFullPathName = fullPathName;
}
public String getNodeName() {
return mNodeName;
}
public void setNodeName(String nodeName) {
mNodeName = nodeName;
}
public String getIconUrl() {
return mIconUrl;
}
public void setIconUrl(String iconUrl) {
mIconUrl = iconUrl;
}
public Group<Category> getChildCategories() {
return mChildCategories;
}
public void setChildCategories(Group<Category> categories) {
mChildCategories = categories;
}
@Override
public void writeToParcel(Parcel out, int flags) {
ParcelUtils.writeStringToParcel(out, mId);
ParcelUtils.writeStringToParcel(out, mFullPathName);
ParcelUtils.writeStringToParcel(out, mNodeName);
ParcelUtils.writeStringToParcel(out, mIconUrl);
out.writeInt(mChildCategories.size());
for (Category it : mChildCategories) {
out.writeParcelable(it, flags);
}
}
@Override
public int describeContents() {
return 0;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Category.java | Java | asf20 | 3,059 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
/**
* @date 2010-05-05
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Emails extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Emails.java | Java | asf20 | 322 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public interface FoursquareType {
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/FoursquareType.java | Java | asf20 | 169 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
import java.util.Collection;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Group<T extends FoursquareType> extends ArrayList<T> implements FoursquareType {
private static final long serialVersionUID = 1L;
private String mType;
public Group() {
super();
}
public Group(Collection<T> collection) {
super(collection);
}
public void setType(String type) {
mType = type;
}
public String getType() {
return mType;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Group.java | Java | asf20 | 627 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
/**
* @date 2010-05-05
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class FriendInvitesResult implements FoursquareType {
/**
* Users that are in our contact book by email or phone, are already on foursquare,
* but are not our friends.
*/
private Group<User> mContactsOnFoursquare;
/**
* Users not on foursquare, but in our contact book by email or phone. These are
* users we have not already sent an email invite to.
*/
private Emails mContactEmailsNotOnFoursquare;
/**
* A list of email addresses we've already sent email invites to.
*/
private Emails mContactEmailsNotOnFoursquareAlreadyInvited;
public FriendInvitesResult() {
mContactsOnFoursquare = new Group<User>();
mContactEmailsNotOnFoursquare = new Emails();
mContactEmailsNotOnFoursquareAlreadyInvited = new Emails();
}
public Group<User> getContactsOnFoursquare() {
return mContactsOnFoursquare;
}
public void setContactsOnFoursquare(Group<User> contactsOnFoursquare) {
mContactsOnFoursquare = contactsOnFoursquare;
}
public Emails getContactEmailsNotOnFoursquare() {
return mContactEmailsNotOnFoursquare;
}
public void setContactEmailsOnNotOnFoursquare(Emails emails) {
mContactEmailsNotOnFoursquare = emails;
}
public Emails getContactEmailsNotOnFoursquareAlreadyInvited() {
return mContactEmailsNotOnFoursquareAlreadyInvited;
}
public void setContactEmailsOnNotOnFoursquareAlreadyInvited(Emails emails) {
mContactEmailsNotOnFoursquareAlreadyInvited = emails;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/FriendInvitesResult.java | Java | asf20 | 1,757 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
/**
* @date April 14, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Types extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Types.java | Java | asf20 | 319 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
/**
* @date April 28, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Response implements FoursquareType {
private String mValue;
public Response() {
}
public String getValue() {
return mValue;
}
public void setValue(String value) {
mValue = value;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Response.java | Java | asf20 | 411 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.types;
import java.util.ArrayList;
import java.util.List;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Tags extends ArrayList<String> implements FoursquareType {
private static final long serialVersionUID = 1L;
public Tags() {
super();
}
public Tags(List<String> values) {
super();
addAll(values);
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/types/Tags.java | Java | asf20 | 452 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.types;
import com.joelapenna.foursquare.util.ParcelUtils;
import android.os.Parcel;
import android.os.Parcelable;
/**
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class Todo implements FoursquareType, Parcelable {
private String mCreated;
private String mId;
private Tip mTip;
public Todo() {
}
private Todo(Parcel in) {
mCreated = ParcelUtils.readStringFromParcel(in);
mId = ParcelUtils.readStringFromParcel(in);
if (in.readInt() == 1) {
mTip = in.readParcelable(Tip.class.getClassLoader());
}
}
public static final Parcelable.Creator<Todo> CREATOR = new Parcelable.Creator<Todo>() {
public Todo createFromParcel(Parcel in) {
return new Todo(in);
}
@Override
public Todo[] newArray(int size) {
return new Todo[size];
}
};
public String getCreated() {
return mCreated;
}
public void setCreated(String created) {
mCreated = created;
}
public String getId() {
return mId;
}
public void setId(String id) {
mId = id;
}
public Tip getTip() {
return mTip;
}
public void setTip(Tip tip) {
mTip = tip;
}
@Override
public void writeToParcel(Parcel out, int flags) {
ParcelUtils.writeStringToParcel(out, mCreated);
ParcelUtils.writeStringToParcel(out, mId);
if (mTip != null) {
out.writeInt(1);
out.writeParcelable(mTip, flags);
} else {
out.writeInt(0);
}
}
@Override
public int describeContents() {
return 0;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/types/Todo.java | Java | asf20 | 1,818 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.util;
import android.os.Parcel;
/**
* @date March 25, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ParcelUtils {
public static void writeStringToParcel(Parcel out, String str) {
if (str != null) {
out.writeInt(1);
out.writeString(str);
} else {
out.writeInt(0);
}
}
public static String readStringFromParcel(Parcel in) {
int flag = in.readInt();
if (flag == 1) {
return in.readString();
} else {
return null;
}
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/util/ParcelUtils.java | Java | asf20 | 659 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.util;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class MayorUtils {
public static final String TYPE_NOCHANGE = "nochange";
public static final String TYPE_NEW = "new";
public static final String TYPE_STOLEN = "stolen";
}
| 07806919d-a | main/src/com/joelapenna/foursquare/util/MayorUtils.java | Java | asf20 | 325 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare.util;
import com.joelapenna.foursquare.types.Venue;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueUtils {
public static final boolean isValid(Venue venue) {
return !(venue == null || venue.getId() == null || venue.getId().length() == 0);
}
public static final boolean hasValidLocation(Venue venue) {
boolean valid = false;
if (venue != null) {
String geoLat = venue.getGeolat();
String geoLong = venue.getGeolong();
if (!(geoLat == null || geoLat.length() == 0 || geoLong == null || geoLong.length() == 0)) {
if (geoLat != "0" || geoLong != "0") {
valid = true;
}
}
}
return valid;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/util/VenueUtils.java | Java | asf20 | 843 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.util;
/**
* This is not ideal.
*
* @date July 1, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class IconUtils {
private static IconUtils mInstance;
private boolean mRequestHighDensityIcons;
private IconUtils() {
mRequestHighDensityIcons = false;
}
public static IconUtils get() {
if (mInstance == null) {
mInstance = new IconUtils();
}
return mInstance;
}
public boolean getRequestHighDensityIcons() {
return mRequestHighDensityIcons;
}
public void setRequestHighDensityIcons(boolean requestHighDensityIcons) {
mRequestHighDensityIcons = requestHighDensityIcons;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/util/IconUtils.java | Java | asf20 | 791 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.util;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.parsers.json.TipParser;
import com.joelapenna.foursquare.types.FoursquareType;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
public class JSONUtils {
private static final boolean DEBUG = Foursquare.DEBUG;
private static final Logger LOG = Logger.getLogger(TipParser.class.getCanonicalName());
/**
* Takes a parser, a json string, and returns a foursquare type.
*/
public static FoursquareType consume(Parser<? extends FoursquareType> parser, String content)
throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException {
if (DEBUG) {
LOG.log(Level.FINE, "http response: " + content);
}
try {
// The v1 API returns the response raw with no wrapper. Depending on the
// type of API call, the content might be a JSONObject or a JSONArray.
// Since JSONArray does not derive from JSONObject, we need to check for
// either of these cases to parse correctly.
JSONObject json = new JSONObject(content);
Iterator<String> it = (Iterator<String>)json.keys();
if (it.hasNext()) {
String key = (String)it.next();
if (key.equals("error")) {
throw new FoursquareException(json.getString(key));
} else {
Object obj = json.get(key);
if (obj instanceof JSONArray) {
return parser.parse((JSONArray)obj);
} else {
return parser.parse((JSONObject)obj);
}
}
} else {
throw new FoursquareException("Error parsing JSON response, object had no single child key.");
}
} catch (JSONException ex) {
throw new FoursquareException("Error parsing JSON response: " + ex.getMessage());
}
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/util/JSONUtils.java | Java | asf20 | 2,556 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquare;
import com.joelapenna.foursquare.error.FoursquareCredentialsException;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.error.FoursquareParseException;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.Credentials;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Settings;
import com.joelapenna.foursquare.types.Tip;
import com.joelapenna.foursquare.types.Todo;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import android.net.Uri;
import android.text.TextUtils;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class Foursquare {
private static final Logger LOG = Logger.getLogger("com.joelapenna.foursquare");
public static final boolean DEBUG = false;
public static final boolean PARSER_DEBUG = false;
public static final String FOURSQUARE_API_DOMAIN = "api.foursquare.com";
public static final String FOURSQUARE_MOBILE_ADDFRIENDS = "http://m.foursquare.com/addfriends";
public static final String FOURSQUARE_MOBILE_FRIENDS = "http://m.foursquare.com/friends";
public static final String FOURSQUARE_MOBILE_SIGNUP = "http://m.foursquare.com/signup";
public static final String FOURSQUARE_PREFERENCES = "http://foursquare.com/settings";
public static final String MALE = "male";
public static final String FEMALE = "female";
private String mPhone;
private String mPassword;
private FoursquareHttpApiV1 mFoursquareV1;
@V1
public Foursquare(FoursquareHttpApiV1 httpApi) {
mFoursquareV1 = httpApi;
}
public void setCredentials(String phone, String password) {
mPhone = phone;
mPassword = password;
mFoursquareV1.setCredentials(phone, password);
}
@V1
public void setOAuthToken(String token, String secret) {
mFoursquareV1.setOAuthTokenWithSecret(token, secret);
}
@V1
public void setOAuthConsumerCredentials(String oAuthConsumerKey, String oAuthConsumerSecret) {
mFoursquareV1.setOAuthConsumerCredentials(oAuthConsumerKey, oAuthConsumerSecret);
}
public void clearAllCredentials() {
setCredentials(null, null);
setOAuthToken(null, null);
}
@V1
public boolean hasCredentials() {
return mFoursquareV1.hasCredentials() && mFoursquareV1.hasOAuthTokenWithSecret();
}
@V1
public boolean hasLoginAndPassword() {
return mFoursquareV1.hasCredentials();
}
@V1
public Credentials authExchange() throws FoursquareException, FoursquareError,
FoursquareCredentialsException, IOException {
if (mFoursquareV1 == null) {
throw new NoSuchMethodError(
"authExchange is unavailable without a consumer key/secret.");
}
return mFoursquareV1.authExchange(mPhone, mPassword);
}
@V1
public Tip addTip(String vid, String text, String type, Location location)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.addtip(vid, text, type, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
}
@V1
public Tip tipDetail(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.tipDetail(tid);
}
@V1
@LocationRequired
public Venue addVenue(String name, String address, String crossstreet, String city,
String state, String zip, String phone, String categoryId, Location location)
throws FoursquareException,
FoursquareError, IOException {
return mFoursquareV1.addvenue(name, address, crossstreet, city, state, zip, phone,
categoryId, location.geolat, location.geolong, location.geohacc, location.geovacc,
location.geoalt);
}
@V1
public CheckinResult checkin(String venueId, String venueName, Location location, String shout,
boolean isPrivate, boolean tellFollowers, boolean twitter, boolean facebook)
throws FoursquareException,
FoursquareError,
IOException {
return mFoursquareV1.checkin(venueId, venueName, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt, shout, isPrivate,
tellFollowers, twitter, facebook);
}
@V1
public Group<Checkin> checkins(Location location) throws FoursquareException, FoursquareError,
IOException {
return mFoursquareV1.checkins(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
public Group<User> friends(String userId, Location location) throws FoursquareException,
FoursquareError, IOException {
return mFoursquareV1.friends(userId, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
}
@V1
public Group<User> friendRequests() throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.friendRequests();
}
@V1
public User friendApprove(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendApprove(userId);
}
@V1
public User friendDeny(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendDeny(userId);
}
@V1
public User friendSendrequest(String userId) throws FoursquareException,
FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.friendSendrequest(userId);
}
@V1
public Group<Tip> tips(Location location, String uid, String filter, String sort, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.tips(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, uid, filter, sort, limit);
}
@V1
public Group<Todo> todos(Location location, String uid, boolean recent, boolean nearby, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.todos(uid, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, recent, nearby, limit);
}
@V1
public User user(String user, boolean mayor, boolean badges, boolean stats, Location location)
throws FoursquareException, FoursquareError, IOException {
if (location != null) {
return mFoursquareV1.user(user, mayor, badges, stats, location.geolat, location.geolong,
location.geohacc, location.geovacc, location.geoalt);
} else {
return mFoursquareV1.user(user, mayor, badges, stats, null, null, null, null, null);
}
}
@V1
public Venue venue(String id, Location location) throws FoursquareException, FoursquareError,
IOException {
return mFoursquareV1.venue(id, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
@LocationRequired
public Group<Group<Venue>> venues(Location location, String query, int limit)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.venues(location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt, query, limit);
}
@V1
public Group<User> findFriendsByName(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByName(text);
}
@V1
public Group<User> findFriendsByPhone(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByPhone(text);
}
@V1
public Group<User> findFriendsByFacebook(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByFacebook(text);
}
@V1
public Group<User> findFriendsByTwitter(String text)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByTwitter(text);
}
@V1
public Group<Category> categories()
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.categories();
}
@V1
public Group<Checkin> history(String limit, String sinceid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.history(limit, sinceid);
}
@V1
public Todo markTodo(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markTodo(tid);
}
@V1
public Todo markTodoVenue(String vid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markTodoVenue(vid);
}
@V1
public Tip markIgnore(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markIgnore(tid);
}
@V1
public Tip markDone(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.markDone(tid);
}
@V1
public Tip unmarkTodo(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.unmarkTodo(tid);
}
@V1
public Tip unmarkDone(String tid)
throws FoursquareException, FoursquareError, IOException {
return mFoursquareV1.unmarkDone(tid);
}
@V1
public FriendInvitesResult findFriendsByPhoneOrEmail(String phones, String emails)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.findFriendsByPhoneOrEmail(phones, emails);
}
@V1
public Response inviteByEmail(String emails)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.inviteByEmail(emails);
}
@V1
public Settings setpings(boolean on)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.setpings(on);
}
@V1
public Settings setpings(String userid, boolean on)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.setpings(userid, on);
}
@V1
public Response flagclosed(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagclosed(venueid);
}
@V1
public Response flagmislocated(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagmislocated(venueid);
}
@V1
public Response flagduplicate(String venueid)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.flagduplicate(venueid);
}
@V1
public Response proposeedit(String venueId, String name, String address, String crossstreet,
String city, String state, String zip, String phone, String categoryId, Location location)
throws FoursquareException, FoursquareCredentialsException, FoursquareError, IOException {
return mFoursquareV1.proposeedit(venueId, name, address, crossstreet, city, state, zip,
phone, categoryId, location.geolat, location.geolong, location.geohacc,
location.geovacc, location.geoalt);
}
@V1
public User userUpdate(String imagePathToJpg, String username, String password)
throws SocketTimeoutException, IOException, FoursquareError, FoursquareParseException {
return mFoursquareV1.userUpdate(imagePathToJpg, username, password);
}
public static final FoursquareHttpApiV1 createHttpApi(String domain, String clientVersion,
boolean useOAuth) {
LOG.log(Level.INFO, "Using foursquare.com for requests.");
return new FoursquareHttpApiV1(domain, clientVersion, useOAuth);
}
public static final FoursquareHttpApiV1 createHttpApi(String clientVersion, boolean useOAuth) {
return createHttpApi(FOURSQUARE_API_DOMAIN, clientVersion, useOAuth);
}
public static final String createLeaderboardUrl(String userId, Location location) {
Uri.Builder builder = new Uri.Builder() //
.scheme("http") //
.authority("foursquare.com") //
.appendEncodedPath("/iphone/me") //
.appendQueryParameter("view", "all") //
.appendQueryParameter("scope", "friends") //
.appendQueryParameter("uid", userId);
if (!TextUtils.isEmpty(location.geolat)) {
builder.appendQueryParameter("geolat", location.geolat);
}
if (!TextUtils.isEmpty(location.geolong)) {
builder.appendQueryParameter("geolong", location.geolong);
}
if (!TextUtils.isEmpty(location.geohacc)) {
builder.appendQueryParameter("geohacc", location.geohacc);
}
if (!TextUtils.isEmpty(location.geovacc)) {
builder.appendQueryParameter("geovacc", location.geovacc);
}
return builder.build().toString();
}
/**
* This api is supported in the V1 API documented at:
* http://groups.google.com/group/foursquare-api/web/api-documentation
*/
@interface V1 {
}
/**
* This api call requires a location.
*/
@interface LocationRequired {
}
public static class Location {
String geolat = null;
String geolong = null;
String geohacc = null;
String geovacc = null;
String geoalt = null;
public Location() {
}
public Location(final String geolat, final String geolong, final String geohacc,
final String geovacc, final String geoalt) {
this.geolat = geolat;
this.geolong = geolong;
this.geohacc = geohacc;
this.geovacc = geovacc;
this.geoalt = geovacc;
}
public Location(final String geolat, final String geolong) {
this(geolat, geolong, null, null, null);
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/Foursquare.java | Java | asf20 | 15,243 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Emails;
import com.joelapenna.foursquare.types.FriendInvitesResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class FriendInvitesResultParser extends AbstractParser<FriendInvitesResult> {
@Override
public FriendInvitesResult parse(JSONObject json) throws JSONException {
FriendInvitesResult obj = new FriendInvitesResult();
if (json.has("users")) {
obj.setContactsOnFoursquare(
new GroupParser(
new UserParser()).parse(json.getJSONArray("users")));
}
if (json.has("emails")) {
Emails emails = new Emails();
if (json.optJSONObject("emails") != null) {
JSONObject emailsAsObject = json.getJSONObject("emails");
emails.add(emailsAsObject.getString("email"));
} else if (json.optJSONArray("emails") != null) {
JSONArray emailsAsArray = json.getJSONArray("emails");
for (int i = 0; i < emailsAsArray.length(); i++) {
emails.add(emailsAsArray.getString(i));
}
}
obj.setContactEmailsOnNotOnFoursquare(emails);
}
if (json.has("invited")) {
Emails emails = new Emails();
JSONArray array = json.getJSONArray("invited");
for (int i = 0; i < array.length(); i++) {
emails.add(array.getString(i));
}
obj.setContactEmailsOnNotOnFoursquareAlreadyInvited(emails);
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/FriendInvitesResultParser.java | Java | asf20 | 1,808 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.User;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class UserParser extends AbstractParser<User> {
@Override
public User parse(JSONObject json) throws JSONException {
User user = new User();
if (json.has("badges")) {
user.setBadges(
new GroupParser(
new BadgeParser()).parse(json.getJSONArray("badges")));
}
if (json.has("badgecount")) {
user.setBadgeCount(json.getInt("badgecount"));
}
if (json.has("checkin")) {
user.setCheckin(new CheckinParser().parse(json.getJSONObject("checkin")));
}
if (json.has("checkincount")) {
user.setCheckinCount(json.getInt("checkincount"));
}
if (json.has("created")) {
user.setCreated(json.getString("created"));
}
if (json.has("email")) {
user.setEmail(json.getString("email"));
}
if (json.has("facebook")) {
user.setFacebook(json.getString("facebook"));
}
if (json.has("firstname")) {
user.setFirstname(json.getString("firstname"));
}
if (json.has("followercount")) {
user.setFollowerCount(json.getInt("followercount"));
}
if (json.has("friendcount")) {
user.setFriendCount(json.getInt("friendcount"));
}
if (json.has("friendsincommon")) {
user.setFriendsInCommon(
new GroupParser(
new UserParser()).parse(json.getJSONArray("friendsincommon")));
}
if (json.has("friendstatus")) {
user.setFriendstatus(json.getString("friendstatus"));
}
if (json.has("gender")) {
user.setGender(json.getString("gender"));
}
if (json.has("hometown")) {
user.setHometown(json.getString("hometown"));
}
if (json.has("id")) {
user.setId(json.getString("id"));
}
if (json.has("lastname")) {
user.setLastname(json.getString("lastname"));
}
if (json.has("mayor")) {
user.setMayorships(
new GroupParser(
new VenueParser()).parse(json.getJSONArray("mayor")));
}
if (json.has("mayorcount")) {
user.setMayorCount(json.getInt("mayorcount"));
}
if (json.has("phone")) {
user.setPhone(json.getString("phone"));
}
if (json.has("photo")) {
user.setPhoto(json.getString("photo"));
}
if (json.has("settings")) {
user.setSettings(new SettingsParser().parse(json.getJSONObject("settings")));
}
if (json.has("tipcount")) {
user.setTipCount(json.getInt("tipcount"));
}
if (json.has("todocount")) {
user.setTodoCount(json.getInt("todocount"));
}
if (json.has("twitter")) {
user.setTwitter(json.getString("twitter"));
}
if (json.has("types")) {
user.setTypes(new TypesParser().parseAsJSONArray(json.getJSONArray("types")));
}
return user;
}
//@Override
//public String getObjectName() {
// return "user";
//}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/UserParser.java | Java | asf20 | 3,621 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Mayor;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class MayorParser extends AbstractParser<Mayor> {
@Override
public Mayor parse(JSONObject json) throws JSONException {
Mayor obj = new Mayor();
if (json.has("checkins")) {
obj.setCheckins(json.getString("checkins"));
}
if (json.has("count")) {
obj.setCount(json.getString("count"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("type")) {
obj.setType(json.getString("type"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/MayorParser.java | Java | asf20 | 1,023 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Tip;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TipParser extends AbstractParser<Tip> {
@Override
public Tip parse(JSONObject json) throws JSONException {
Tip obj = new Tip();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("stats")) {
obj.setStats(new TipParser.StatsParser().parse(json.getJSONObject("stats")));
}
if (json.has("status")) {
obj.setStatus(json.getString("status"));
}
if (json.has("text")) {
obj.setText(json.getString("text"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
public static class StatsParser extends AbstractParser<Tip.Stats> {
@Override
public Tip.Stats parse(JSONObject json) throws JSONException {
Tip.Stats stats = new Tip.Stats();
if (json.has("donecount")) {
stats.setDoneCount(json.getInt("donecount"));
}
if (json.has("todocount")) {
stats.setTodoCount(json.getInt("todocount"));
}
return stats;
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/TipParser.java | Java | asf20 | 1,857 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Badge;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class BadgeParser extends AbstractParser<Badge> {
@Override
public Badge parse(JSONObject json) throws JSONException {
Badge obj = new Badge();
if (json.has("description")) {
obj.setDescription(json.getString("description"));
}
if (json.has("icon")) {
obj.setIcon(json.getString("icon"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/BadgeParser.java | Java | asf20 | 878 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Response;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date April 28, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class ResponseParser extends AbstractParser<Response> {
@Override
public Response parse(JSONObject json) throws JSONException {
Response response = new Response();
response.setValue(json.getString("response"));
return response;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/ResponseParser.java | Java | asf20 | 559 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Settings;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class SettingsParser extends AbstractParser<Settings> {
@Override
public Settings parse(JSONObject json) throws JSONException {
Settings obj = new Settings();
if (json.has("feeds_key")) {
obj.setFeedsKey(json.getString("feeds_key"));
}
if (json.has("get_pings")) {
obj.setGetPings(json.getBoolean("get_pings"));
}
if (json.has("pings")) {
obj.setPings(json.getString("pings"));
}
if (json.has("sendtofacebook")) {
obj.setSendtofacebook(json.getBoolean("sendtofacebook"));
}
if (json.has("sendtotwitter")) {
obj.setSendtotwitter(json.getBoolean("sendtotwitter"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/SettingsParser.java | Java | asf20 | 1,059 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Types;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TypesParser extends AbstractParser<Types> {
@Override
public Types parse(JSONObject json) throws JSONException {
Types obj = new Types();
if (json.has("type")) {
obj.add(json.getString("type"));
}
return obj;
}
public Types parseAsJSONArray(JSONArray array) throws JSONException {
Types obj = new Types();
for (int i = 0, m = array.length(); i < m; i++) {
obj.add(array.getString(i));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/TypesParser.java | Java | asf20 | 858 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Data;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class DataParser extends AbstractParser<Data> {
@Override
public Data parse(JSONObject json) throws JSONException {
Data obj = new Data();
if (json.has("cityid")) {
obj.setCityid(json.getString("cityid"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("status")) {
obj.setStatus("1".equals(json.getString("status")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/DataParser.java | Java | asf20 | 793 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.CheckinResult;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CheckinResultParser extends AbstractParser<CheckinResult> {
@Override
public CheckinResult parse(JSONObject json) throws JSONException {
CheckinResult obj = new CheckinResult();
if (json.has("badges")) {
obj.setBadges(
new GroupParser(
new BadgeParser()).parse(json.getJSONArray("badges")));
}
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("markup")) {
obj.setMarkup(json.getString("markup"));
}
if (json.has("mayor")) {
obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor")));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("scores")) {
obj.setScoring(
new GroupParser(
new ScoreParser()).parse(json.getJSONArray("scores")));
}
if (json.has("specials")) {
obj.setSpecials(
new GroupParser(
new SpecialParser()).parse(json.getJSONArray("specials")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/CheckinResultParser.java | Java | asf20 | 1,728 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Beenhere;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class BeenhereParser extends AbstractParser<Beenhere> {
@Override
public Beenhere parse(JSONObject json) throws JSONException {
Beenhere obj = new Beenhere();
if (json.has("friends")) {
obj.setFriends(json.getBoolean("friends"));
}
if (json.has("me")) {
obj.setMe(json.getBoolean("me"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/BeenhereParser.java | Java | asf20 | 697 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Iterator;
import java.util.logging.Level;
/**
* Reference:
* http://www.json.org/javadoc/org/json/JSONObject.html
* http://www.json.org/javadoc/org/json/JSONArray.html
*
* @author Mark Wyszomierski (markww@gmail.com)
* @param <T>
*/
public class GroupParser extends AbstractParser<Group> {
private Parser<? extends FoursquareType> mSubParser;
public GroupParser(Parser<? extends FoursquareType> subParser) {
mSubParser = subParser;
}
/**
* When we encounter a JSONObject in a GroupParser, we expect one attribute
* named 'type', and then another JSONArray attribute.
*/
public Group<FoursquareType> parse(JSONObject json) throws JSONException {
Group<FoursquareType> group = new Group<FoursquareType>();
Iterator<String> it = (Iterator<String>)json.keys();
while (it.hasNext()) {
String key = it.next();
if (key.equals("type")) {
group.setType(json.getString(key));
} else {
Object obj = json.get(key);
if (obj instanceof JSONArray) {
parse(group, (JSONArray)obj);
} else {
throw new JSONException("Could not parse data.");
}
}
}
return group;
}
/**
* Here we are getting a straight JSONArray and do not expect the 'type' attribute.
*/
@Override
public Group parse(JSONArray array) throws JSONException {
Group<FoursquareType> group = new Group<FoursquareType>();
parse(group, array);
return group;
}
private void parse(Group group, JSONArray array) throws JSONException {
for (int i = 0, m = array.length(); i < m; i++) {
Object element = array.get(i);
FoursquareType item = null;
if (element instanceof JSONArray) {
item = mSubParser.parse((JSONArray)element);
} else {
item = mSubParser.parse((JSONObject)element);
}
group.add(item);
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/GroupParser.java | Java | asf20 | 2,439 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Score;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class ScoreParser extends AbstractParser<Score> {
@Override
public Score parse(JSONObject json) throws JSONException {
Score obj = new Score();
if (json.has("icon")) {
obj.setIcon(json.getString("icon"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("points")) {
obj.setPoints(json.getString("points"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/ScoreParser.java | Java | asf20 | 781 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.parsers.json.CategoryParser;
import com.joelapenna.foursquare.parsers.json.GroupParser;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.util.IconUtils;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CategoryParser extends AbstractParser<Category> {
@Override
public Category parse(JSONObject json) throws JSONException {
Category obj = new Category();
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("fullpathname")) {
obj.setFullPathName(json.getString("fullpathname"));
}
if (json.has("nodename")) {
obj.setNodeName(json.getString("nodename"));
}
if (json.has("iconurl")) {
// TODO: Remove this once api v2 allows icon request.
String iconUrl = json.getString("iconurl");
if (IconUtils.get().getRequestHighDensityIcons()) {
iconUrl = iconUrl.replace(".png", "_64.png");
}
obj.setIconUrl(iconUrl);
}
if (json.has("categories")) {
obj.setChildCategories(
new GroupParser(
new CategoryParser()).parse(json.getJSONArray("categories")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/CategoryParser.java | Java | asf20 | 1,530 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Stats;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class StatsParser extends AbstractParser<Stats> {
@Override
public Stats parse(JSONObject json) throws JSONException {
Stats obj = new Stats();
if (json.has("beenhere")) {
obj.setBeenhere(new BeenhereParser().parse(json.getJSONObject("beenhere")));
}
if (json.has("checkins")) {
obj.setCheckins(json.getString("checkins"));
}
if (json.has("herenow")) {
obj.setHereNow(json.getString("herenow"));
}
if (json.has("mayor")) {
obj.setMayor(new MayorParser().parse(json.getJSONObject("mayor")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/StatsParser.java | Java | asf20 | 956 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Special;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class SpecialParser extends AbstractParser<Special> {
@Override
public Special parse(JSONObject json) throws JSONException {
Special obj = new Special();
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("type")) {
obj.setType(json.getString("type"));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/SpecialParser.java | Java | asf20 | 910 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Todo;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date September 2, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class TodoParser extends AbstractParser<Todo> {
@Override
public Todo parse(JSONObject json) throws JSONException {
Todo obj = new Todo();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("tip")) {
obj.setTip(new TipParser().parse(json.getJSONObject("tip")));
}
if (json.has("todoid")) {
obj.setId(json.getString("todoid"));
}
return obj;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/TodoParser.java | Java | asf20 | 796 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Rank;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class RankParser extends AbstractParser<Rank> {
@Override
public Rank parse(JSONObject json) throws JSONException {
Rank obj = new Rank();
if (json.has("city")) {
obj.setCity(json.getString("city"));
}
if (json.has("message")) {
obj.setMessage(json.getString("message"));
}
if (json.has("position")) {
obj.setPosition(json.getString("position"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/RankParser.java | Java | asf20 | 790 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.parsers.json.Parser;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public abstract class AbstractParser<T extends FoursquareType> implements Parser<T> {
/**
* All derived parsers must implement parsing a JSONObject instance of themselves.
*/
public abstract T parse(JSONObject json) throws JSONException;
/**
* Only the GroupParser needs to implement this.
*/
public Group parse(JSONArray array) throws JSONException {
throw new JSONException("Unexpected JSONArray parse type encountered.");
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/AbstractParser.java | Java | asf20 | 903 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Tags;
import com.joelapenna.foursquare.types.Venue;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public class VenueParser extends AbstractParser<Venue> {
@Override
public Venue parse(JSONObject json) throws JSONException {
Venue obj = new Venue();
if (json.has("address")) {
obj.setAddress(json.getString("address"));
}
if (json.has("checkins")) {
obj.setCheckins(
new GroupParser(
new CheckinParser()).parse(json.getJSONArray("checkins")));
}
if (json.has("city")) {
obj.setCity(json.getString("city"));
}
if (json.has("cityid")) {
obj.setCityid(json.getString("cityid"));
}
if (json.has("crossstreet")) {
obj.setCrossstreet(json.getString("crossstreet"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("geolat")) {
obj.setGeolat(json.getString("geolat"));
}
if (json.has("geolong")) {
obj.setGeolong(json.getString("geolong"));
}
if (json.has("hasTodo")) {
obj.setHasTodo(json.getBoolean("hasTodo"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
if (json.has("phone")) {
obj.setPhone(json.getString("phone"));
}
if (json.has("primarycategory")) {
obj.setCategory(new CategoryParser().parse(json.getJSONObject("primarycategory")));
}
if (json.has("specials")) {
obj.setSpecials(
new GroupParser(
new SpecialParser()).parse(json.getJSONArray("specials")));
}
if (json.has("state")) {
obj.setState(json.getString("state"));
}
if (json.has("stats")) {
obj.setStats(new StatsParser().parse(json.getJSONObject("stats")));
}
if (json.has("tags")) {
obj.setTags(
new Tags(StringArrayParser.parse(json.getJSONArray("tags"))));
}
if (json.has("tips")) {
obj.setTips(
new GroupParser(
new TipParser()).parse(json.getJSONArray("tips")));
}
if (json.has("todos")) {
obj.setTodos(
new GroupParser(
new TodoParser()).parse(json.getJSONArray("todos")));
}
if (json.has("twitter")) {
obj.setTwitter(json.getString("twitter"));
}
if (json.has("zip")) {
obj.setZip(json.getString("zip"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/VenueParser.java | Java | asf20 | 3,034 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
import java.util.List;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class StringArrayParser {
public static List<String> parse(JSONArray json) throws JSONException {
List<String> array = new ArrayList<String>();
for (int i = 0, m = json.length(); i < m; i++) {
array.add(json.getString(i));
}
return array;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/StringArrayParser.java | Java | asf20 | 599 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Credentials;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CredentialsParser extends AbstractParser<Credentials> {
@Override
public Credentials parse(JSONObject json) throws JSONException {
Credentials obj = new Credentials();
if (json.has("oauth_token")) {
obj.setOauthToken(json.getString("oauth_token"));
}
if (json.has("oauth_token_secret")) {
obj.setOauthTokenSecret(json.getString("oauth_token_secret"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/CredentialsParser.java | Java | asf20 | 771 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.City;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CityParser extends AbstractParser<City> {
@Override
public City parse(JSONObject json) throws JSONException {
City obj = new City();
if (json.has("geolat")) {
obj.setGeolat(json.getString("geolat"));
}
if (json.has("geolong")) {
obj.setGeolong(json.getString("geolong"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("name")) {
obj.setName(json.getString("name"));
}
if (json.has("shortname")) {
obj.setShortname(json.getString("shortname"));
}
if (json.has("timezone")) {
obj.setTimezone(json.getString("timezone"));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/CityParser.java | Java | asf20 | 1,077 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.Checkin;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*
*/
public class CheckinParser extends AbstractParser<Checkin> {
@Override
public Checkin parse(JSONObject json) throws JSONException {
Checkin obj = new Checkin();
if (json.has("created")) {
obj.setCreated(json.getString("created"));
}
if (json.has("display")) {
obj.setDisplay(json.getString("display"));
}
if (json.has("distance")) {
obj.setDistance(json.getString("distance"));
}
if (json.has("id")) {
obj.setId(json.getString("id"));
}
if (json.has("ismayor")) {
obj.setIsmayor(json.getBoolean("ismayor"));
}
if (json.has("ping")) {
obj.setPing(json.getBoolean("ping"));
}
if (json.has("shout")) {
obj.setShout(json.getString("shout"));
}
if (json.has("user")) {
obj.setUser(new UserParser().parse(json.getJSONObject("user")));
}
if (json.has("venue")) {
obj.setVenue(new VenueParser().parse(json.getJSONObject("venue")));
}
return obj;
}
} | 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/CheckinParser.java | Java | asf20 | 1,432 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquare.parsers.json;
import com.joelapenna.foursquare.types.FoursquareType;
import com.joelapenna.foursquare.types.Group;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* @date July 13, 2010
* @author Mark Wyszomierski (markww@gmail.com)
*/
public interface Parser<T extends FoursquareType> {
public abstract T parse(JSONObject json) throws JSONException;
public Group parse(JSONArray array) throws JSONException;
}
| 07806919d-a | main/src/com/joelapenna/foursquare/parsers/json/Parser.java | Java | asf20 | 546 |
/**
* Copyright 2010 Tauno Talimaa
*/
package com.joelapenna.foursquared.providers;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareError;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.Foursquared;
import com.joelapenna.foursquared.FoursquaredSettings;
import com.joelapenna.foursquared.error.LocationException;
import com.joelapenna.foursquared.location.BestLocationListener;
import com.joelapenna.foursquared.location.LocationUtils;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.util.Log;
import java.io.IOException;
/**
* A ContentProvider for Foursquare search results.
*
* @author Tauno Talimaa (tauntz@gmail.com)
*/
public class GlobalSearchProvider extends ContentProvider {
// TODO: Implement search for friends by name/phone number/twitter ID when
// API is implemented in Foursquare.java
private static final String TAG = GlobalSearchProvider.class.getSimpleName();
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private static final String[] QSB_COLUMNS = {
"_id", SearchManager.SUGGEST_COLUMN_ICON_1, SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_SHORTCUT_ID,
SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING,
SearchManager.SUGGEST_COLUMN_INTENT_DATA, SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID
};
private static final int URI_TYPE_QUERY = 1;
private static final int URI_TYPE_SHORTCUT = 2;
private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
static {
sUriMatcher.addURI(Foursquared.PACKAGE_NAME, SearchManager.SUGGEST_URI_PATH_QUERY + "/*",
URI_TYPE_QUERY);
sUriMatcher.addURI(Foursquared.PACKAGE_NAME,
SearchManager.SUGGEST_URI_PATH_SHORTCUT + "/*", URI_TYPE_SHORTCUT);
}
public static final String VENUE_DIRECTORY = "venue";
public static final String FRIEND_DIRECTORY = "friend";
// TODO: Use the argument from SUGGEST_PARAMETER_LIMIT from the Uri passed
// to query() instead of the hardcoded value (this is available starting
// from API level 5)
private static final int VENUE_QUERY_LIMIT = 30;
private Foursquare mFoursquare;
@Override
public boolean onCreate() {
synchronized (this) {
if (mFoursquare == null) mFoursquare = Foursquared.createFoursquare(getContext());
}
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
String query = uri.getLastPathSegment();
MatrixCursor cursor = new MatrixCursor(QSB_COLUMNS);
switch (sUriMatcher.match(uri)) {
case URI_TYPE_QUERY:
if (DEBUG) {
Log.d(TAG, "Global search for venue name: " + query);
}
Group<Group<Venue>> venueGroups;
try {
venueGroups = mFoursquare.venues(LocationUtils
.createFoursquareLocation(getBestRecentLocation()), query,
VENUE_QUERY_LIMIT);
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue list for query: " + query, e);
return cursor;
}
for (int groupIndex = 0; groupIndex < venueGroups.size(); groupIndex++) {
Group<Venue> venueGroup = venueGroups.get(groupIndex);
if (DEBUG) {
Log.d(TAG, venueGroup.size() + " results for group: "
+ venueGroup.getType());
}
for (int venueIndex = 0; venueIndex < venueGroup.size(); venueIndex++) {
Venue venue = venueGroup.get(venueIndex);
if (DEBUG) {
Log.d(TAG, "Venue " + venueIndex + ": " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(),
com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(),
venue.getId(), "true", VENUE_DIRECTORY, venue.getId()
});
}
}
break;
case URI_TYPE_SHORTCUT:
if (DEBUG) {
Log.d(TAG, "Global search for venue ID: " + query);
}
Venue venue;
try {
venue = mFoursquare.venue(query, LocationUtils
.createFoursquareLocation(getBestRecentLocation()));
} catch (FoursquareError e) {
if (DEBUG) Log.e(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (LocationException e) {
if (DEBUG) Log.w(TAG, "Could not retrieve a recent location", e);
return cursor;
} catch (FoursquareException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
} catch (IOException e) {
if (DEBUG) Log.w(TAG, "Could not get venue details for venue ID: " + query, e);
return cursor;
}
if (DEBUG) {
Log.d(TAG, "Updated venue details: " + venue.getName() + " ("
+ venue.getAddress() + ")");
}
cursor.addRow(new Object[] {
venue.getId(), com.joelapenna.foursquared.R.drawable.venue_shortcut_icon,
venue.getName(), venue.getAddress(), venue.getName(), venue.getId(),
"true", VENUE_DIRECTORY, venue.getId()
});
break;
case UriMatcher.NO_MATCH:
if (DEBUG) {
Log.d(TAG, "No matching URI for: " + uri);
}
break;
}
return cursor;
}
@Override
public String getType(Uri uri) {
return SearchManager.SUGGEST_MIME_TYPE;
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
@Override
public Uri insert(Uri uri, ContentValues values) {
throw new UnsupportedOperationException();
}
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
throw new UnsupportedOperationException();
}
/**
* Convenience method for getting the most recent Location
*
* @return the most recent Locations
* @throws LocationException when no recent Location could be determined
*/
private Location getBestRecentLocation() throws LocationException {
BestLocationListener locationListener = new BestLocationListener();
locationListener.updateLastKnownLocation((LocationManager) getContext().getSystemService(
Context.LOCATION_SERVICE));
Location location = locationListener.getLastKnownLocation();
if (location != null) {
return location;
}
throw new LocationException();
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/providers/GlobalSearchProvider.java | Java | asf20 | 8,688 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.providers;
import android.content.SearchRecentSuggestionsProvider;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class VenueQuerySuggestionsProvider extends SearchRecentSuggestionsProvider {
public static final String AUTHORITY = "com.joelapenna.foursquared.providers.VenueQuerySuggestionsProvider";
public static final int MODE = DATABASE_MODE_QUERIES;
public VenueQuerySuggestionsProvider() {
super();
setupSuggestions(AUTHORITY, MODE);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/providers/VenueQuerySuggestionsProvider.java | Java | asf20 | 566 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
class FoursquaredException extends Exception {
private static final long serialVersionUID = 1L;
public FoursquaredException(String message) {
super(message);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/error/FoursquaredException.java | Java | asf20 | 318 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared.error;
/**
* @author Joe LaPenna (joe@joelapenna.com)
*/
public class LocationException extends FoursquaredException {
public LocationException() {
super("Unable to determine your location.");
}
public LocationException(String message) {
super(message);
}
private static final long serialVersionUID = 1L;
}
| 07806919d-a | main/src/com/joelapenna/foursquared/error/LocationException.java | Java | asf20 | 424 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.CategoryPickerAdapter;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
/**
* Presents the user with a list of all available categories from foursquare
* that they can use to label a new venue.
*
* @date March 7, 2010
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*/
public class CategoryPickerDialog extends Dialog {
private static final String TAG = "FriendRequestsActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private Foursquared mApplication;
private Group<Category> mCategories;
private ViewFlipper mViewFlipper;
private Category mChosenCategory;
private int mFirstDialogHeight;
public CategoryPickerDialog(Context context, Group<Category> categories, Foursquared application) {
super(context);
mApplication = application;
mCategories = categories;
mChosenCategory = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_picker_dialog);
setTitle(getContext().getResources().getString(R.string.category_picket_dialog_title));
mViewFlipper = (ViewFlipper) findViewById(R.id.categoryPickerViewFlipper);
mFirstDialogHeight = -1;
// By default we always have a top-level page.
Category root = new Category();
root.setNodeName("root");
root.setChildCategories(mCategories);
mViewFlipper.addView(makePage(root));
}
private View makePage(Category category) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.category_picker_page, null);
CategoryPickerPage page = new CategoryPickerPage();
page.ensureUI(view, mPageListItemSelected, category, mApplication
.getRemoteResourceManager());
view.setTag(page);
if (mViewFlipper.getChildCount() == 1 && mFirstDialogHeight == -1) {
mFirstDialogHeight = mViewFlipper.getChildAt(0).getHeight();
}
if (mViewFlipper.getChildCount() > 0) {
view.setLayoutParams(new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT, mFirstDialogHeight));
}
return view;
}
@Override
protected void onStop() {
super.onStop();
cleanupPageAdapters();
}
private void cleanupPageAdapters() {
for (int i = 0; i < mViewFlipper.getChildCount(); i++) {
CategoryPickerPage page = (CategoryPickerPage) mViewFlipper.getChildAt(i).getTag();
page.cleanup();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mViewFlipper.getChildCount() > 1) {
mViewFlipper.removeViewAt(mViewFlipper.getChildCount() - 1);
return true;
}
break;
}
return super.onKeyDown(keyCode, event);
}
/**
* After the user has dismissed the dialog, the parent activity can use this
* to see which category they picked, if any. Will return null if no
* category was picked.
*/
public Category getChosenCategory() {
return mChosenCategory;
}
private static class CategoryPickerPage {
private CategoryPickerAdapter mListAdapter;
private Category mCategory;
private PageListItemSelected mClickListener;
public void ensureUI(View view, PageListItemSelected clickListener, Category category,
RemoteResourceManager rrm) {
mCategory = category;
mClickListener = clickListener;
mListAdapter = new CategoryPickerAdapter(view.getContext(), rrm, category);
ListView listview = (ListView) view.findViewById(R.id.categoryPickerListView);
listview.setAdapter(mListAdapter);
listview.setOnItemClickListener(mOnItemClickListener);
LinearLayout llRootCategory = (LinearLayout) view
.findViewById(R.id.categoryPickerRootCategoryButton);
if (category.getNodeName().equals("root") == false) {
ImageView iv = (ImageView) view.findViewById(R.id.categoryPickerIcon);
try {
Bitmap bitmap = BitmapFactory.decodeStream(rrm.getInputStream(Uri
.parse(category.getIconUrl())));
iv.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon from disk.", e);
}
TextView tv = (TextView) view.findViewById(R.id.categoryPickerName);
tv.setText(category.getNodeName());
llRootCategory.setClickable(true);
llRootCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mClickListener.onCategorySelected(mCategory);
}
});
} else {
llRootCategory.setVisibility(View.GONE);
}
}
public void cleanup() {
mListAdapter.removeObserver();
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
mClickListener.onPageListItemSelcected((Category) mListAdapter.getItem(position));
}
};
}
private PageListItemSelected mPageListItemSelected = new PageListItemSelected() {
@Override
public void onPageListItemSelcected(Category category) {
// If the item has children, create a new page for it.
if (category.getChildCategories() != null && category.getChildCategories().size() > 0) {
mViewFlipper.addView(makePage(category));
mViewFlipper.showNext();
} else {
// This is a leaf node, finally the user's selection. Record the
// category
// then cancel ourselves, parent activity should pick us up
// after that.
mChosenCategory = category;
cancel();
}
}
@Override
public void onCategorySelected(Category category) {
// The user has chosen the category parent listed at the top of the
// current page.
mChosenCategory = category;
cancel();
}
};
private interface PageListItemSelected {
public void onPageListItemSelcected(Category category);
public void onCategorySelected(Category category);
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/CategoryPickerDialog.java | Java | asf20 | 7,738 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.types.Checkin;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.app.LoadableListActivity;
import com.joelapenna.foursquared.util.UserUtils;
import com.joelapenna.foursquared.widget.CheckinListAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
/**
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -refactored for display of straight checkins list (September 16, 2010).
*
*/
public class VenueCheckinsActivity extends LoadableListActivity {
public static final String TAG = "VenueCheckinsActivity";
public static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String INTENT_EXTRA_VENUE = Foursquared.PACKAGE_NAME
+ ".VenueCheckinsActivity.INTENT_EXTRA_VENUE";
private SeparatedListAdapter mListAdapter;
private StateHolder mStateHolder;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
} else {
if (getIntent().hasExtra(INTENT_EXTRA_VENUE)) {
mStateHolder = new StateHolder(
(Venue)getIntent().getExtras().getParcelable(INTENT_EXTRA_VENUE),
((Foursquared) getApplication()).getUserId());
} else {
Log.e(TAG, "VenueCheckinsActivity requires a venue parcel its intent extras.");
finish();
return;
}
}
ensureUi();
}
@Override
public void onPause() {
super.onPause();
if (isFinishing()) {
mListAdapter.removeObserver();
unregisterReceiver(mLoggedOutReceiver);
}
}
@Override
public Object onRetainNonConfigurationInstance() {
return mStateHolder;
}
private void ensureUi() {
mListAdapter = new SeparatedListAdapter(this);
if (mStateHolder.getCheckinsYou().size() > 0) {
String title = getResources().getString(R.string.venue_activity_people_count_you);
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsYou());
mListAdapter.addSection(title, adapter);
}
if (mStateHolder.getCheckinsFriends().size() > 0) {
String title = getResources().getString(
mStateHolder.getCheckinsOthers().size() == 1 ?
R.string.venue_activity_checkins_count_friends_single :
R.string.venue_activity_checkins_count_friends_plural,
mStateHolder.getCheckinsFriends().size());
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsFriends());
mListAdapter.addSection(title, adapter);
}
if (mStateHolder.getCheckinsOthers().size() > 0) {
boolean others = mStateHolder.getCheckinsYou().size() +
mStateHolder.getCheckinsFriends().size() > 0;
String title = getResources().getString(
mStateHolder.getCheckinsOthers().size() == 1 ?
(others ? R.string.venue_activity_checkins_count_others_single :
R.string.venue_activity_checkins_count_others_alone_single) :
(others ? R.string.venue_activity_checkins_count_others_plural :
R.string.venue_activity_checkins_count_others_alone_plural),
mStateHolder.getCheckinsOthers().size());
CheckinListAdapter adapter = new CheckinListAdapter(this,
((Foursquared) getApplication()).getRemoteResourceManager());
adapter.setGroup(mStateHolder.getCheckinsOthers());
mListAdapter.addSection(title, adapter);
}
ListView listView = getListView();
listView.setAdapter(mListAdapter);
listView.setSmoothScrollbarEnabled(true);
listView.setDividerHeight(0);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Checkin checkin = (Checkin) parent.getAdapter().getItem(position);
Intent intent = new Intent(VenueCheckinsActivity.this, UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_PARCEL, checkin.getUser());
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
startActivity(intent);
}
});
setTitle(getString(R.string.venue_checkins_activity_title, mStateHolder.getVenueName()));
}
private static class StateHolder {
private String mVenueName;
private Group<Checkin> mYou;
private Group<Checkin> mFriends;
private Group<Checkin> mOthers;
public StateHolder(Venue venue, String loggedInUserId) {
mVenueName = venue.getName();
mYou = new Group<Checkin>();
mFriends = new Group<Checkin>();
mOthers = new Group<Checkin>();
mYou.clear();
mFriends.clear();
mOthers.clear();
for (Checkin it : venue.getCheckins()) {
User user = it.getUser();
if (UserUtils.isFriend(user)) {
mFriends.add(it);
} else if (loggedInUserId.equals(user.getId())) {
mYou.add(it);
} else {
mOthers.add(it);
}
}
}
public String getVenueName() {
return mVenueName;
}
public Group<Checkin> getCheckinsYou() {
return mYou;
}
public Group<Checkin> getCheckinsFriends() {
return mFriends;
}
public Group<Checkin> getCheckinsOthers() {
return mOthers;
}
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/VenueCheckinsActivity.java | Java | asf20 | 7,339 |
/**
* Copyright 2009 Joe LaPenna
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.error.FoursquareException;
import com.joelapenna.foursquare.types.Category;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Response;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.location.LocationUtils;
import com.joelapenna.foursquared.util.NotificationsUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
/**
* Allows the user to add a new venue. This activity can also be used to submit
* edits to an existing venue. Pass a venue parcelable using the EXTRA_VENUE_TO_EDIT
* key to put the activity into edit mode.
*
* @author Joe LaPenna (joe@joelapenna.com)
* @author Mark Wyszomierski (markww@gmail.com)
* -Added support for using this activity to edit existing venues (June 8, 2010).
*/
public class AddVenueActivity extends Activity {
private static final String TAG = "AddVenueActivity";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
public static final String EXTRA_VENUE_TO_EDIT = "com.joelapenna.foursquared.VenueParcel";
private static final double MINIMUM_ACCURACY_FOR_ADDRESS = 100.0;
private static final int DIALOG_PICK_CATEGORY = 1;
private static final int DIALOG_ERROR = 2;
private StateHolder mStateHolder;
private EditText mNameEditText;
private EditText mAddressEditText;
private EditText mCrossstreetEditText;
private EditText mCityEditText;
private EditText mStateEditText;
private EditText mZipEditText;
private EditText mPhoneEditText;
private Button mAddOrEditVenueButton;
private LinearLayout mCategoryLayout;
private ImageView mCategoryImageView;
private TextView mCategoryTextView;
private ProgressBar mCategoryProgressBar;
private ProgressDialog mDlgProgress;
private TextWatcher mNameFieldWatcher = new TextWatcher() {
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
};
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (DEBUG) Log.d(TAG, "onReceive: " + intent);
finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (DEBUG) Log.d(TAG, "onCreate()");
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.add_venue_activity);
registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT));
mAddOrEditVenueButton = (Button) findViewById(R.id.addVenueButton);
mNameEditText = (EditText) findViewById(R.id.nameEditText);
mAddressEditText = (EditText) findViewById(R.id.addressEditText);
mCrossstreetEditText = (EditText) findViewById(R.id.crossstreetEditText);
mCityEditText = (EditText) findViewById(R.id.cityEditText);
mStateEditText = (EditText) findViewById(R.id.stateEditText);
mZipEditText = (EditText) findViewById(R.id.zipEditText);
mPhoneEditText = (EditText) findViewById(R.id.phoneEditText);
mCategoryLayout = (LinearLayout) findViewById(R.id.addVenueCategoryLayout);
mCategoryImageView = (ImageView) findViewById(R.id.addVenueCategoryIcon);
mCategoryTextView = (TextView) findViewById(R.id.addVenueCategoryTextView);
mCategoryProgressBar = (ProgressBar) findViewById(R.id.addVenueCategoryProgressBar);
mCategoryLayout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
showDialog(DIALOG_PICK_CATEGORY);
}
});
mCategoryLayout.setEnabled(false);
mAddOrEditVenueButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String name = mNameEditText.getText().toString();
String address = mAddressEditText.getText().toString();
String crossstreet = mCrossstreetEditText.getText().toString();
String city = mCityEditText.getText().toString();
String state = mStateEditText.getText().toString();
String zip = mZipEditText.getText().toString();
String phone = mPhoneEditText.getText().toString();
if (mStateHolder.getVenueBeingEdited() != null) {
if (TextUtils.isEmpty(name)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_name));
return;
} else if (TextUtils.isEmpty(address)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_address));
return;
} else if (TextUtils.isEmpty(city)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_city));
return;
} else if (TextUtils.isEmpty(state)) {
showDialogError(getResources().getString(
R.string.add_venue_activity_error_no_venue_state));
return;
}
}
mStateHolder.startTaskAddOrEditVenue(
AddVenueActivity.this,
new String[] {
name,
address,
crossstreet,
city,
state,
zip,
phone,
mStateHolder.getChosenCategory() != null ?
mStateHolder.getChosenCategory().getId() : ""
},
// If editing a venue, pass in its id.
mStateHolder.getVenueBeingEdited() != null ?
mStateHolder.getVenueBeingEdited().getId() : null);
}
});
mNameEditText.addTextChangedListener(mNameFieldWatcher);
Object retained = getLastNonConfigurationInstance();
if (retained != null && retained instanceof StateHolder) {
mStateHolder = (StateHolder) retained;
mStateHolder.setActivity(this);
setFields(mStateHolder.getAddressLookup());
setChosenCategory(mStateHolder.getChosenCategory());
if (mStateHolder.getCategories() != null && mStateHolder.getCategories().size() > 0) {
mCategoryLayout.setEnabled(true);
mCategoryProgressBar.setVisibility(View.GONE);
}
} else {
mStateHolder = new StateHolder();
mStateHolder.startTaskGetCategories(this);
// If passed the venue parcelable, then we are in 'edit' mode.
if (getIntent().getExtras() != null && getIntent().getExtras().containsKey(EXTRA_VENUE_TO_EDIT)) {
Venue venue = getIntent().getExtras().getParcelable(EXTRA_VENUE_TO_EDIT);
if (venue != null) {
mStateHolder.setVenueBeingEdited(venue);
setFields(venue);
setTitle(getResources().getString(R.string.add_venue_activity_label_edit_venue));
mAddOrEditVenueButton.setText(getResources().getString(
R.string.add_venue_activity_btn_submit_edits));
} else {
Log.e(TAG, "Null venue parcelable supplied at startup, will finish immediately.");
finish();
}
} else {
mStateHolder.startTaskAddressLookup(this);
}
}
}
@Override
public void onResume() {
super.onResume();
((Foursquared) getApplication()).requestLocationUpdates(true);
if (mStateHolder.getIsRunningTaskAddOrEditVenue()) {
startProgressBar();
}
}
@Override
public void onPause() {
super.onPause();
((Foursquared) getApplication()).removeLocationUpdates();
stopProgressBar();
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mLoggedOutReceiver);
}
@Override
public Object onRetainNonConfigurationInstance() {
mStateHolder.setActivity(null);
return mStateHolder;
}
private void showDialogError(String message) {
mStateHolder.setError(message);
showDialog(DIALOG_ERROR);
}
/**
* Set fields from an address lookup, only used when adding a venue. This is done
* to prepopulate some fields for the user.
*/
private void setFields(AddressLookup addressLookup) {
if (mStateHolder.getVenueBeingEdited() == null &&
addressLookup != null &&
addressLookup.getAddress() != null) {
// Don't fill in the street unless we're reasonably confident we
// know where the user is.
String address = addressLookup.getAddress().getAddressLine(0);
double accuracy = addressLookup.getLocation().getAccuracy();
if (address != null && (accuracy > 0.0 && accuracy < MINIMUM_ACCURACY_FOR_ADDRESS)) {
if (DEBUG) Log.d(TAG, "Accuracy good enough, setting address field.");
mAddressEditText.setText(address);
}
String city = addressLookup.getAddress().getLocality();
if (city != null) {
mCityEditText.setText(city);
}
String state = addressLookup.getAddress().getAdminArea();
if (state != null) {
mStateEditText.setText(state);
}
String zip = addressLookup.getAddress().getPostalCode();
if (zip != null) {
mZipEditText.setText(zip);
}
String phone = addressLookup.getAddress().getPhone();
if (phone != null) {
mPhoneEditText.setText(phone);
}
}
}
/**
* Set fields from an existing venue, this is only used when editing a venue.
*/
private void setFields(Venue venue) {
mNameEditText.setText(venue.getName());
mCrossstreetEditText.setText(venue.getCrossstreet());
mAddressEditText.setText(venue.getAddress());
mCityEditText.setText(venue.getCity());
mStateEditText.setText(venue.getState());
mZipEditText.setText(venue.getZip());
mPhoneEditText.setText(venue.getPhone());
}
private void startProgressBar() {
startProgressBar(
getResources().getString(
mStateHolder.getVenueBeingEdited() == null ?
R.string.add_venue_progress_bar_message_add_venue :
R.string.add_venue_progress_bar_message_edit_venue));
}
private void startProgressBar(String message) {
if (mDlgProgress == null) {
mDlgProgress = ProgressDialog.show(this, null, message);
}
mDlgProgress.show();
}
private void stopProgressBar() {
if (mDlgProgress != null) {
mDlgProgress.dismiss();
mDlgProgress = null;
}
}
private void onGetCategoriesTaskComplete(Group<Category> categories, Exception ex) {
mStateHolder.setIsRunningTaskGetCategories(false);
try {
// Populate the categories list now.
if (categories != null) {
mStateHolder.setCategories(categories);
mCategoryLayout.setEnabled(true);
mCategoryTextView.setText(getResources().getString(R.string.add_venue_activity_pick_category_label));
mCategoryProgressBar.setVisibility(View.GONE);
// If we are editing a venue, set its category here.
if (mStateHolder.getVenueBeingEdited() != null) {
Venue venue = mStateHolder.getVenueBeingEdited();
if (venue.getCategory() != null) {
setChosenCategory(venue.getCategory());
}
}
} else {
// If error, feed list adapter empty user group.
mStateHolder.setCategories(new Group<Category>());
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} finally {
}
stopIndeterminateProgressBar();
}
private void ooGetAddressLookupTaskComplete(AddressLookup addressLookup, Exception ex) {
mStateHolder.setIsRunningTaskAddressLookup(false);
stopIndeterminateProgressBar();
if (addressLookup != null) {
mStateHolder.setAddressLookup(addressLookup);
setFields(addressLookup);
} else {
// Nothing to do on failure, don't need to report.
}
}
private void onAddOrEditVenueTaskComplete(Venue venue, String venueIdIfEditing, Exception ex) {
mStateHolder.setIsRunningTaskAddOrEditVenue(false);
stopProgressBar();
if (venueIdIfEditing == null) {
if (venue != null) {
// If they added the venue ok, then send them to an activity displaying it
// so they can play around with it.
Intent intent = new Intent(AddVenueActivity.this, VenueActivity.class);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
startActivity(intent);
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
} else {
if (venue != null) {
// Editing the venue worked ok, just return to caller.
Toast.makeText(this, getResources().getString(
R.string.add_venue_activity_edit_venue_success),
Toast.LENGTH_SHORT).show();
finish();
} else {
// Error, let them hang out here.
NotificationsUtil.ToastReasonForFailure(this, ex);
}
}
}
private void stopIndeterminateProgressBar() {
if (mStateHolder.getIsRunningTaskAddressLookup() == false &&
mStateHolder.getIsRunningTaskGetCategories() == false) {
setProgressBarIndeterminateVisibility(false);
}
}
private static class AddOrEditVenueTask extends AsyncTask<Void, Void, Venue> {
private AddVenueActivity mActivity;
private String[] mParams;
private String mVenueIdIfEditing;
private Exception mReason;
private Foursquared mFoursquared;
private String mErrorMsgForEditVenue;
public AddOrEditVenueTask(AddVenueActivity activity,
String[] params,
String venueIdIfEditing) {
mActivity = activity;
mParams = params;
mVenueIdIfEditing = venueIdIfEditing;
mFoursquared = (Foursquared) activity.getApplication();
mErrorMsgForEditVenue = activity.getResources().getString(
R.string.add_venue_activity_edit_venue_fail);
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.startProgressBar();
}
@Override
protected Venue doInBackground(Void... params) {
try {
Foursquare foursquare = mFoursquared.getFoursquare();
Location location = mFoursquared.getLastKnownLocationOrThrow();
if (mVenueIdIfEditing == null) {
return foursquare.addVenue(
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
} else {
Response response =
foursquare.proposeedit(
mVenueIdIfEditing,
mParams[0], // name
mParams[1], // address
mParams[2], // cross street
mParams[3], // city
mParams[4], // state,
mParams[5], // zip
mParams[6], // phone
mParams[7], // category id
LocationUtils.createFoursquareLocation(location));
if (response != null && response.getValue().equals("ok")) {
// TODO: Come up with a better method than returning an empty venue on success.
return new Venue();
} else {
throw new Exception(mErrorMsgForEditVenue);
}
}
} catch (Exception e) {
Log.e(TAG, "Exception during add or edit venue.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Venue venue) {
if (DEBUG) Log.d(TAG, "onPostExecute()");
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(venue, mVenueIdIfEditing, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onAddOrEditVenueTaskComplete(null, mVenueIdIfEditing, mReason);
}
}
}
private static class AddressLookupTask extends AsyncTask<Void, Void, AddressLookup> {
private AddVenueActivity mActivity;
private Exception mReason;
public AddressLookupTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected AddressLookup doInBackground(Void... params) {
try {
Location location = ((Foursquared)mActivity.getApplication()).getLastKnownLocationOrThrow();
Geocoder geocoder = new Geocoder(mActivity);
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null && addresses.size() > 0) {
Log.i(TAG, "Address found: " + addresses.toString());
return new AddressLookup(location, addresses.get(0));
} else {
Log.i(TAG, "No address could be found for current location.");
throw new FoursquareException("No address could be found for the current geolocation.");
}
} catch (Exception ex) {
Log.e(TAG, "Error during address lookup.", ex);
mReason = ex;
}
return null;
}
@Override
protected void onPostExecute(AddressLookup address) {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(address, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.ooGetAddressLookupTaskComplete(null, mReason);
}
}
}
private static class GetCategoriesTask extends AsyncTask<Void, Void, Group<Category>> {
private AddVenueActivity mActivity;
private Exception mReason;
public GetCategoriesTask(AddVenueActivity activity) {
mActivity = activity;
}
public void setActivity(AddVenueActivity activity) {
mActivity = activity;
}
@Override
protected void onPreExecute() {
mActivity.setProgressBarIndeterminateVisibility(true);
}
@Override
protected Group<Category> doInBackground(Void... params) {
try {
Foursquared foursquared = (Foursquared) mActivity.getApplication();
Foursquare foursquare = foursquared.getFoursquare();
return foursquare.categories();
} catch (Exception e) {
if (DEBUG)
Log.d(TAG, "GetCategoriesTask: Exception doing send friend request.", e);
mReason = e;
}
return null;
}
@Override
protected void onPostExecute(Group<Category> categories) {
if (DEBUG) Log.d(TAG, "GetCategoriesTask: onPostExecute()");
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(categories, mReason);
}
}
@Override
protected void onCancelled() {
if (mActivity != null) {
mActivity.onGetCategoriesTaskComplete(null,
new Exception("Get categories task request cancelled."));
}
}
}
private static class StateHolder {
private AddressLookupTask mTaskGetAddress;
private AddressLookup mAddressLookup;
private boolean mIsRunningTaskAddressLookup;
private GetCategoriesTask mTaskGetCategories;
private Group<Category> mCategories;
private boolean mIsRunningTaskGetCategories;
private AddOrEditVenueTask mTaskAddOrEditVenue;
private boolean mIsRunningTaskAddOrEditVenue;
private Category mChosenCategory;
private Venue mVenueBeingEdited;
private String mError;
public StateHolder() {
mCategories = new Group<Category>();
mIsRunningTaskAddressLookup = false;
mIsRunningTaskGetCategories = false;
mIsRunningTaskAddOrEditVenue = false;
mVenueBeingEdited = null;
}
public void setCategories(Group<Category> categories) {
mCategories = categories;
}
public void setAddressLookup(AddressLookup addressLookup) {
mAddressLookup = addressLookup;
}
public Group<Category> getCategories() {
return mCategories;
}
public AddressLookup getAddressLookup() {
return mAddressLookup;
}
public Venue getVenueBeingEdited() {
return mVenueBeingEdited;
}
public void setVenueBeingEdited(Venue venue) {
mVenueBeingEdited = venue;
}
public void startTaskGetCategories(AddVenueActivity activity) {
mIsRunningTaskGetCategories = true;
mTaskGetCategories = new GetCategoriesTask(activity);
mTaskGetCategories.execute();
}
public void startTaskAddressLookup(AddVenueActivity activity) {
mIsRunningTaskAddressLookup = true;
mTaskGetAddress = new AddressLookupTask(activity);
mTaskGetAddress.execute();
}
public void startTaskAddOrEditVenue(AddVenueActivity activity, String[] params,
String venueIdIfEditing) {
mIsRunningTaskAddOrEditVenue = true;
mTaskAddOrEditVenue = new AddOrEditVenueTask(activity, params, venueIdIfEditing);
mTaskAddOrEditVenue.execute();
}
public void setActivity(AddVenueActivity activity) {
if (mTaskGetCategories != null) {
mTaskGetCategories.setActivity(activity);
}
if (mTaskGetAddress != null) {
mTaskGetAddress.setActivity(activity);
}
if (mTaskAddOrEditVenue != null) {
mTaskAddOrEditVenue.setActivity(activity);
}
}
public void setIsRunningTaskAddressLookup(boolean isRunning) {
mIsRunningTaskAddressLookup = isRunning;
}
public void setIsRunningTaskGetCategories(boolean isRunning) {
mIsRunningTaskGetCategories = isRunning;
}
public void setIsRunningTaskAddOrEditVenue(boolean isRunning) {
mIsRunningTaskAddOrEditVenue = isRunning;
}
public boolean getIsRunningTaskAddressLookup() {
return mIsRunningTaskAddressLookup;
}
public boolean getIsRunningTaskGetCategories() {
return mIsRunningTaskGetCategories;
}
public boolean getIsRunningTaskAddOrEditVenue() {
return mIsRunningTaskAddOrEditVenue;
}
public Category getChosenCategory() {
return mChosenCategory;
}
public void setChosenCategory(Category category) {
mChosenCategory = category;
}
public String getError() {
return mError;
}
public void setError(String error) {
mError = error;
}
}
private static class AddressLookup {
private Location mLocation;
private Address mAddress;
public AddressLookup(Location location, Address address) {
mLocation = location;
mAddress = address;
}
public Location getLocation() {
return mLocation;
}
public Address getAddress() {
return mAddress;
}
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_PICK_CATEGORY:
// When the user cancels the dialog (by hitting the 'back' key), we
// finish this activity. We don't listen to onDismiss() for this
// action, because a device rotation will fire onDismiss(), and our
// dialog would not be re-displayed after the rotation is complete.
CategoryPickerDialog dlg = new CategoryPickerDialog(
this,
mStateHolder.getCategories(),
((Foursquared)getApplication()));
dlg.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
CategoryPickerDialog dlg = (CategoryPickerDialog)dialog;
setChosenCategory(dlg.getChosenCategory());
removeDialog(DIALOG_PICK_CATEGORY);
}
});
return dlg;
case DIALOG_ERROR:
AlertDialog dlgInfo = new AlertDialog.Builder(this)
.setIcon(0)
.setTitle(getResources().getString(R.string.add_venue_progress_bar_title_edit_venue))
.setMessage(mStateHolder.getError()).create();
dlgInfo.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
removeDialog(DIALOG_ERROR);
}
});
return dlgInfo;
}
return null;
}
private void setChosenCategory(Category category) {
if (category == null) {
mCategoryTextView.setText(getResources().getString(
R.string.add_venue_activity_pick_category_label));
return;
}
try {
Bitmap bitmap = BitmapFactory.decodeStream(
((Foursquared)getApplication()).getRemoteResourceManager().getInputStream(
Uri.parse(category.getIconUrl())));
mCategoryImageView.setImageBitmap(bitmap);
} catch (IOException e) {
if (DEBUG) Log.e(TAG, "Error loading category icon.", e);
}
mCategoryTextView.setText(category.getNodeName());
// Record the chosen category.
mStateHolder.setChosenCategory(category);
if (canEnableSaveButton()) {
mAddOrEditVenueButton.setEnabled(canEnableSaveButton());
}
}
private boolean canEnableSaveButton() {
return mNameEditText.getText().length() > 0;
}
}
| 07806919d-a | main/src/com/joelapenna/foursquared/AddVenueActivity.java | Java | asf20 | 30,780 |
/**
* Copyright 2010 Mark Wyszomierski
*/
package com.joelapenna.foursquared;
import com.joelapenna.foursquare.Foursquare;
import com.joelapenna.foursquare.types.Badge;
import com.joelapenna.foursquare.types.CheckinResult;
import com.joelapenna.foursquare.types.Group;
import com.joelapenna.foursquare.types.Mayor;
import com.joelapenna.foursquare.types.Score;
import com.joelapenna.foursquare.types.Special;
import com.joelapenna.foursquare.types.User;
import com.joelapenna.foursquare.types.Venue;
import com.joelapenna.foursquared.util.Base64Coder;
import com.joelapenna.foursquared.util.RemoteResourceManager;
import com.joelapenna.foursquared.widget.BadgeWithIconListAdapter;
import com.joelapenna.foursquared.widget.ScoreListAdapter;
import com.joelapenna.foursquared.widget.SeparatedListAdapter;
import com.joelapenna.foursquared.widget.SpecialListAdapter;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import java.io.IOException;
import java.util.Observable;
import java.util.Observer;
/**
* Renders the result of a checkin using a CheckinResult object. This is called
* from CheckinExecuteActivity. It would be nicer to put this in another activity,
* but right now the CheckinResult is quite large and would require a good amount
* of work to add serializers for all its inner classes. This wouldn't be a huge
* problem, but maintaining it as the classes evolve could more trouble than it's
* worth.
*
* The only way the user can dismiss this dialog is by hitting the 'back' key.
* CheckingExecuteActivity depends on this so it knows when to finish() itself.
*
* @date March 3, 2010.
* @author Mark Wyszomierski (markww@gmail.com), foursquare.
*
*/
public class CheckinResultDialog extends Dialog
{
private static final String TAG = "CheckinResultDialog";
private static final boolean DEBUG = FoursquaredSettings.DEBUG;
private CheckinResult mCheckinResult;
private Handler mHandler;
private RemoteResourceManagerObserver mObserverMayorPhoto;
private Foursquared mApplication;
private String mExtrasDecoded;
private WebViewDialog mDlgWebViewExtras;
public CheckinResultDialog(Context context, CheckinResult result, Foursquared application) {
super(context, R.style.ThemeCustomDlgBase_ThemeCustomDlg);
mCheckinResult = result;
mApplication = application;
mHandler = new Handler();
mObserverMayorPhoto = null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.checkin_result_dialog);
setTitle(getContext().getResources().getString(R.string.checkin_title_result));
TextView tvMessage = (TextView)findViewById(R.id.textViewCheckinMessage);
if (mCheckinResult != null) {
tvMessage.setText(mCheckinResult.getMessage());
SeparatedListAdapter adapter = new SeparatedListAdapter(getContext());
// Add any badges the user unlocked as a result of this checkin.
addBadges(mCheckinResult.getBadges(), adapter, mApplication.getRemoteResourceManager());
// Add whatever points they got as a result of this checkin.
addScores(mCheckinResult.getScoring(), adapter, mApplication.getRemoteResourceManager());
// Add any specials that are nearby.
addSpecials(mCheckinResult.getSpecials(), adapter);
// Add a button below the mayor section which will launch a new webview if
// we have additional content from the server. This is base64 encoded and
// is supposed to be just dumped into a webview.
addExtras(mCheckinResult.getMarkup());
// List items construction complete.
ListView listview = (ListView)findViewById(R.id.listViewCheckinBadgesAndScores);
listview.setAdapter(adapter);
listview.setOnItemClickListener(mOnItemClickListener);
// Show mayor info if any.
addMayor(mCheckinResult.getMayor(), mApplication.getRemoteResourceManager());
} else {
// This shouldn't be possible but we've gotten a few crash reports showing that
// mCheckinResult is null on entry of this method.
Log.e(TAG, "Checkin result object was null on dialog creation.");
tvMessage.setText("Checked-in!");
}
}
@Override
protected void onStop() {
super.onStop();
if (mDlgWebViewExtras != null && mDlgWebViewExtras.isShowing()) {
mDlgWebViewExtras.dismiss();
}
if (mObserverMayorPhoto != null) {
mApplication.getRemoteResourceManager().deleteObserver(mObserverMayorPhoto);
}
}
private void addBadges(Group<Badge> badges, SeparatedListAdapter adapterMain, RemoteResourceManager rrm) {
if (badges == null || badges.size() < 1) {
return;
}
BadgeWithIconListAdapter adapter = new BadgeWithIconListAdapter(
getContext(), rrm, R.layout.badge_list_item);
adapter.setGroup(badges);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_result_dialog_badges),
adapter);
}
private void addScores(Group<Score> scores,
SeparatedListAdapter adapterMain,
RemoteResourceManager rrm) {
if (scores == null || scores.size() < 1) {
return;
}
// We make our own local score group because we'll inject the total as
// a new dummy score element.
Group<Score> scoresWithTotal = new Group<Score>();
// Total up the scoring.
int total = 0;
for (Score score : scores) {
total += Integer.parseInt(score.getPoints());
scoresWithTotal.add(score);
}
// Add a dummy score element to the group which is just the total.
Score scoreTotal = new Score();
scoreTotal.setIcon("");
scoreTotal.setMessage(getContext().getResources().getString(
R.string.checkin_result_dialog_score_total));
scoreTotal.setPoints(String.valueOf(total));
scoresWithTotal.add(scoreTotal);
// Give it all to the adapter now.
ScoreListAdapter adapter = new ScoreListAdapter(getContext(), rrm);
adapter.setGroup(scoresWithTotal);
adapterMain.addSection(getContext().getResources().getString(R.string.checkin_score), adapter);
}
private void addMayor(Mayor mayor, RemoteResourceManager rrm) {
LinearLayout llMayor = (LinearLayout)findViewById(R.id.llCheckinMayorInfo);
if (mayor == null) {
llMayor.setVisibility(View.GONE);
return;
} else {
llMayor.setVisibility(View.VISIBLE);
}
// Set the mayor message.
TextView tvMayorMessage = (TextView)findViewById(R.id.textViewCheckinMayorMessage);
tvMayorMessage.setText(mayor.getMessage());
// A few cases here for the image to display.
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (mCheckinResult.getMayor().getUser() == null) {
// I am still the mayor.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("nochange")) {
// Someone else is mayor.
// Show that user's photo from the network. If not already on disk,
// we need to start a fetch for it.
Uri photoUri = populateMayorImageFromNetwork();
if (photoUri != null) {
mApplication.getRemoteResourceManager().request(photoUri);
mObserverMayorPhoto = new RemoteResourceManagerObserver();
rrm.addObserver(mObserverMayorPhoto);
}
addClickHandlerForMayorImage(ivMayor, mayor.getUser().getId());
}
else if (mCheckinResult.getMayor().getType().equals("new")) {
// I just became the new mayor as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
else if (mCheckinResult.getMayor().getType().equals("stolen")) {
// I stole mayorship from someone else as a result of this checkin.
// Just show the crown icon.
ivMayor.setImageDrawable(getContext().getResources().getDrawable(R.drawable.crown));
}
}
private void addSpecials(Group<Special> specials,
SeparatedListAdapter adapterMain) {
if (specials == null || specials.size() < 1) {
return;
}
// For now, get rid of specials not tied to the current venue. If the special is
// tied to this venue, then there would be no <venue> block associated with the
// special. If there is a <venue> block associated with the special, it means it
// belongs to another venue and we won't show it.
Group<Special> localSpecials = new Group<Special>();
for (Special it : specials) {
if (it.getVenue() == null) {
localSpecials.add(it);
}
}
if (localSpecials.size() < 1) {
return;
}
SpecialListAdapter adapter = new SpecialListAdapter(getContext());
adapter.setGroup(localSpecials);
adapterMain.addSection(
getContext().getResources().getString(R.string.checkin_specials), adapter);
}
private void addExtras(String extras) {
LinearLayout llExtras = (LinearLayout)findViewById(R.id.llCheckinExtras);
if (TextUtils.isEmpty(extras)) {
llExtras.setVisibility(View.GONE);
return;
} else {
llExtras.setVisibility(View.VISIBLE);
}
// The server sent us additional content, it is base64 encoded, so decode it now.
mExtrasDecoded = Base64Coder.decodeString(extras);
// TODO: Replace with generic extras method.
// Now when the user clicks this 'button' pop up yet another dialog dedicated
// to showing just the webview and the decoded content. This is not ideal but
// having problems putting a webview directly inline with the rest of the
// checkin content, we can improve this later.
llExtras.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mDlgWebViewExtras = new WebViewDialog(getContext(), "SXSW Stats", mExtrasDecoded);
mDlgWebViewExtras.show();
}
});
}
private void addClickHandlerForMayorImage(View view, final String userId) {
// Show a user detail activity when the user clicks on the mayor's image.
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), UserDetailsActivity.class);
intent.putExtra(UserDetailsActivity.EXTRA_USER_ID, userId);
intent.putExtra(UserDetailsActivity.EXTRA_SHOW_ADD_FRIEND_OPTIONS, true);
v.getContext().startActivity(intent);
}
});
}
/**
* If we have to download the user's photo from the net (wasn't already in cache)
* will return the uri to launch.
*/
private Uri populateMayorImageFromNetwork() {
User user = mCheckinResult.getMayor().getUser();
ImageView ivMayor = (ImageView)findViewById(R.id.imageViewCheckinMayor);
if (user != null) {
Uri photoUri = Uri.parse(user.getPhoto());
try {
Bitmap bitmap = BitmapFactory.decodeStream(
mApplication.getRemoteResourceManager().getInputStream(photoUri));
ivMayor.setImageBitmap(bitmap);
return null;
} catch (IOException e) {
// User's image wasn't already in the cache, have to start a request for it.
if (Foursquare.MALE.equals(user.getGender())) {
ivMayor.setImageResource(R.drawable.blank_boy);
} else {
ivMayor.setImageResource(R.drawable.blank_girl);
}
return photoUri;
}
}
return null;
}
/**
* Called if the remote resource manager downloads the mayor's photo.
* If the photo is already on disk, this observer will never be used.
*/
private class RemoteResourceManagerObserver implements Observer {
@Override
public void update(Observable observable, Object data) {
if (DEBUG) Log.d(TAG, "Fetcher got: " + data);
mHandler.post(new Runnable() {
@Override
public void run() {
populateMayorImageFromNetwork();
}
});
}
}
private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Object obj = adapter.getItemAtPosition(position);
if (obj != null) {
if (obj instanceof Special) {
// When the user clicks on a special, if the venue is different than
// the venue the user checked in at (already being viewed) then show
// a new venue activity for that special.
Venue venue = ((Special)obj).getVenue();
if (venue != null) {
Intent intent = new Intent(getContext(), VenueActivity.class);
intent.setAction(Intent.ACTION_VIEW);
intent.putExtra(VenueActivity.INTENT_EXTRA_VENUE_PARTIAL, venue);
getContext().startActivity(intent);
}
}
}
}
};
}
| 07806919d-a | main/src/com/joelapenna/foursquared/CheckinResultDialog.java | Java | asf20 | 14,998 |