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
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by GoogleCodeTest.rc // #define IDD_ABOUTBOX 100 #define IDP_OLE_INIT_FAILED 100 #define IDR_POPUP_EDIT 119 #define ID_STATUSBAR_PANE1 120 #define ID_STATUSBAR_PANE2 121 #define IDS_STATUS_PANE1 122 #define IDS_STATUS_PANE2 123 #define IDS_TOOLBAR_STANDARD 124 #define IDS_TOOLBAR_CUSTOMIZE 125 #define ID_VIEW_CUSTOMIZE 126 #define IDR_MAINFRAME 128 #define IDR_MAINFRAME_256 129 #define IDR_GoogleCodeTestTYPE 130 #define ID_WINDOW_MANAGER 131 #define ID_VIEW_FILEVIEW 133 #define ID_VIEW_CLASSVIEW 134 #define ID_PROPERTIES 135 #define ID_OPEN 136 #define ID_OPEN_WITH 137 #define ID_DUMMY_COMPILE 138 #define ID_CLASS_ADD_MEMBER_FUNCTION 139 #define ID_CLASS_ADD_MEMBER_VARIABLE 140 #define ID_CLASS_DEFINITION 141 #define ID_CLASS_PROPERTIES 142 #define ID_NEW_FOLDER 143 #define ID_SORT_MENU 144 #define ID_SORTING_GROUPBYTYPE 145 #define ID_SORTING_SORTALPHABETIC 146 #define ID_SORTING_SORTBYTYPE 147 #define ID_SORTING_SORTBYACCESS 148 #define ID_VIEW_OUTPUTWND 149 #define ID_VIEW_PROPERTIESWND 150 #define ID_SORTPROPERTIES 151 #define ID_PROPERTIES1 152 #define ID_PROPERTIES2 153 #define ID_EXPAND_ALL 154 #define IDS_FILE_VIEW 155 #define IDS_CLASS_VIEW 156 #define IDS_OUTPUT_WND 157 #define IDS_PROPERTIES_WND 158 #define IDI_FILE_VIEW 161 #define IDI_FILE_VIEW_HC 162 #define IDI_CLASS_VIEW 163 #define IDI_CLASS_VIEW_HC 164 #define IDI_OUTPUT_WND 165 #define IDI_OUTPUT_WND_HC 166 #define IDI_PROPERTIES_WND 167 #define IDI_PROPERTIES_WND_HC 168 #define IDR_EXPLORER 169 #define IDB_EXPLORER_24 170 #define IDR_SORT 171 #define IDB_SORT_24 172 #define IDR_POPUP_SORT 173 #define IDR_POPUP_EXPLORER 174 #define IDB_FILE_VIEW 175 #define IDB_FILE_VIEW_24 176 #define IDB_CLASS_VIEW 177 #define IDB_CLASS_VIEW_24 178 #define IDR_MENU_IMAGES 179 #define IDB_MENU_IMAGES_24 180 #define ID_TOOLS_MACRO 181 #define IDR_OUTPUT_POPUP 182 #define IDR_PROPERTIES 183 #define IDB_PROPERTIES_HC 184 #define IDR_THEME_MENU 200 #define ID_SET_STYLE 201 #define ID_VIEW_APPLOOK_WIN_2000 205 #define ID_VIEW_APPLOOK_OFF_XP 206 #define ID_VIEW_APPLOOK_WIN_XP 207 #define ID_VIEW_APPLOOK_OFF_2003 208 #define ID_VIEW_APPLOOK_VS_2005 209 #define ID_VIEW_APPLOOK_VS_2008 210 #define ID_VIEW_APPLOOK_OFF_2007_BLUE 215 #define ID_VIEW_APPLOOK_OFF_2007_BLACK 216 #define ID_VIEW_APPLOOK_OFF_2007_SILVER 217 #define ID_VIEW_APPLOOK_OFF_2007_AQUA 218 #define ID_VIEW_APPLOOK_WINDOWS_7 219 #define IDS_BUILD_TAB 300 #define IDS_DEBUG_TAB 301 #define IDS_FIND_TAB 302 #define IDS_EXPLORER 305 #define IDS_EDIT_MENU 306 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 310 #define _APS_NEXT_CONTROL_VALUE 1000 #define _APS_NEXT_SYMED_VALUE 310 #define _APS_NEXT_COMMAND_VALUE 32771 #endif #endif
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/Resource.h
C
asf20
3,120
// GoogleCodeTest.h : main header file for the GoogleCodeTest application // #pragma once #ifndef __AFXWIN_H__ #error "include 'stdafx.h' before including this file for PCH" #endif #include "resource.h" // main symbols // CGoogleCodeTestApp: // See GoogleCodeTest.cpp for the implementation of this class // class CGoogleCodeTestApp : public CWinAppEx { public: CGoogleCodeTestApp(); // Overrides public: virtual BOOL InitInstance(); virtual int ExitInstance(); // Implementation UINT m_nAppLook; BOOL m_bHiColorIcons; virtual void PreLoadState(); virtual void LoadCustomState(); virtual void SaveCustomState(); afx_msg void OnAppAbout(); DECLARE_MESSAGE_MAP() }; extern CGoogleCodeTestApp theApp;
zzh-project-test
trunk/GoogleCodeTest/GoogleCodeTest/GoogleCodeTest.h
C++
asf20
769
#! /usr/bin/env python # coding=utf-8 ############################################################################# # # # File: proxy.py # # # # Copyright (C) 2008-2010 Du XiaoGang <dugang.2008@gmail.com> # # # # Home: http://gappproxy.googlecode.com # # # # This file is part of GAppProxy. # # # # GAppProxy is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # GAppProxy is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with GAppProxy. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# import BaseHTTPServer, SocketServer, urllib, urllib2, urlparse, zlib, socket, os, common, sys, errno, base64, re try: import ssl ssl_enabled = True except: ssl_enabled = False # global varibles listen_port = common.DEF_LISTEN_PORT local_proxy = common.DEF_LOCAL_PROXY fetch_server = common.DEF_FETCH_SERVER google_proxy = {} class LocalProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): PostDataLimit = 0x100000 def do_CONNECT(self): if not ssl_enabled: self.send_error(501, "Local proxy error, HTTPS needs Python2.6 or later.") self.connection.close() return # for ssl proxy (https_host, _, https_port) = self.path.partition(":") if https_port != "" and https_port != "443": self.send_error(501, "Local proxy error, Only port 443 is allowed for https.") self.connection.close() return # continue self.wfile.write("HTTP/1.1 200 OK\r\n") self.wfile.write("\r\n") ssl_sock = ssl.SSLSocket(self.connection, server_side=True, certfile=common.DEF_CERT_FILE, keyfile=common.DEF_KEY_FILE) # rewrite request line, url to abs first_line = "" while True: chr = ssl_sock.read(1) # EOF? if chr == "": # bad request ssl_sock.close() self.connection.close() return # newline(\r\n)? if chr == "\r": chr = ssl_sock.read(1) if chr == "\n": # got break else: # bad request ssl_sock.close() self.connection.close() return # newline(\n)? if chr == "\n": # got break first_line += chr # got path, rewrite (method, path, ver) = first_line.split() if path.startswith("/"): path = "https://%s" % https_host + path # connect to local proxy server sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(("127.0.0.1", listen_port)) sock.send("%s %s %s\r\n" % (method, path, ver)) # forward https request ssl_sock.settimeout(1) while True: try: data = ssl_sock.read(8192) except ssl.SSLError, e: if str(e).lower().find("timed out") == -1: # error sock.close() ssl_sock.close() self.connection.close() return # timeout break if data != "": sock.send(data) else: # EOF break ssl_sock.setblocking(True) # simply forward response while True: data = sock.recv(8192) if data != "": ssl_sock.write(data) else: # EOF break # clean sock.close() ssl_sock.shutdown(socket.SHUT_WR) ssl_sock.close() self.connection.close() def do_METHOD(self): # check http method and post data method = self.command if method == "GET" or method == "HEAD": # no post data post_data_len = 0 elif method == "POST": # get length of post data post_data_len = 0 for header in self.headers: if header.lower() == "content-length": post_data_len = int(self.headers[header]) break # exceed limit? if post_data_len > self.PostDataLimit: self.send_error(413, "Local proxy error, Sorry, Google's limit, file size up to 1MB.") self.connection.close() return else: # unsupported method self.send_error(501, "Local proxy error, Method not allowed.") self.connection.close() return # get post data post_data = "" if post_data_len > 0: post_data = self.rfile.read(post_data_len) if len(post_data) != post_data_len: # bad request self.send_error(400, "Local proxy error, Post data length error.") self.connection.close() return # do path check (scm, netloc, path, params, query, _) = urlparse.urlparse(self.path) if (scm.lower() != "http" and scm.lower() != "https") or not netloc: self.send_error(501, "Local proxy error, Unsupported scheme(ftp for example).") self.connection.close() return # create new path path = urlparse.urlunparse((scm, netloc, path, params, query, "")) # remove disallowed header dhs = [] for header in self.headers: hl = header.lower() if hl == "if-range": dhs.append(header) elif hl == "range": dhs.append(header) for dh in dhs: del self.headers[dh] # create request for GAppProxy params = urllib.urlencode({"method": method, "encoded_path": base64.b64encode(path), "headers": base64.b64encode(str(self.headers)), "postdata": base64.b64encode(post_data), "version": common.VERSION}) # accept-encoding: identity, *;q=0 # connection: close request = urllib2.Request(fetch_server) request.add_header("Accept-Encoding", "identity, *;q=0") request.add_header("Connection", "close") # create new opener if local_proxy != "": proxy_handler = urllib2.ProxyHandler({"http": local_proxy}) else: proxy_handler = urllib2.ProxyHandler(google_proxy) opener = urllib2.build_opener(proxy_handler) # set the opener as the default opener urllib2.install_opener(opener) try: resp = urllib2.urlopen(request, params) except urllib2.HTTPError, e: if e.code == 404: self.send_error(404, "Local proxy error, Fetchserver not found at the URL you specified, please check it.") elif e.code == 502: self.send_error(502, "Local proxy error, Transmission error, or the fetchserver is too busy.") else: self.send_error(e.code) self.connection.close() return except urllib2.URLError, e: if local_proxy == "": shallWeNeedGoogleProxy() self.connection.close() return # parse resp # for status line line = resp.readline() words = line.split() status = int(words[1]) reason = " ".join(words[2:]) # for large response if status == 592 and method == "GET": self.processLargeResponse(path) self.connection.close() return # normal response try: self.send_response(status, reason) except socket.error, (err, _): # Connection/Webpage closed before proxy return if err == errno.EPIPE or err == 10053: # *nix, Windows return else: raise # for headers text_content = True while True: line = resp.readline().strip() # end header? if line == "": break # header (name, _, value) = line.partition(":") name = name.strip() value = value.strip() # ignore Accept-Ranges if name.lower() == "accept-ranges": continue self.send_header(name, value) # check Content-Type if name.lower() == "content-type": if value.lower().find("text") == -1: # not text text_content = False self.send_header("Accept-Ranges", "none") self.end_headers() # for page if text_content: data = resp.read() if len(data) > 0: self.wfile.write(zlib.decompress(data)) else: self.wfile.write(resp.read()) self.connection.close() do_GET = do_METHOD do_HEAD = do_METHOD do_POST = do_METHOD def processLargeResponse(self, path): cur_pos = 0 part_length = 0x100000 # 1m initial, at least 64k first_part = True content_length = 0 text_content = True allowed_failed = 10 while allowed_failed > 0: next_pos = 0 self.headers["Range"] = "bytes=%d-%d" % (cur_pos, cur_pos + part_length - 1) # create request for GAppProxy params = urllib.urlencode({"method": "GET", "encoded_path": base64.b64encode(path), "headers": base64.b64encode(str(self.headers)), "postdata": base64.b64encode(""), "version": common.VERSION}) # accept-encoding: identity, *;q=0 # connection: close request = urllib2.Request(fetch_server) request.add_header("Accept-Encoding", "identity, *;q=0") request.add_header("Connection", "close") # create new opener if local_proxy != "": proxy_handler = urllib2.ProxyHandler({"http": local_proxy}) else: proxy_handler = urllib2.ProxyHandler(google_proxy) opener = urllib2.build_opener(proxy_handler) # set the opener as the default opener urllib2.install_opener(opener) resp = urllib2.urlopen(request, params) # parse resp # for status line line = resp.readline() words = line.split() status = int(words[1]) # not range response? if status != 206: # reduce part_length and try again if part_length > 65536: part_length /= 2 allowed_failed -= 1 continue # for headers if first_part: self.send_response(200, "OK") while True: line = resp.readline().strip() # end header? if line == "": break # header (name, _, value) = line.partition(":") name = name.strip() value = value.strip() # get total length from Content-Range nl = name.lower() if nl == "content-range": m = re.match(r"bytes[ \t]+([0-9]+)-([0-9]+)/([0-9]+)", value) if not m or int(m.group(1)) != cur_pos: # Content-Range error, fatal error return next_pos = int(m.group(2)) + 1 content_length = int(m.group(3)) continue # ignore Content-Length elif nl == "content-length": continue # ignore Accept-Ranges elif nl == "accept-ranges": continue self.send_header(name, value) # check Content-Type if nl == "content-type": if value.lower().find("text") == -1: # not text text_content = False if content_length == 0: # no Content-Length, fatal error return self.send_header("Content-Length", content_length) self.send_header("Accept-Ranges", "none") self.end_headers() first_part = False else: while True: line = resp.readline().strip() # end header? if line == "": break # header (name, _, value) = line.partition(":") name = name.strip() value = value.strip() # get total length from Content-Range if name.lower() == "content-range": m = re.match(r"bytes[ \t]+([0-9]+)-([0-9]+)/([0-9]+)", value) if not m or int(m.group(1)) != cur_pos: # Content-Range error, fatal error return next_pos = int(m.group(2)) + 1 continue # for body if text_content: data = resp.read() if len(data) > 0: self.wfile.write(zlib.decompress(data)) else: self.wfile.write(resp.read()) # next part? if next_pos == content_length: return cur_pos = next_pos class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass def shallWeNeedGoogleProxy(): global google_proxy # send http request directly #request = urllib2.Request(common.LOAD_BALANCE) #try: # avoid wait too long at startup, timeout argument need py2.6 or later. # if sys.hexversion >= 0x20600f0: # resp = urllib2.urlopen(request, timeout=3) # else: # resp = urllib2.urlopen(request) # resp.read() #except: #google_proxy = {"http": common.GOOGLE_PROXY} def getAvailableFetchServer(): request = urllib2.Request(common.LOAD_BALANCE) if local_proxy != "": proxy_handler = urllib2.ProxyHandler({"http": local_proxy}) else: proxy_handler = urllib2.ProxyHandler(google_proxy) opener = urllib2.build_opener(proxy_handler) urllib2.install_opener(opener) try: resp = urllib2.urlopen(request) return resp.read().strip() except: return "" def parseConf(confFile): global listen_port, local_proxy, fetch_server # read config file try: fp = open(confFile, "r") except IOError: # use default parameters return # parse user defined parameters while True: line = fp.readline() if line == "": # end break # parse line line = line.strip() if line == "": # empty line continue if line.startswith("#"): # comments continue (name, sep, value) = line.partition("=") if sep == "=": name = name.strip().lower() value = value.strip() if name == "listen_port": listen_port = int(value) elif name == "local_proxy": local_proxy = value elif name == "fetch_server": fetch_server = value fp.close() if __name__ == "__main__": # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) parseConf(common.DEF_CONF_FILE) socket.setdefaulttimeout(10) if local_proxy == "": shallWeNeedGoogleProxy() #if fetch_server == "": # fetch_server = getAvailableFetchServer() if fetch_server == "": raise common.GAppProxyError("Invalid response from load balance server.") pid = str(os.getpid()) f = open('/data/data/org.gaeproxy/python.pid','a') f.write(" ") f.write(pid) f.close() print "--------------------------------------------" print "HTTPS Enabled: %s" % (ssl_enabled and "YES" or "NO") print "Direct Fetch : %s" % (google_proxy and "NO" or "YES") print "Listen Addr : 127.0.0.1:%d" % listen_port print "Local Proxy : %s" % local_proxy print "Fetch Server : %s" % fetch_server print "PID : %s" % pid print "--------------------------------------------" httpd = ThreadingHTTPServer(("127.0.0.1", listen_port), LocalProxyHandler) httpd.serve_forever()
zyh3290-proxy
assets/gappproxy.py
Python
gpl3
19,172
#!/usr/bin/env python # coding:utf-8 # Based on GAppProxy 2.0.0 by Du XiaoGang <dugang@188.com> # Based on WallProxy 0.4.0 by hexieshe <www.ehust@gmail.com> from __future__ import with_statement __version__ = '1.8.11' __author__ = "{phus.lu,hewigovens}@gmail.com (Phus Lu and Hewig Xu)" __config__ = 'proxy.ini' try: import gevent, gevent.monkey gevent.monkey.patch_all(dns=gevent.version_info[0]>=1) except: pass import sys import os import re import time import errno import binascii import itertools import zlib import struct import random import hashlib import fnmatch import base64 import urlparse import thread import threading import socket import ssl import select import httplib import urllib2 import BaseHTTPServer import SocketServer import ConfigParser import traceback try: import logging except ImportError: logging = None try: import ctypes except ImportError: ctypes = None try: import OpenSSL except ImportError: OpenSSL = None try: import sqlite3 except ImportError: sqlite3 = None class Common(object): """global config object""" def __init__(self): """load config from proxy.ini""" ConfigParser.RawConfigParser.OPTCRE = re.compile(r'(?P<option>[^=\s][^=]*)\s*(?P<vi>[=])\s*(?P<value>.*)$') self.CONFIG = ConfigParser.ConfigParser() # GAEProxy Patch self.CONFIG.read('/data/data/org.gaeproxy/proxy.ini') self.LISTEN_IP = self.CONFIG.get('listen', 'ip') self.LISTEN_PORT = self.CONFIG.getint('listen', 'port') self.LISTEN_VISIBLE = self.CONFIG.getint('listen', 'visible') self.GAE_ENABLE = self.CONFIG.getint('gae', 'enable') self.GAE_APPIDS = self.CONFIG.get('gae', 'appid').replace('.appspot.com', '').split('|') self.GAE_PASSWORD = self.CONFIG.get('gae', 'password').strip() self.GAE_PATH = self.CONFIG.get('gae', 'path') self.GAE_PROFILE = self.CONFIG.get('gae', 'profile') self.GAE_MULCONN = self.CONFIG.getint('gae', 'mulconn') self.GAE_DEBUGLEVEL = self.CONFIG.getint('gae', 'debuglevel') if self.CONFIG.has_option('gae', 'debuglevel') else 0 paas_section = 'paas' if self.CONFIG.has_section('paas') else 'php' self.PAAS_ENABLE = self.CONFIG.getint(paas_section, 'enable') self.PAAS_LISTEN = self.CONFIG.get(paas_section, 'listen') self.PAAS_PASSWORD = self.CONFIG.get(paas_section, 'password') if self.CONFIG.has_option(paas_section, 'password') else '' self.PAAS_FETCHSERVER = self.CONFIG.get(paas_section, 'fetchserver') if self.CONFIG.has_section('pac'): # XXX, cowork with GoAgentX self.PAC_ENABLE = self.CONFIG.getint('pac','enable') self.PAC_IP = self.CONFIG.get('pac','ip') self.PAC_PORT = self.CONFIG.getint('pac','port') self.PAC_FILE = self.CONFIG.get('pac','file').lstrip('/') self.PAC_UPDATE = self.CONFIG.getint('pac', 'update') self.PAC_REMOTE = self.CONFIG.get('pac', 'remote') self.PAC_TIMEOUT = self.CONFIG.getint('pac', 'timeout') self.PAC_DIRECTS = self.CONFIG.get('pac', 'direct').split('|') if self.CONFIG.get('pac', 'direct') else [] else: self.PAC_ENABLE = 0 self.PROXY_ENABLE = self.CONFIG.getint('proxy', 'enable') self.PROXY_HOST = self.CONFIG.get('proxy', 'host') self.PROXY_PORT = self.CONFIG.getint('proxy', 'port') self.PROXY_USERNAME = self.CONFIG.get('proxy', 'username') self.PROXY_PASSWROD = self.CONFIG.get('proxy', 'password') self.GOOGLE_MODE = self.CONFIG.get(self.GAE_PROFILE, 'mode') self.GOOGLE_HOSTS = tuple(self.CONFIG.get(self.GAE_PROFILE, 'hosts').split('|')) self.GOOGLE_SITES = tuple(self.CONFIG.get(self.GAE_PROFILE, 'sites').split('|')) self.GOOGLE_FORCEHTTPS = frozenset(self.CONFIG.get(self.GAE_PROFILE, 'forcehttps').split('|')) self.GOOGLE_WITHGAE = frozenset(self.CONFIG.get(self.GAE_PROFILE, 'withgae').split('|')) self.FETCHMAX_LOCAL = self.CONFIG.getint('fetchmax', 'local') if self.CONFIG.get('fetchmax', 'local') else 3 self.FETCHMAX_SERVER = self.CONFIG.get('fetchmax', 'server') self.AUTORANGE_HOSTS = tuple(self.CONFIG.get('autorange', 'hosts').split('|')) self.AUTORANGE_HOSTS_TAIL = tuple(x.rpartition('*')[2] for x in self.AUTORANGE_HOSTS) self.AUTORANGE_MAXSIZE = self.CONFIG.getint('autorange', 'maxsize') self.AUTORANGE_WAITSIZE = self.CONFIG.getint('autorange', 'waitsize') self.AUTORANGE_BUFSIZE = self.CONFIG.getint('autorange', 'bufsize') assert self.AUTORANGE_BUFSIZE <= self.AUTORANGE_WAITSIZE <= self.AUTORANGE_MAXSIZE if self.CONFIG.has_section('crlf'): # XXX, cowork with GoAgentX self.CRLF_ENABLE = self.CONFIG.getint('crlf', 'enable') self.CRLF_DNS = self.CONFIG.get('crlf', 'dns') self.CRLF_SITES = tuple(self.CONFIG.get('crlf', 'sites').split('|')) self.CRLF_CNAME = dict(x.split('=') for x in self.CONFIG.get('crlf', 'cname').split('|')) else: self.CRLF_ENABLE = 0 self.USERAGENT_ENABLE = self.CONFIG.getint('useragent', 'enable') self.USERAGENT_STRING = self.CONFIG.get('useragent', 'string') self.LOVE_ENABLE = self.CONFIG.getint('love','enable') self.LOVE_TIMESTAMP = self.CONFIG.get('love', 'timestamp') self.LOVE_TIP = [re.sub(r'(?i)\\u([0-9a-f]{4})', lambda m:unichr(int(m.group(1),16)), x) for x in self.CONFIG.get('love','tip').split('|')] self.HOSTS = dict((k, tuple(v.split('|')) if v else tuple()) for k, v in self.CONFIG.items('hosts')) self.build_gae_fetchserver() self.PAAS_FETCH_INFO = dict(((listen.rpartition(':')[0], int(listen.rpartition(':')[-1])), (re.sub(r':\d+$', '', urlparse.urlparse(server).netloc), server)) for listen, server in zip(self.PAAS_LISTEN.split('|'), [re.sub(r'/index\.[^/]+$','/',x) for x in self.PAAS_FETCHSERVER.split('|')])) def build_gae_fetchserver(self): """rebuild gae fetch server config""" if self.PROXY_ENABLE: self.GOOGLE_MODE = 'https' self.GAE_FETCHHOST = '%s.appspot.com' % self.GAE_APPIDS[0] if not self.PROXY_ENABLE: # append '?' to url, it can avoid china telicom/unicom AD self.GAE_FETCHSERVER = '%s://%s%s?' % (self.GOOGLE_MODE, self.GAE_FETCHHOST, self.GAE_PATH) else: self.GAE_FETCHSERVER = '%s://%s%s?' % (self.GOOGLE_MODE, random.choice(self.GOOGLE_HOSTS), self.GAE_PATH) def install_opener(self): """install urllib2 opener""" httplib.HTTPMessage = SimpleMessageClass if self.PROXY_ENABLE: proxy = '%s:%s@%s:%d'%(self.PROXY_USERNAME, self.PROXY_PASSWROD, self.PROXY_HOST, self.PROXY_PORT) handlers = [urllib2.ProxyHandler({'http':proxy,'https':proxy})] else: handlers = [urllib2.ProxyHandler({})] opener = urllib2.build_opener(*handlers) opener.addheaders = [] urllib2.install_opener(opener) def info(self): info = '' info += '------------------------------------------------------\n' info += 'GoAgent Version : %s (python/%s pyopenssl/%s)\n' % (__version__, sys.version.partition(' ')[0], (OpenSSL.version.__version__ if OpenSSL else 'Disabled')) info += 'Listen Address : %s:%d\n' % (self.LISTEN_IP,self.LISTEN_PORT) info += 'Local Proxy : %s:%s\n' % (self.PROXY_HOST, self.PROXY_PORT) if self.PROXY_ENABLE else '' info += 'Debug Level : %s\n' % self.GAE_DEBUGLEVEL if self.GAE_DEBUGLEVEL else '' info += 'GAE Mode : %s\n' % self.GOOGLE_MODE if self.GAE_ENABLE else '' info += 'GAE Profile : %s\n' % self.GAE_PROFILE info += 'GAE APPID : %s\n' % '|'.join(self.GAE_APPIDS) if common.PAAS_ENABLE: for (ip, port),(fetchhost, fetchserver) in common.PAAS_FETCH_INFO.iteritems(): info += 'PAAS Listen : %s:%d\n' % (ip, port) info += 'PAAS FetchServer : %s\n' % fetchserver if common.PAC_ENABLE: info += 'Pac Server : http://%s:%d/%s\n' % (self.PAC_IP,self.PAC_PORT,self.PAC_FILE) if common.CRLF_ENABLE: #http://www.acunetix.com/websitesecurity/crlf-injection.htm info += 'CRLF Injection : %s\n' % '|'.join(self.CRLF_SITES) info += '------------------------------------------------------\n' return info common = Common() class MultiplexConnection(object): """multiplex tcp connection class""" retry = 3 timeout = 8 timeout_min = 4 timeout_max = 60 timeout_ack = 0 window = 8 window_min = 4 window_max = 60 window_ack = 0 def __init__(self, hosts, port): self.socket = None self._sockets = set([]) self.connect(hosts, port, MultiplexConnection.timeout, MultiplexConnection.window) def connect(self, hostlist, port, timeout, window): for i in xrange(MultiplexConnection.retry): hosts = random.sample(hostlist, window) if len(hostlist) > window else hostlist logging.debug('MultiplexConnection try connect hosts=%s, port=%d', hosts, port) socks = [] # multiple connect start here for host in hosts: sock = socket.socket(2 if ':' not in host else socket.AF_INET6) sock.setblocking(0) #logging.debug('MultiplexConnection connect_ex (%r, %r)', host, port) err = sock.connect_ex((host, port)) self._sockets.add(sock) socks.append(sock) # something happens :D (_, outs, _) = select.select([], socks, [], timeout) if outs: self.socket = outs[0] self.socket.setblocking(1) self._sockets.remove(self.socket) if window > MultiplexConnection.window_min: MultiplexConnection.window_ack += 1 if MultiplexConnection.window_ack > 10: MultiplexConnection.window = window - 1 MultiplexConnection.window_ack = 0 logging.info('MultiplexConnection CONNECT port=%s OK 10 times, switch new window=%d', port, MultiplexConnection.window) if timeout > MultiplexConnection.timeout_min: MultiplexConnection.timeout_ack += 1 if MultiplexConnection.timeout_ack > 10: MultiplexConnection.timeout = timeout - 1 MultiplexConnection.timeout_ack = 0 logging.info('MultiplexConnection CONNECT port=%s OK 10 times, switch new timeout=%d', port, MultiplexConnection.timeout) break else: logging.debug('MultiplexConnection Cannot hosts %r:%r, window=%d', hosts, port, window) else: # OOOPS, cannot multiple connect MultiplexConnection.window = min(int(round(window*1.5)), self.window_max) MultiplexConnection.window_ack = 0 MultiplexConnection.timeout = min(int(round(timeout*1.5)), self.timeout_max) MultiplexConnection.timeout_ack = 0 logging.warning(r'MultiplexConnection Connect hosts %s:%s fail %d times!', hosts, port, MultiplexConnection.retry) raise socket.error('MultiplexConnection connect hosts=%s failed' % repr(hosts)) def connect_single(self, hostlist, port, timeout, window): for host in hostlist: logging.debug('MultiplexConnection try connect host=%s, port=%d', host, port) sock = None try: sock_family = socket.AF_INET6 if ':' in host else socket.AF_INET sock = socket.socket(sock_family, socket.SOCK_STREAM) sock.settimeout(timeout) sock.connect((host, port)) self.socket = sock except socket.error: if sock is not None: sock.close() raise def close(self): """close all sockets, otherwise CLOSE_WAIT""" for sock in self._sockets: try: sock.close() except: pass del self._sockets def socket_create_connection((host, port), timeout=None, source_address=None): logging.debug('socket_create_connection connect (%r, %r)', host, port) if host == common.GAE_FETCHHOST: msg = 'socket_create_connection returns an empty list' try: conn = MultiplexConnection(common.GOOGLE_HOSTS, port) sock = conn.socket sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) return sock except socket.error: logging.error('socket_create_connection connect fail: (%r, %r)', common.GOOGLE_HOSTS, port) sock = None if not sock: raise socket.error, msg elif host in common.HOSTS: msg = 'socket_create_connection returns an empty list' try: iplist = common.HOSTS[host] if not iplist: iplist = tuple(x[-1][0] for x in socket.getaddrinfo(host, 80)) common.HOSTS[host] = iplist conn = MultiplexConnection(iplist, port) sock = conn.socket sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) return sock except socket.error: logging.error('socket_create_connection connect fail: (%r, %r)', common.HOSTS[host], port) sock = None if not sock: raise socket.error, msg else: msg = 'getaddrinfo returns an empty list' for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM): af, socktype, proto, canonname, sa = res sock = None try: sock = socket.socket(af, socktype, proto) if isinstance(timeout, (int, float)): sock.settimeout(timeout) if source_address is not None: sock.bind(source_address) sock.connect(sa) return sock except socket.error: if sock is not None: sock.close() raise socket.error, msg socket.create_connection = socket_create_connection def socket_forward(local, remote, timeout=60, tick=2, bufsize=8192, maxping=None, maxpong=None, idlecall=None): timecount = timeout try: while 1: timecount -= tick if timecount <= 0: break (ins, _, errors) = select.select([local, remote], [], [local, remote], tick) if errors: break if ins: for sock in ins: data = sock.recv(bufsize) if data: if sock is local: remote.sendall(data) timecount = maxping or timeout else: local.sendall(data) timecount = maxpong or timeout else: return else: if idlecall: try: idlecall() except Exception: logging.exception('socket_forward idlecall fail') finally: idlecall = None except Exception: logging.exception('socket_forward error') raise finally: if idlecall: idlecall() def dns_resolve(host, dnsserver='8.8.8.8', dnscache=common.HOSTS, dnslock=threading.Lock()): index = os.urandom(2) hoststr = ''.join(chr(len(x))+x for x in host.split('.')) data = '%s\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00%s\x00\x00\x01\x00\x01' % (index, hoststr) data = struct.pack('!H', len(data)) + data if host not in dnscache: with dnslock: if host not in dnscache: sock = None try: sock = socket.socket(socket.AF_INET6 if ':' in dnsserver else socket.AF_INET) sock.connect((dnsserver, 53)) sock.sendall(data) rfile = sock.makefile('rb') size = struct.unpack('!H', rfile.read(2))[0] data = rfile.read(size) iplist = re.findall('\xC0.\x00\x01\x00\x01.{6}(.{4})', data) iplist = tuple('.'.join(str(ord(x)) for x in s) for s in iplist) logging.info('dns_resolve(host=%r) return %s', host, iplist) dnscache[host] = iplist except socket.error: logging.exception('dns_resolve(host=%r) fail', host) finally: if sock: sock.close() return dnscache.get(host, tuple()) _httplib_HTTPConnection_putrequest = httplib.HTTPConnection.putrequest def httplib_HTTPConnection_putrequest(self, method, url, skip_host=0, skip_accept_encoding=1): self._output('\r\n\r\n') return _httplib_HTTPConnection_putrequest(self, method, url, skip_host, skip_accept_encoding) httplib.HTTPConnection.putrequest = httplib_HTTPConnection_putrequest class DNSCacheUtil(object): '''DNSCache module, integrated with GAEProxy''' cache = {"127.0.0.1": 'localhost'} @staticmethod def getHost(address): if DNSCacheUtil.cache.has_key(address): return DNSCacheUtil.cache[address] host = "www.google.com" if sqlite3 is not None: try: conn = sqlite3.connect('/data/data/org.gaeproxy/databases/dnscache.db') except Exception: logging.exception('DNSCacheUtil.initConn failed') conn = None if conn is not None: try: c = conn.cursor() c.execute("select request from dnsresponse where address = '%s'" % address) row = c.fetchone() if row is not None: host = row[0] DNSCacheUtil.cache[address] = host c.close() conn.close() except Exception: logging.exception('DNSCacheUtil.getHost failed: %s', address) return host class CertUtil(object): '''CertUtil module, based on WallProxy 0.4.0''' CA = None CALock = threading.Lock() subj_alts = \ 'DNS: twitter.com, DNS: facebook.com, \ DNS: *.twitter.com, DNS: *.twimg.com, \ DNS: *.akamaihd.net, DNS: *.google.com, \ DNS: *.facebook.com, DNS: *.ytimg.com, \ DNS: *.appspot.com, DNS: *.google.com, \ DNS: *.youtube.com, DNS: *.googleusercontent.com, \ DNS: *.gstatic.com, DNS: *.live.com, \ DNS: *.ak.fbcdn.net, DNS: *.ak.facebook.com, \ DNS: *.android.com, DNS: *.fbcdn.net' @staticmethod def readFile(filename): content = None with open(filename, 'rb') as fp: content = fp.read() return content @staticmethod def writeFile(filename, content): with open(filename, 'wb') as fp: fp.write(str(content)) @staticmethod def createKeyPair(type=None, bits=1024): if type is None: type = OpenSSL.crypto.TYPE_RSA pkey = OpenSSL.crypto.PKey() pkey.generate_key(type, bits) return pkey @staticmethod def createCertRequest(pkey, digest='sha1', **subj): req = OpenSSL.crypto.X509Req() subject = req.get_subject() for k,v in subj.iteritems(): setattr(subject, k, v) req.set_pubkey(pkey) req.sign(pkey, digest) return req @staticmethod def createCertificate(req, (issuerKey, issuerCert), serial, (notBefore, notAfter), digest='sha1', host=None): cert = OpenSSL.crypto.X509() cert.set_version(3) cert.set_serial_number(serial) cert.gmtime_adj_notBefore(notBefore) cert.gmtime_adj_notAfter(notAfter) cert.set_issuer(issuerCert.get_subject()) cert.set_subject(req.get_subject()) cert.set_pubkey(req.get_pubkey()) alts = CertUtil.subj_alts if host is not None: alts += ", DNS: %s" % host cert.add_extensions([OpenSSL.crypto.X509Extension("subjectAltName", True, alts)]) cert.sign(issuerKey, digest) return cert @staticmethod def loadPEM(pem, type): handlers = ('load_privatekey', 'load_certificate_request', 'load_certificate') return getattr(OpenSSL.crypto, handlers[type])(OpenSSL.crypto.FILETYPE_PEM, pem) @staticmethod def dumpPEM(obj, type): handlers = ('dump_privatekey', 'dump_certificate_request', 'dump_certificate') return getattr(OpenSSL.crypto, handlers[type])(OpenSSL.crypto.FILETYPE_PEM, obj) @staticmethod def makeCA(): pkey = CertUtil.createKeyPair(bits=2048) subj = {'countryName': 'CN', 'stateOrProvinceName': 'Internet', 'localityName': 'Cernet', 'organizationName': 'GoAgent', 'organizationalUnitName': 'GoAgent Root', 'commonName': 'GoAgent CA'} req = CertUtil.createCertRequest(pkey, **subj) cert = CertUtil.createCertificate(req, (pkey, req), 0, (0, 60*60*24*7305)) #20 years return (CertUtil.dumpPEM(pkey, 0), CertUtil.dumpPEM(cert, 2)) @staticmethod def makeCert(host, (cakey, cacrt), serial): pkey = CertUtil.createKeyPair() subj = {'countryName': 'CN', 'stateOrProvinceName': 'Internet', 'localityName': 'Cernet', 'organizationName': host, 'organizationalUnitName': 'GoAgent Branch', 'commonName': host} req = CertUtil.createCertRequest(pkey, **subj) cert = CertUtil.createCertificate(req, (cakey, cacrt), serial, (0, 60*60*24*7305), host=host) return (CertUtil.dumpPEM(pkey, 0), CertUtil.dumpPEM(cert, 2)) # GAEProxy Patch @staticmethod def getCertificate(host): basedir = '/data/data/org.gaeproxy' keyFile = os.path.join(basedir, 'certs/%s.key' % host) crtFile = os.path.join(basedir, 'certs/%s.crt' % host) if os.path.exists(keyFile): return (keyFile, crtFile) if OpenSSL is None: keyFile = os.path.join(basedir, 'CA.key') crtFile = os.path.join(basedir, 'CA.crt') return (keyFile, crtFile) if not os.path.isfile(keyFile): with CertUtil.CALock: if not os.path.isfile(keyFile): logging.info('CertUtil getCertificate for %r', host) # FIXME: howto generate a suitable serial number? for serial in (int(hashlib.md5(host).hexdigest(), 16), int(time.time()*100)): try: key, crt = CertUtil.makeCert(host, CertUtil.CA, serial) CertUtil.writeFile(crtFile, crt) CertUtil.writeFile(keyFile, key) break except Exception: logging.exception('CertUtil.makeCert failed: host=%r, serial=%r', host, serial) else: keyFile = os.path.join(basedir, 'CA.key') crtFile = os.path.join(basedir, 'CA.crt') return (keyFile, crtFile) @staticmethod def checkCA(): #Check CA exists basedir = '/data/data/org.gaeproxy' keyFile = os.path.join(basedir, 'CA.key') crtFile = os.path.join(basedir, 'CA.crt') if not os.path.exists(keyFile): if not OpenSSL: logging.critical('CA.crt is not exist and OpenSSL is disabled, ABORT!') sys.exit(-1) key, crt = CertUtil.makeCA() CertUtil.writeFile(keyFile, key) CertUtil.writeFile(crtFile, crt) [os.remove(os.path.join('certs', x)) for x in os.listdir('certs')] if OpenSSL: keyFile = os.path.join(basedir, 'CA.key') crtFile = os.path.join(basedir, 'CA.crt') cakey = CertUtil.readFile(keyFile) cacrt = CertUtil.readFile(crtFile) CertUtil.CA = (CertUtil.loadPEM(cakey, 0), CertUtil.loadPEM(cacrt, 2)) class SimpleLogging(object): CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0 def __init__(self, *args, **kwargs): self.level = SimpleLogging.INFO if self.level > SimpleLogging.DEBUG: self.debug = self.dummy self.__write = sys.stdout.write @classmethod def getLogger(cls, *args, **kwargs): return cls(*args, **kwargs) def basicConfig(self, *args, **kwargs): self.level = kwargs.get('level', SimpleLogging.INFO) if self.level > SimpleLogging.DEBUG: self.debug = self.dummy def log(self, level, fmt, *args, **kwargs): self.__write('%s - - [%s] %s\n' % (level, time.ctime()[4:-5], fmt%args)) def dummy(self, *args, **kwargs): pass def debug(self, fmt, *args, **kwargs): self.log('DEBUG', fmt, *args, **kwargs) def info(self, fmt, *args, **kwargs): self.log('INFO', fmt, *args) def warning(self, fmt, *args, **kwargs): self.log('WARNING', fmt, *args, **kwargs) def warn(self, fmt, *args, **kwargs): self.log('WARNING', fmt, *args, **kwargs) def error(self, fmt, *args, **kwargs): self.log('ERROR', fmt, *args, **kwargs) def exception(self, fmt, *args, **kwargs): self.log('ERROR', fmt, *args, **kwargs) traceback.print_exc(file=sys.stderr) def critical(self, fmt, *args, **kwargs): self.log('CRITICAL', fmt, *args, **kwargs) class SimpleMessageClass(object): def __init__(self, fp, seekable = 0): self.dict = dict = {} self.headers = headers = [] readline = getattr(fp, 'readline', None) headers_append = headers.append if readline: while 1: line = readline(8192) if not line or line == '\r\n': break key, _, value = line.partition(':') if value: headers_append(line) dict[key.title()] = value.strip() else: for key, value in fp: key = key.title() dict[key] = value headers_append('%s: %s\r\n' % (key, value)) def getheader(self, name, default=None): return self.dict.get(name.title(), default) def getheaders(self, name, default=None): return [self.getheader(name, default)] def addheader(self, key, value): self[key] = value def get(self, name, default=None): return self.dict.get(name.title(), default) def iteritems(self): return self.dict.iteritems() def iterkeys(self): return self.dict.iterkeys() def itervalues(self): return self.dict.itervalues() def keys(self): return self.dict.keys() def values(self): return self.dict.values() def items(self): return self.dict.items() def __getitem__(self, name): return self.dict[name.title()] def __setitem__(self, name, value): name = name.title() self.dict[name] = value headers = self.headers try: i = (i for i, line in enumerate(headers) if line.partition(':')[0].title() == name).next() headers[i] = '%s: %s\r\n' % (name, value) except StopIteration: headers.append('%s: %s\r\n' % (name, value)) def __delitem__(self, name): name = name.title() del self.dict[name] headers = self.headers for i in reversed([i for i, line in enumerate(headers) if line.partition(':')[0].title() == name]): del headers[i] def __contains__(self, name): return name.title() in self.dict def __len__(self): return len(self.dict) def __iter__(self): return iter(self.dict) def __str__(self): return ''.join(self.headers) def urlfetch(url, payload, method, headers, fetchhost, fetchserver, password=None, dns=None, on_error=None): errors = [] params = {'url':url, 'method':method, 'headers':headers, 'payload':payload} logging.debug('urlfetch params %s', params) if password: params['password'] = password if common.FETCHMAX_SERVER: params['fetchmax'] = common.FETCHMAX_SERVER if dns: params['dns'] = dns params = '&'.join('%s=%s' % (k, binascii.b2a_hex(v)) for k, v in params.iteritems()) for i in xrange(common.FETCHMAX_LOCAL): try: logging.debug('urlfetch %r by %r', url, fetchserver) request = urllib2.Request(fetchserver, zlib.compress(params, 9)) request.add_header('Content-Type', '') if common.PROXY_ENABLE: request.add_header('Host', fetchhost) response = urllib2.urlopen(request) compressed = response.read(1) data = {} if compressed == '0': data['code'], hlen, clen = struct.unpack('>3I', response.read(12)) data['headers'] = SimpleMessageClass((k, binascii.a2b_hex(v)) for k, _, v in (x.partition('=') for x in response.read(hlen).split('&'))) data['response'] = response elif compressed == '1': rawdata = zlib.decompress(response.read()) data['code'], hlen, clen = struct.unpack('>3I', rawdata[:12]) data['headers'] = SimpleMessageClass((k, binascii.a2b_hex(v)) for k, _, v in (x.partition('=') for x in rawdata[12:12+hlen].split('&'))) data['content'] = rawdata[12+hlen:12+hlen+clen] response.close() else: raise ValueError('Data format not match(%s)' % url) return (0, data) except Exception as e: if on_error: logging.info('urlfetch error=%s on_error=%s', str(e), str(on_error)) data = on_error(e) if data: newfetch = (data.get('fetchhost'), data.get('fetchserver')) if newfetch != (fetchhost, fetchserver): (fetchhost, fetchserver) = newfetch sys.stdout.write(common.info()) errors.append(str(e)) time.sleep(i+1) continue return (-1, errors) class GAEProxyHandler(BaseHTTPServer.BaseHTTPRequestHandler): skip_headers = frozenset(['Host', 'Vary', 'Via', 'X-Forwarded-For', 'Proxy-Authorization', 'Proxy-Connection', 'Upgrade', 'Keep-Alive']) SetupLock = threading.Lock() MessageClass = SimpleMessageClass DefaultHosts = 'eJxdztsNgDAMQ9GNIvIoSXZjeApSqc3nUVT3ZojakFTR47wSNEhB8qXhorXg+kMjckGtQM9efDKf\n91Km4W+N4M1CldNIYMu+qSVoTm7MsG5E4KPd8apInNUUMo4betRQjg==' def handle_fetch_error(self, error): logging.info('handle_fetch_error self.path=%r', self.path) if isinstance(error, urllib2.HTTPError): # http error 400/502/504, swith to https if error.code in (400, 504) or (error.code==502 and common.GAE_PROFILE=='google_cn'): common.GOOGLE_MODE = 'https' logging.error('GAE Error(%s) switch to https', error) # seems that current appid is overqouta, swith to next appid if error.code == 503: common.GAE_APPIDS.append(common.GAE_APPIDS.pop(0)) logging.error('GAE Error(%s) switch to appid(%r)', error, common.GAE_APPIDS[0]) # 405 method not allowed, disable CRLF if error.code == 405: httplib.HTTPConnection.putrequest = _httplib_HTTPConnection_putrequest elif isinstance(error, urllib2.URLError): if error.reason[0] in (11004, 10051, 10060, 'timed out', 10054): # it seems that google.cn is reseted, switch to https common.GOOGLE_MODE = 'https' elif isinstance(error, httplib.HTTPException): common.GOOGLE_MODE = 'https' httplib.HTTPConnection.putrequest = _httplib_HTTPConnection_putrequest else: logging.warning('GAEProxyHandler.handle_fetch_error Exception %s', error) return {} common.build_gae_fetchserver() return {'fetchhost':common.GAE_FETCHHOST, 'fetchserver':common.GAE_FETCHSERVER} def fetch(self, url, payload, method, headers): return urlfetch(url, payload, method, headers, common.GAE_FETCHHOST, common.GAE_FETCHSERVER, password=common.GAE_PASSWORD, on_error=self.handle_fetch_error) def rangefetch(self, m, data): m = map(int, m.groups()) if 'range' in self.headers: content_range = 'bytes %d-%d/%d' % (m[0], m[1], m[2]) req_range = re.search(r'(\d+)?-(\d+)?', self.headers['range']) if req_range: req_range = [u and int(u) for u in req_range.groups()] if req_range[0] is None: if req_range[1] is not None: if not (m[1]-m[0]+1==req_range[1] and m[1]+1==m[2]): return False if m[2] >= req_range[1]: content_range = 'bytes %d-%d/%d' % (req_range[1], m[2]-1, m[2]) else: if req_range[1] is not None: if not (m[0]==req_range[0] and m[1]==req_range[1]): return False if m[2] - 1 > req_range[1]: content_range = 'bytes %d-%d/%d' % (req_range[0], req_range[1], m[2]) data['headers']['Content-Range'] = content_range data['headers']['Content-Length'] = m[2]-m[0] elif m[0] == 0: data['code'] = 200 data['headers']['Content-Length'] = m[2] del data['headers']['Content-Range'] self.wfile.write('%s %d %s\r\n%s\r\n' % (self.protocol_version, data['code'], 'OK', data['headers'])) if 'response' in data: response = data['response'] bufsize = common.AUTORANGE_BUFSIZE if data['headers'].get('Content-Type', '').startswith('video/'): bufsize = common.AUTORANGE_WAITSIZE while 1: content = response.read(bufsize) if not content: response.close() break self.wfile.write(content) bufsize = common.AUTORANGE_BUFSIZE else: self.wfile.write(data['content']) start = m[1] + 1 end = m[2] - 1 failed = 0 logging.info('>>>>>>>>>>>>>>> Range Fetch started(%r)', self.headers.get('Host')) while start < end: if failed > 16: break self.headers['Range'] = 'bytes=%d-%d' % (start, min(start+common.AUTORANGE_MAXSIZE-1, end)) retval, data = self.fetch(self.path, '', self.command, str(self.headers)) if retval != 0 or data['code'] >= 400: failed += 1 seconds = random.randint(2*failed, 2*(failed+1)) logging.error('Range Fetch fail %d times, retry after %d secs!', failed, seconds) time.sleep(seconds) continue if 'Location' in data['headers']: logging.info('Range Fetch got a redirect location:%r', data['headers']['Location']) self.path = data['headers']['Location'] failed += 1 continue m = re.search(r'bytes\s+(\d+)-(\d+)/(\d+)', data['headers'].get('Content-Range','')) if not m: failed += 1 logging.error('Range Fetch fail %d times, data[\'headers\']=%s', failed, data['headers']) continue start = int(m.group(2)) + 1 logging.info('>>>>>>>>>>>>>>> %s %d' % (data['headers']['Content-Range'], end+1)) failed = 0 if 'response' in data: response = data['response'] while 1: content = response.read(common.AUTORANGE_BUFSIZE) if not content: response.close() break self.wfile.write(content) else: self.wfile.write(data['content']) logging.info('>>>>>>>>>>>>>>> Range Fetch ended(%r)', self.headers.get('Host')) return True def log_message(self, fmt, *args): host, port = self.client_address[:2] sys.stdout.write("%s:%d - - [%s] %s\n" % (host, port, time.ctime()[4:-5], fmt%args)) def send_response(self, code, message=None): self.log_request(code) message = message or self.responses.get(code, ('GoAgent Notify',))[0] self.connection.sendall('%s %d %s\r\n' % (self.protocol_version, code, message)) def end_error(self, code, message=None, data=None): if not data: self.send_error(code, message) else: self.send_response(code, message) self.connection.sendall(data) def setup(self): if not common.PROXY_ENABLE and common.GAE_PROFILE != 'google_ipv6': logging.info('resolve common.GOOGLE_HOSTS domian=%r to iplist', common.GOOGLE_HOSTS) if any(not re.match(r'\d+\.\d+\.\d+\.\d+', x) for x in common.GOOGLE_HOSTS): with GAEProxyHandler.SetupLock: if any(not re.match(r'\d+\.\d+\.\d+\.\d+', x) for x in common.GOOGLE_HOSTS): google_iplist = [host for host in common.GOOGLE_HOSTS if re.match(r'\d+\.\d+\.\d+\.\d+', host)] google_hosts = [host for host in common.GOOGLE_HOSTS if not re.match(r'\d+\.\d+\.\d+\.\d+', host)] try: google_hosts_iplist = [[x[-1][0] for x in socket.getaddrinfo(host, 80)] for host in google_hosts] need_remote_dns = google_hosts and any(len(iplist)==1 for iplist in google_hosts_iplist) except socket.gaierror: need_remote_dns = True if need_remote_dns: logging.warning('OOOPS, there are some mistake in socket.getaddrinfo, try remote dns_resolve') google_hosts_iplist = [list(dns_resolve(host)) for host in google_hosts] common.GOOGLE_HOSTS = tuple(set(sum(google_hosts_iplist, google_iplist))) if len(common.GOOGLE_HOSTS) == 0: logging.error('resolve common.GOOGLE_HOSTS domian to iplist return empty! use default iplist') common.GOOGLE_HOSTS = zlib.decompress(base64.b64decode(self.DefaultHosts)).split('|') common.GOOGLE_HOSTS = tuple(x for x in common.GOOGLE_HOSTS if ':' not in x) logging.info('resolve common.GOOGLE_HOSTS domian to iplist=%r', common.GOOGLE_HOSTS) if not common.GAE_MULCONN: MultiplexConnection.connect = MultiplexConnection.connect_single if not common.GAE_ENABLE: GAEProxyHandler.do_CONNECT = GAEProxyHandler.do_CONNECT_Direct GAEProxyHandler.do_METHOD = GAEProxyHandler.do_METHOD_Direct GAEProxyHandler.do_GET = GAEProxyHandler.do_METHOD GAEProxyHandler.do_POST = GAEProxyHandler.do_METHOD GAEProxyHandler.do_PUT = GAEProxyHandler.do_METHOD GAEProxyHandler.do_DELETE = GAEProxyHandler.do_METHOD GAEProxyHandler.do_OPTIONS = GAEProxyHandler.do_METHOD GAEProxyHandler.do_HEAD = GAEProxyHandler.do_METHOD GAEProxyHandler.setup = BaseHTTPServer.BaseHTTPRequestHandler.setup BaseHTTPServer.BaseHTTPRequestHandler.setup(self) def do_CONNECT(self): host, _, port = self.path.rpartition(':') if host.endswith(common.GOOGLE_SITES) and host not in common.GOOGLE_WITHGAE: common.HOSTS[host] = common.GOOGLE_HOSTS return self.do_CONNECT_Direct() elif host in common.HOSTS: return self.do_CONNECT_Direct() elif common.CRLF_ENABLE and host.endswith(common.CRLF_SITES): if host not in common.HOSTS: try: cname = common.CRLF_CNAME[itertools.ifilter(host.endswith, common.CRLF_CNAME).next()] except StopIteration: cname = host logging.info('crlf dns_resolve(host=%r, cname=%r dnsserver=%r)', host, cname, common.CRLF_DNS) iplist = tuple(set(sum((dns_resolve(x, common.CRLF_DNS) if not re.match(r'\d+\.\d+\.\d+\.\d+', host) else (host,) for x in cname.split(',')), ()))) common.HOSTS[host] = iplist return self.do_CONNECT_Direct() else: return self.do_CONNECT_Tunnel() def do_CONNECT_Direct(self): try: logging.debug('GAEProxyHandler.do_CONNECT_Directt %s' % self.path) host, _, port = self.path.rpartition(':') port = int(port) idlecall = None if not common.PROXY_ENABLE: if host in common.HOSTS: iplist = common.HOSTS[host] if not iplist: common.HOSTS[host] = iplist = tuple(x[-1][0] for x in socket.getaddrinfo(host, 80)) conn = MultiplexConnection(iplist, port) sock = conn.socket idlecall=conn.close else: sock = socket.create_connection((host, port)) self.log_request(200) self.connection.sendall('%s 200 Tunnel established\r\n\r\n' % self.protocol_version) else: sock = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT)) if host in common.HOSTS: iplist = common.HOSTS[host] if not iplist: common.HOSTS[host] = iplist = tuple(x[-1][0] for x in socket.getaddrinfo(host, 80)) conn = MultiplexConnection(iplist, port) else: iplist = (host,) if 'Host' in self.headers: del self.headers['Host'] if common.PROXY_USERNAME and 'Proxy-Authorization' not in self.headers: self.headers['Proxy-Authorization'] = 'Basic %s' + base64.b64encode('%s:%s'%(common.PROXY_USERNAME, common.PROXY_PASSWROD)) data = '\r\n\r\n%s %s:%s %s\r\n%s\r\n' % (self.command, random.choice(iplist), port, self.protocol_version, self.headers) sock.sendall(data) socket_forward(self.connection, sock, idlecall=idlecall) except Exception: logging.exception('GAEProxyHandler.do_CONNECT_Direct Error') finally: try: sock.close() del sock except: pass def do_CONNECT_Tunnel(self): # for ssl proxy host, _, port = self.path.rpartition(':') p = "(?:\d{1,3}\.){3}\d{1,3}" if re.match(p, host) is not None: host = DNSCacheUtil.getHost(host) keyFile, crtFile = CertUtil.getCertificate(host) self.log_request(200) self.connection.sendall('%s 200 OK\r\n\r\n' % self.protocol_version) try: self._realpath = self.path self._realrfile = self.rfile self._realwfile = self.wfile self._realconnection = self.connection self.connection = ssl.wrap_socket(self.connection, keyFile, crtFile, True) self.rfile = self.connection.makefile('rb', self.rbufsize) self.wfile = self.connection.makefile('wb', self.wbufsize) self.raw_requestline = self.rfile.readline(8192) if self.raw_requestline == '': return self.parse_request() if self.path[0] == '/': if 'Host' in self.headers: self.path = 'https://%s:%s%s' % (self.headers['Host'].partition(':')[0], port or 443, self.path) else: self.path = 'https://%s%s' % (self._realpath, self.path) self.requestline = '%s %s %s' % (self.command, self.path, self.protocol_version) self.do_METHOD_Tunnel() except socket.error: logging.exception('do_CONNECT_Tunnel socket.error') finally: try: self.connection.shutdown(socket.SHUT_WR) except socket.error: pass self.rfile = self._realrfile self.wfile = self._realwfile self.connection = self._realconnection def do_METHOD(self): host = self.headers['Host'] if host.endswith(common.GOOGLE_SITES) and host not in common.GOOGLE_WITHGAE: if host in common.GOOGLE_FORCEHTTPS: self.send_response(301) self.send_header('Location', self.path.replace('http://', 'https://')) self.end_headers() return common.HOSTS[host] = common.GOOGLE_HOSTS return self.do_METHOD_Direct() elif host in common.HOSTS: return self.do_METHOD_Direct() elif common.CRLF_ENABLE and host.endswith(common.CRLF_SITES): if host not in common.HOSTS: try: cname = common.CRLF_CNAME[itertools.ifilter(host.endswith, common.CRLF_CNAME).next()] except StopIteration: cname = host logging.info('crlf dns_resolve(host=%r, cname=%r dnsserver=%r)', host, cname, common.CRLF_DNS) iplist = tuple(set(sum((dns_resolve(x, common.CRLF_DNS) if re.match(r'\d+\.\d+\.\d+\.\d+', host) else (host,) for x in cname.split(',')), ()))) common.HOSTS[host] = iplist return self.do_METHOD_Direct() else: return self.do_METHOD_Tunnel() def do_METHOD_Direct(self): scheme, netloc, path, params, query, fragment = urlparse.urlparse(self.path, 'http') try: host, _, port = netloc.rpartition(':') port = int(port) except ValueError: host = netloc port = 80 try: self.log_request() idlecall = None if not common.PROXY_ENABLE: if host in common.HOSTS: iplist = common.HOSTS[host] if not iplist: common.HOSTS[host] = iplist = tuple(x[-1][0] for x in socket.getaddrinfo(host, 80)) conn = MultiplexConnection(iplist, port) sock = conn.socket idlecall = conn.close else: sock = socket.create_connection((host, port)) self.headers['Connection'] = 'close' data = '\r\n\r\n%s %s %s\r\n%s\r\n' % (self.command, urlparse.urlunparse(('', '', path, params, query, '')), self.request_version, ''.join(line for line in self.headers.headers if not line.startswith('Proxy-'))) else: sock = socket.create_connection((common.PROXY_HOST, common.PROXY_PORT)) if host in common.HOSTS: host = random.choice(common.HOSTS[host]) else: host = host url = urlparse.urlunparse((scheme, host + ('' if port == 80 else ':%d' % port), path, params, query, '')) self.headers['Host'] = netloc self.headers['Proxy-Connection'] = 'close' if common.PROXY_USERNAME and 'Proxy-Authorization' not in self.headers: self.headers['Proxy-Authorization'] = 'Basic %s' + base64.b64encode('%s:%s'%(common.PROXY_USERNAME, common.PROXY_PASSWROD)) data ='\r\n\r\n%s %s %s\r\n%s\r\n' % (self.command, url, self.request_version, self.headers) content_length = int(self.headers.get('Content-Length', 0)) if content_length > 0: data += self.rfile.read(content_length) sock.sendall(data) socket_forward(self.connection, sock, idlecall=idlecall) except Exception: logging.exception('GAEProxyHandler.do_GET Error') finally: try: sock.close() del sock except: pass def do_METHOD_Tunnel(self): headers = self.headers host = headers.get('Host') or urlparse.urlparse(self.path).netloc.partition(':')[0] if self.path[0] == '/': self.path = 'http://%s%s' % (host, self.path) payload_len = int(headers.get('Content-Length', 0)) if payload_len: payload = self.rfile.read(payload_len) else: payload = '' if common.USERAGENT_ENABLE: headers['User-Agent'] = common.USERAGENT_STRING if 'Range' in headers.dict: m = re.search('bytes=(\d+)-', headers.dict['Range']) start = int(m.group(1) if m else 0) headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1) logging.info('autorange range=%r match url=%r', headers['Range'], self.path) elif host.endswith(common.AUTORANGE_HOSTS_TAIL): try: pattern = (p for p in common.AUTORANGE_HOSTS if host.endswith(p) or fnmatch.fnmatch(host, p)).next() logging.debug('autorange pattern=%r match url=%r', pattern, self.path) m = re.search('bytes=(\d+)-', headers.get('Range', '')) start = int(m.group(1) if m else 0) headers['Range'] = 'bytes=%d-%d' % (start, start+common.AUTORANGE_MAXSIZE-1) except StopIteration: pass skip_headers = self.skip_headers strheaders = ''.join('%s: %s\r\n' % (k, v) for k, v in headers.iteritems() if k not in skip_headers) retval, data = self.fetch(self.path, payload, self.command, strheaders) try: if retval == -1: return self.end_error(502, str(data)) code = data['code'] headers = data['headers'] self.log_request(code) if code == 206 and self.command=='GET': content_range = headers.get('Content-Range') or headers.get('content-range') or '' m = re.search(r'bytes\s+(\d+)-(\d+)/(\d+)', content_range) if m and self.rangefetch(m, data): return content = '%s %d %s\r\n%s\r\n' % (self.protocol_version, code, self.responses.get(code, ('GoAgent Notify', ''))[0], headers) self.connection.sendall(content) try: self.connection.sendall(data['content']) except KeyError: #logging.info('OOPS, KeyError! Content-Type=%r', headers.get('Content-Type')) response = data['response'] while 1: content = response.read(common.AUTORANGE_BUFSIZE) if not content: response.close() break self.connection.sendall(content) if 'close' == headers.get('Connection',''): self.close_connection = 1 except socket.error as e: # Connection closed before proxy return if e[0] in (10053, errno.EPIPE): return class PAASProxyHandler(GAEProxyHandler): HOSTS = {} def handle_fetch_error(self, error): logging.error('PAASProxyHandler handle_fetch_error %s', error) httplib.HTTPConnection.putrequest = _httplib_HTTPConnection_putrequest def fetch(self, url, payload, method, headers): fetchhost, fetchserver = common.PAAS_FETCH_INFO[self.server.server_address] dns = None host = self.headers.get('Host') if host in PAASProxyHandler.HOSTS: dns = random.choice(tuple(x[-1][0] for x in socket.getaddrinfo(host, 80))) return urlfetch(url, payload, method, headers, fetchhost, fetchserver, password=common.PAAS_PASSWORD, dns=dns, on_error=self.handle_fetch_error) def setup(self): PAASProxyHandler.HOSTS = dict((k, tuple(v.split('|')) if v else None) for k, v in common.CONFIG.items('hosts')) if common.PROXY_ENABLE: logging.info('Local Proxy is enable, PAASProxyHandler dont resole DNS') else: for fetchhost, _ in common.PAAS_FETCH_INFO.itervalues(): logging.info('PAASProxyHandler.setup check %s is in common.HOSTS', fetchhost) if fetchhost not in common.HOSTS: with GAEProxyHandler.SetupLock: if fetchhost not in common.HOSTS: try: logging.info('Resole PAAS fetchserver address.') common.HOSTS[fetchhost] = tuple(x[-1][0] for x in socket.getaddrinfo(fetchhost, 80)) logging.info('Resole PAAS fetchserver address OK. %s', common.HOSTS[fetchhost]) except Exception: logging.exception('PAASProxyHandler.setup resolve fail') PAASProxyHandler.do_CONNECT = GAEProxyHandler.do_CONNECT_Tunnel PAASProxyHandler.do_GET = GAEProxyHandler.do_METHOD_Tunnel PAASProxyHandler.do_POST = GAEProxyHandler.do_METHOD_Tunnel PAASProxyHandler.do_PUT = GAEProxyHandler.do_METHOD_Tunnel PAASProxyHandler.do_DELETE = GAEProxyHandler.do_METHOD_Tunnel PAASProxyHandler.do_HEAD = PAASProxyHandler.do_METHOD PAASProxyHandler.setup = BaseHTTPServer.BaseHTTPRequestHandler.setup BaseHTTPServer.BaseHTTPRequestHandler.setup(self) class PacServerHandler(BaseHTTPServer.BaseHTTPRequestHandler): def _generate_pac(self): url = common.PAC_REMOTE logging.info('PacServerHandler._generate_pac url=%r, timeout=%r', url, common.PAC_TIMEOUT) content = urllib2.urlopen(url, timeout=common.PAC_TIMEOUT).read() cndatas = re.findall(r'(?i)apnic\|cn\|ipv4\|([0-9\.]+)\|([0-9]+)\|[0-9]+\|a.*', content) logging.info('PacServerHandler._generate_pac download %s bytes %s items', len(content), len(cndatas)) assert len(cndatas) > 0 cndatas = [(ip, socket.inet_ntoa(struct.pack('!I', (int(n)-1)^0xffffffff))) for ip, n in cndatas] cndataslist = [[] for i in xrange(256)] for ip, mask in cndatas: i = int(ip.partition('.')[0]) cndataslist[i].append([ip, mask]) if common.LISTEN_IP in ('', '0.0.0.0', '::'): proxy = 'PROXY %s:%d' % (socket.gethostbyname(socket.gethostname()), common.LISTEN_PORT) else: proxy = 'PROXY %s:%d' % (common.LISTEN_IP, common.LISTEN_PORT) PAC_TEMPLATE = '''\ //inspired from https://github.com/Leask/Flora_Pac function FindProxyForURL(url, host) { if (false %s) { return 'DIRECT'; } var ip = dnsResolve(host); if (ip == null) { return '%s'; } var lists = %s; var index = parseInt(ip.split('.', 1)[0], 10); var list = lists[index]; for (var i in list) { if (isInNet(ip, list[i][0], list[i][1])) { return 'DIRECT'; } } return '%s'; }''' directs = '||'.join(['dnsDomainIs(host, "%s")' % x for x in common.PAC_DIRECTS]) if common.PAC_DIRECTS else '' return PAC_TEMPLATE % (directs, proxy, repr(cndataslist), proxy) def do_GET(self): filename = os.path.join(os.path.dirname(__file__), common.PAC_FILE) if self.path != '/'+common.PAC_FILE or not os.path.isfile(filename): return self.send_error(404, 'Not Found') if common.PAC_UPDATE and time.time() - os.path.getmtime(common.PAC_FILE) > 86400: try: logging.info('PacServerHandler begin sync remote pac') content = self._generate_pac() with open(filename, 'wb') as fp: fp.write(content) logging.info('PacServerHandler end sync remote pac') except Exception: logging.exception('PacServerHandler sync remote pac failed') with open(filename, 'rb') as fp: data = fp.read() self.send_response(200) self.send_header('Content-Type', 'application/x-ns-proxy-autoconfig') self.end_headers() self.wfile.write(data) self.wfile.close() class ProxyAndPacHandler(GAEProxyHandler, PacServerHandler): def do_GET(self): if self.path == '/'+common.PAC_FILE: PacServerHandler.do_GET(self) else: GAEProxyHandler.do_METHOD(self) class LocalProxyServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): daemon_threads = True allow_reuse_address = True def try_show_love(): '''If you hate this funtion, please go back to gappproxy/wallproxy''' if ctypes and os.name == 'nt' and common.LOVE_ENABLE: SetConsoleTitleW = ctypes.windll.kernel32.SetConsoleTitleW GetConsoleTitleW = ctypes.windll.kernel32.GetConsoleTitleW if common.LOVE_TIMESTAMP.strip(): common.LOVE_TIMESTAMP = int(common.LOVE_TIMESTAMP) else: common.LOVE_TIMESTAMP = int(time.time()) with open(__config__, 'w') as fp: common.CONFIG.set('love', 'timestamp', int(time.time())) common.CONFIG.write(fp) if time.time() - common.LOVE_TIMESTAMP > 86400 and random.randint(1,10) > 5: title = ctypes.create_unicode_buffer(1024) GetConsoleTitleW(ctypes.byref(title), len(title)-1) SetConsoleTitleW(u'%s %s' % (title.value, random.choice(common.LOVE_TIP))) with open(__config__, 'w') as fp: common.CONFIG.set('love', 'timestamp', int(time.time())) common.CONFIG.write(fp) def main(): # GAEProxy Patch # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) global logging if logging is None: sys.modules['logging'] = logging = SimpleLogging() logging.basicConfig(level=logging.DEBUG if common.GAE_DEBUGLEVEL else logging.INFO, format='%(levelname)s - - %(asctime)s %(message)s', datefmt='[%b %d %H:%M:%S]') if ctypes and os.name == 'nt': ctypes.windll.kernel32.SetConsoleTitleW(u'GoAgent v%s' % __version__) if not common.LOVE_TIMESTAMP.strip(): sys.stdout.write('Double click addto-startup.vbs could add goagent to autorun programs. :)\n') try_show_love() if not common.LISTEN_VISIBLE: ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0) if common.GAE_APPIDS[0] == 'goagent' and not common.CRLF_ENABLE: logging.critical('please edit %s to add your appid to [gae] !', __config__) sys.exit(-1) CertUtil.checkCA() common.install_opener() sys.stdout.write(common.info()) LocalProxyServer.address_family = (socket.AF_INET, socket.AF_INET6)[':' in common.LISTEN_IP] # GAEProxy Patch pid = str(os.getpid()) f = open('/data/data/org.gaeproxy/python.pid','a') f.write(" ") f.write(pid) f.close() if common.PAAS_ENABLE: for address in common.PAAS_FETCH_INFO: httpd = LocalProxyServer(address, PAASProxyHandler) thread.start_new_thread(httpd.serve_forever, ()) if common.PAC_ENABLE and common.PAC_PORT != common.LISTEN_PORT: httpd = LocalProxyServer((common.PAC_IP,common.PAC_PORT),PacServerHandler) thread.start_new_thread(httpd.serve_forever,()) if common.PAC_ENABLE and common.PAC_PORT == common.LISTEN_PORT: httpd = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), ProxyAndPacHandler) else: httpd = LocalProxyServer((common.LISTEN_IP, common.LISTEN_PORT), GAEProxyHandler) httpd.serve_forever() if __name__ == '__main__': try: main() except KeyboardInterrupt: pass
zyh3290-proxy
assets/goagent.py
Python
gpl3
62,180
#!/system/bin/sh DIR=/data/data/org.gaeproxy PYTHONPATH=${1}/python-extras PYTHONPATH=${PYTHONPATH}:${DIR}/python/lib/python2.6/lib-dynload export PYTHONPATH export TEMP=${1}/python-extras export PYTHONHOME=${DIR}/python export LD_LIBRARY_PATH=${DIR}/python/lib case $2 in goagent) echo " [listen] ip = 127.0.0.1 port = $4 visible = 1 [gae] enable = 1 appid = $3 password = $7 path = /$6 profile = google_hk mulconn = 1 [paas] enable = 0 password = 123456 listen = 127.0.0.1:8088 fetchserver = http://demophus.app.com/ [proxy] enable = 0 host = 10.64.1.63 port = 8080 username = username password = 123456 [google_cn] mode = http hosts = 203.208.46.1|203.208.46.2|203.208.46.3|203.208.46.4|203.208.46.5|203.208.46.6|203.208.46.7|203.208.46.8 sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.appspot.com|.android.com|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = plus.google.com|plusone.google.com|reader.googleusercontent.com|music.google.com|apis.google.com [google_hk] mode = http hosts = $5 sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = www.google.com.hk [google_ipv6] mode = http hosts = 2404:6800:8005::2f|2a00:1450:8006::30|2404:6800:8005::84 sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = [fetchmax] local = server = [autorange] hosts = .youtube.com|.atm.youku.com|.googlevideo.com|av.vimeo.com|smile-*.nicovideo.jp|video.*.fbcdn.net|s*.last.fm|x*.last.fm maxsize = 1048576 waitsize = 524288 bufsize = 8192 [pac] enable = 0 ip = 127.0.0.1 port = 8089 file = goagent.pac update = 0 remote = http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest timeout = 16 direct = .253874.com|.cnn.com [useragent] enable = 0 string = Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 [love] enable = 1 timestamp = 1339122685 tip = \u8bf7\u5173\u6ce8\u5317\u4eac\u5931\u5b66\u513f\u7ae5~~ [hosts] www.253874.com = "> /data/data/org.gaeproxy/proxy.ini $DIR/python-cl $DIR/goagent.py ;; gappproxy) $DIR/python-cl $DIR/gappproxy.py ;; wallproxy) echo " server['listen'] = ('127.0.0.1', $4) server['log_file'] = None hosts = ''' $5 .appspot.com $5 www.youtube.com ''' plugins['plugins.hosts'] = 'hosts' gaeproxy = [{ 'url': '$3', 'key': '$6', 'crypto':'XOR--0', 'max_threads':5 }] plugins['plugins.gaeproxy'] = 'gaeproxy' def find_http_handler(method, url, headers): if method not in ('GET', 'HEAD', 'PUT', 'POST', 'DELETE'): return rawproxy[0] if 80<=url.port<=90 or 440<=url.port<=450 or url.port>=1024: return gaeproxy return None fakehttps = None plugins['plugins.fakehttps'] = 'fakehttps' def find_sock_handler(reqtype, ip, port, cmd): if reqtype == 'https': return fakehttps return None def check_client(ip, reqtype, args): return True " > /data/data/org.gaeproxy/proxy.conf $DIR/python-cl $DIR/wallproxy.py ;; esac
zyh3290-proxy
assets/localproxy_en.sh
Shell
gpl3
3,504
#!/system/bin/sh DIR=/data/data/org.gaeproxy PATH=$DIR:$PATH case $1 in start) echo " base { log_debug = off; log_info = off; log = stderr; daemon = on; redirector = iptables; } redsocks { local_ip = 127.0.0.1; local_port = 8123; ip = 127.0.0.1; port = $2; type = http-relay; } redsocks { local_ip = 127.0.0.1; local_port = 8124; ip = $3; port = $4; type = http-connect; login = "gaeproxy"; password = "gaeproxy"; } " > $DIR/redsocks.conf $DIR/redsocks -p $DIR/redsocks.pid -c $DIR/redsocks.conf ;; stop) kill -9 `cat $DIR/redsocks.pid` kill -9 `cat $DIR/python.pid` rm -f $DIR/redsocks.conf rm -f $DIR/redsocks.pid rm -f $DIR/python.pid killall -9 python-cl killall -9 redsocks ;; esac
zyh3290-proxy
assets/proxy.sh
Shell
gpl3
742
#!/usr/bin/env python import sys, os # do the UNIX double-fork magic, see Stevens' "Advanced # Programming in the UNIX Environment" for details (ISBN 0201563177) try: pid = os.fork() if pid > 0: # exit first parent sys.exit(0) except OSError, e: print >>sys.stderr, "fork #1 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() os.umask(0) # do second fork try: pid = os.fork() if pid > 0: sys.exit(0) except OSError, e: print >>sys.stderr, "fork #2 failed: %d (%s)" % (e.errno, e.strerror) sys.exit(1) pid = str(os.getpid()) f = open('/data/data/org.gaeproxy/python.pid','a') f.write(" ") f.write(pid) f.close() dir = os.path.abspath(os.path.dirname(sys.argv[0])) sys.path.append(os.path.join(dir, 'src.zip')) del sys, os, dir import ProxyServer ProxyServer.main()
zyh3290-proxy
assets/wallproxy.py
Python
gpl3
940
#!/system/bin/sh DIR=/data/data/org.gaeproxy PYTHONPATH=${1}/python-extras PYTHONPATH=${PYTHONPATH}:${DIR}/python/lib/python2.6/lib-dynload export PYTHONPATH export TEMP=${1}/python-extras export PYTHONHOME=${DIR}/python export LD_LIBRARY_PATH=${DIR}/python/lib case $2 in goagent) echo " [listen] ip = 127.0.0.1 port = $4 visible = 1 [gae] enable = 1 appid = $3 password = $7 path = /$6 profile = google_cn mulconn = 1 [paas] enable = 0 password = 123456 listen = 127.0.0.1:8088 fetchserver = http://demophus.app.com/ [proxy] enable = 0 host = 10.64.1.63 port = 8080 username = username password = 123456 [google_cn] mode = http hosts = $5|203.208.46.1|203.208.46.2|203.208.46.3|203.208.46.4|203.208.46.5|203.208.46.6|203.208.46.7|203.208.46.8 sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.appspot.com|.android.com|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = plus.google.com|plusone.google.com|reader.googleusercontent.com|music.google.com|apis.google.com [google_hk] mode = http hosts = www.google.com|mail.google.com|www.google.com.hk|www.google.com.tw sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = www.google.com.hk [google_ipv6] mode = http hosts = 2404:6800:8005::2f|2a00:1450:8006::30|2404:6800:8005::84 sites = .google.com|.googleusercontent.com|.googleapis.com|.google-analytics.com|.googlecode.com|.google.com.hk|.googlegroups.com forcehttps = groups.google.com|code.google.com|mail.google.com|docs.google.com|profiles.google.com|developer.android.com withgae = [fetchmax] local = server = [autorange] hosts = .youtube.com|.atm.youku.com|.googlevideo.com|av.vimeo.com|smile-*.nicovideo.jp|video.*.fbcdn.net|s*.last.fm|x*.last.fm maxsize = 1048576 waitsize = 524288 bufsize = 8192 [pac] enable = 0 ip = 127.0.0.1 port = 8089 file = goagent.pac update = 0 remote = http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest timeout = 16 direct = .253874.com|.cnn.com [useragent] enable = 0 string = Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A543a Safari/419.3 [love] enable = 1 timestamp = 1339122685 tip = \u8bf7\u5173\u6ce8\u5317\u4eac\u5931\u5b66\u513f\u7ae5~~ [hosts] www.253874.com = "> /data/data/org.gaeproxy/proxy.ini $DIR/python-cl $DIR/goagent.py ;; gappproxy) $DIR/python-cl $DIR/gappproxy.py ;; wallproxy) echo " server['listen'] = ('127.0.0.1', $4) server['log_file'] = None hosts = ''' $5 .appspot.com $5 www.youtube.com ''' plugins['plugins.hosts'] = 'hosts' gaeproxy = [{ 'url': '$3', 'key': '$6', 'crypto':'XOR--0', 'max_threads':5 }] plugins['plugins.gaeproxy'] = 'gaeproxy' def find_http_handler(method, url, headers): if method not in ('GET', 'HEAD', 'PUT', 'POST', 'DELETE'): return rawproxy[0] if 80<=url.port<=90 or 440<=url.port<=450 or url.port>=1024: return gaeproxy return None fakehttps = None plugins['plugins.fakehttps'] = 'fakehttps' def find_sock_handler(reqtype, ip, port, cmd): if reqtype == 'https': return fakehttps return None def check_client(ip, reqtype, args): return True " > /data/data/org.gaeproxy/proxy.conf $DIR/python-cl $DIR/wallproxy.py ;; esac
zyh3290-proxy
assets/localproxy.sh
Shell
gpl3
3,569
#! /usr/bin/env python # coding=utf-8 ############################################################################# # # # File: common.py # # # # Copyright (C) 2008-2010 Du XiaoGang <dugang.2008@gmail.com> # # # # Home: http://gappproxy.googlecode.com # # # # This file is part of GAppProxy. # # # # GAppProxy is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as # # published by the Free Software Foundation, either version 3 of the # # License, or (at your option) any later version. # # # # GAppProxy is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # # # You should have received a copy of the GNU General Public License # # along with GAppProxy. If not, see <http://www.gnu.org/licenses/>. # # # ############################################################################# import os, sys def we_are_frozen(): """Returns whether we are frozen via py2exe. This will affect how we find out where we are located.""" return hasattr(sys, "frozen") def module_path(): """ This will get us the program's directory, even if we are frozen using py2exe""" if we_are_frozen(): return os.path.dirname(sys.executable) return os.path.dirname(__file__) dir = module_path() VERSION = "2.0.0" LOAD_BALANCE = 'http://gappproxy-center.appspot.com/available_fetchserver.py' GOOGLE_PROXY = 'www.google.cn:80' DEF_LISTEN_PORT = 8000 DEF_LOCAL_PROXY = '' DEF_FETCH_SERVER = '' DEF_CONF_FILE = os.path.join(dir, 'proxy.conf') DEF_CERT_FILE = os.path.join(dir, 'CA.cert') DEF_KEY_FILE = os.path.join(dir, 'CA.key') class GAppProxyError(Exception): def __init__(self, reason): self.reason = reason def __str__(self): return '<GAppProxy Error: %s>' % self.reason
zyh3290-proxy
assets/common.py
Python
gpl3
2,844
body { font-family: "Helvetica-Bold",Helvetica,Geneva,Arial,sans-serif; margin: 0 0 1em 0; padding: 0; background-image: url("linef.png"); } #main { margin: 0; padding: 0; } a:link, a:visited { color: #333333; text-decoration: none; } input[type="text"] { margin: 0.5em 0 0.5em 0.5em; width: 70%; border: 1px solid #e3e3e3; } input[type="submit"] { background-color: #f5f5f5; border: 1px solid #e3e3e3; } #title { margin: 0 0 0 0; padding-top: 10px; height: 27px; background-color: #f5f5f5; color: #4b4b4b; border-bottom: 1px solid #b1b1b1; font-size: larger; font-weight: bold; text-align: center; } .box-title { margin: 1em 1em 0 1em; padding: 0; background-color: #ffffff; color: #333333; border: 1px solid #b1b1b1; border-radius: 8px 8px 0 0; } .box-title p { margin: 0.25em 0; } .box-title a { margin: 0 0.5em; width: 18px; height: 14px; background-color: #eeeeee; border: 1px solid #cacaca; } .box-title img { vertical-align: middle; padding: 0 0.5em; } .box-content { margin: 0 1em 0 1em; padding: 0; background-color: #ffffff; border: 1px solid #b1b1b1; border-top: 1px solid transparent; border-radius: 0 0 8px 8px; }
zyh3290-proxy
res/raw/start_style.css
CSS
gpl3
1,126
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> <style type="text/css">%s</style> </head> <body> <div id="main"> <div id="title">%s</div> %s </div> </body> </html>
zyh3290-proxy
res/raw/start.html
HTML
gpl3
438
<div id="bookmarks-title" class="box-title"> <p><img src="bookmarks.png" />%s</p> </div> <div id="bookmarks-content" class="box-content"> <ul>%s</ul> </div>
zyh3290-proxy
res/raw/start_bookmarks.html
HTML
gpl3
158
<div id="history-title" class="box-title"> <p><img src="history.png" />%s</p> </div> <div id="history-content" class="box-content"> <ul>%s</ul> </div>
zyh3290-proxy
res/raw/start_history.html
HTML
gpl3
152
<div id="search-title" class="box-title"> <p><img src="search.png" />%s</p> </div> <div id="search-content" class="box-content"> <form method="GET" action="action:search"> <input type="text" name="q"><input type="submit" value="%s"> </form> </div>
zyh3290-proxy
res/raw/start_search.html
HTML
gpl3
252
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; /** * @author Patrick Woodworth */ enum WeaveHeader { X_WEAVE_BACKOFF("X-Weave-Backoff"), X_WEAVE_ALERT("X-Weave-Alert"), X_WEAVE_TIMESTAMP( "X-Weave-Timestamp"), X_WEAVE_RECORDS("X-Weave-Records"), X_WEAVE_IF_UNMODIFIED_SINCE( "X-If-Unmodified-Since"), ; private final String m_name; WeaveHeader(String name) { m_name = name; } public String getName() { return m_name; } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveHeader.java
Java
gpl3
1,040
package org.emergent.android.weave.client; import java.io.IOException; import java.io.OutputStream; class HexEncoder { protected final byte[] encodingTable = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f' }; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; public HexEncoder() { initialiseDecodingTable(); } /** * decode the Hex encoded byte data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode(byte[] data, int off, int length, OutputStream out) throws IOException { byte b1, b2; int outLen = 0; int end = off + length; while (end > off) { if (!ignore((char) data[end - 1])) { break; } end--; } int i = off; while (i < end) { while (i < end && ignore((char) data[i])) { i++; } b1 = decodingTable[data[i++]]; while (i < end && ignore((char) data[i])) { i++; } b2 = decodingTable[data[i++]]; out.write((b1 << 4) | b2); outLen++; } return outLen; } /** * decode the Hex encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode(String data, OutputStream out) throws IOException { byte b1, b2; int length = 0; int end = data.length(); while (end > 0) { if (!ignore(data.charAt(end - 1))) { break; } end--; } int i = 0; while (i < end) { while (i < end && ignore(data.charAt(i))) { i++; } b1 = decodingTable[data.charAt(i++)]; while (i < end && ignore(data.charAt(i))) { i++; } b2 = decodingTable[data.charAt(i++)]; out.write((b1 << 4) | b2); length++; } return length; } /** * encode the input data producing a Hex output stream. * * @return the number of bytes produced. */ public int encode(byte[] data, int off, int length, OutputStream out) throws IOException { for (int i = off; i < (off + length); i++) { int v = data[i] & 0xff; out.write(encodingTable[(v >>> 4)]); out.write(encodingTable[v & 0xf]); } return length * 2; } private boolean ignore(char c) { return (c == '\n' || c == '\r' || c == '\t' || c == ' '); } protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte) i; } decodingTable['A'] = decodingTable['a']; decodingTable['B'] = decodingTable['b']; decodingTable['C'] = decodingTable['c']; decodingTable['D'] = decodingTable['d']; decodingTable['E'] = decodingTable['e']; decodingTable['F'] = decodingTable['f']; } }
zyh3290-proxy
src/org/emergent/android/weave/client/HexEncoder.java
Java
gpl3
2,859
package org.emergent.android.weave.client; import java.io.IOException; import java.net.InetAddress; import java.net.URI; import java.net.UnknownHostException; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.HashSet; import javax.net.ssl.SSLException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpMessage; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org.apache.http.HttpVersion; import org.apache.http.StatusLine; import org.apache.http.auth.AuthScope; import org.apache.http.auth.AuthState; import org.apache.http.auth.Credentials; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.client.HttpClient; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnManagerPNames; import org.apache.http.conn.params.ConnPerRouteBean; 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.AbstractVerifier; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.conn.util.InetAddressUtils; import org.apache.http.impl.auth.BasicScheme; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; /** * @author Patrick Woodworth */ class WeaveTransport { private static class MyInterceptor implements 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 (authState.getAuthScheme() == null) { AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort()); Credentials creds = credsProvider.getCredentials(authScope); if (creds != null) { authState.setAuthScheme(new BasicScheme()); authState.setCredentials(creds); } } } } /** * Based on BasicResponseHandler */ private static class MyResponseHandler implements ResponseHandler<WeaveResponse> { /** * Returns the response body as a String if the response was successful * (a 2xx status code). If no response body exists, this returns null. * If the response was unsuccessful (>= 300 status code), throws an * {@link org.apache.http.client.HttpResponseException}. */ @Override public WeaveResponse handleResponse(final HttpResponse response) throws HttpResponseException, IOException { StatusLine statusLine = response.getStatusLine(); if (statusLine.getStatusCode() >= 300) { throw new WeaveResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase(), response); } return new WeaveResponse(response); } } /** * @author Patrick Woodworth */ static class WeaveHostnameVerifier extends AbstractVerifier { private static boolean isIPAddress(final String hostname) { return hostname != null && (InetAddressUtils.isIPv4Address(hostname) || InetAddressUtils .isIPv6Address(hostname)); } private static void resolveHostAddresses(String cn, Collection<String> retval) { try { InetAddress[] addresses = InetAddress.getAllByName(cn); for (InetAddress address : addresses) { retval.add(address.getHostAddress()); } } catch (UnknownHostException e) { Dbg.d(e); } } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { if (isIPAddress(host) && cns != null && cns.length > 0 && cns[0] != null) { HashSet<String> expandedAlts = new HashSet<String>(); resolveHostAddresses(cns[0], expandedAlts); if (subjectAlts != null) expandedAlts.addAll(Arrays.asList(subjectAlts)); subjectAlts = expandedAlts.toArray(new String[expandedAlts .size()]); } verify(host, cns, subjectAlts, false); } } @SuppressWarnings("serial") public static class WeaveResponseException extends HttpResponseException { private final WeaveResponseHeaders m_responseHeaders; public WeaveResponseException(int statusCode, String reasonPhrase, HttpResponse response) { // super(statusCode, String.format("statusCode = %s ; reason = %s", // statusCode, reasonPhrase)); super(statusCode, reasonPhrase); m_responseHeaders = new WeaveResponseHeaders(response); } public WeaveResponseHeaders getResponseHeaders() { return m_responseHeaders; } @Override public String toString() { String s = getClass().getName(); s += ": (statusCode=" + getStatusCode() + ")"; String message = getLocalizedMessage(); return (message != null) ? (s + " : " + message) : s; } } public static class WeaveResponseHeaders { private final Header[] m_headers; public WeaveResponseHeaders(HttpResponse response) { m_headers = response.getAllHeaders(); } public long getBackoffSeconds() { long retval = 0; try { String valStr = getHeaderValue(WeaveHeader.X_WEAVE_BACKOFF); if (valStr != null) retval = Long.parseLong(valStr); } catch (Exception ignored) { } return retval; } public Header[] getHeaders() { return m_headers; } private String getHeaderValue(String headerName) { for (Header header : m_headers) { if (headerName.equals(header.getName())) return header.getValue(); } return null; } private String getHeaderValue(WeaveHeader header) { return getHeaderValue(header.getName()); } public Date getServerTimestamp() { Date retval = null; String ststamp = getHeaderValue(WeaveHeader.X_WEAVE_TIMESTAMP); if (ststamp != null) retval = WeaveUtil.toModifiedTimeDate(ststamp); return retval; } } private static final int HTTP_PORT_DEFAULT = 80; private static final int HTTPS_PORT_DEFAULT = 443; private static final HttpRequestInterceptor sm_preemptiveAuth = new MyInterceptor(); private static final MyResponseHandler sm_responseHandler = new MyResponseHandler(); private static final HttpParams sm_httpParams; static { HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setUserAgent(params, WeaveConstants.USER_AGENT); HttpProtocolParams.setUseExpectContinue(params, false); // params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false); params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30); params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30)); sm_httpParams = params; } private static SocketFactory createSocketFactory(boolean allowInvalidCerts) { SocketFactory sslSocketFactory; if (allowInvalidCerts) { sslSocketFactory = new WeaveSSLSocketFactory(); } else { sslSocketFactory = SSLSocketFactory.getSocketFactory(); ((SSLSocketFactory) sslSocketFactory) .setHostnameVerifier(new WeaveHostnameVerifier()); } return sslSocketFactory; } private final SocketFactory m_sslSocketFactory; private final ClientConnectionManager m_clientConMgr; public WeaveTransport() { this(WeaveConstants.CONNECTION_POOL_ENABLED_DEFAULT); } public WeaveTransport(boolean useConnectionPool) { this(useConnectionPool, WeaveConstants.ALLOW_INVALID_CERTS_DEFAULT); } public WeaveTransport(boolean useConnectionPool, boolean allowInvalidCerts) { m_sslSocketFactory = createSocketFactory(allowInvalidCerts); m_clientConMgr = useConnectionPool ? createClientConnectionManager(true) : null; } private ClientConnectionManager createClientConnectionManager( boolean threadSafe) { SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory .getSocketFactory(), HTTP_PORT_DEFAULT)); schemeRegistry.register(new Scheme("https", m_sslSocketFactory, HTTPS_PORT_DEFAULT)); if (threadSafe) { return new ThreadSafeClientConnManager(sm_httpParams, schemeRegistry); } else { return new SingleClientConnManager(sm_httpParams, schemeRegistry); } } private DefaultHttpClient createDefaultHttpClient() { ClientConnectionManager connectionManager; if (m_clientConMgr != null) { connectionManager = m_clientConMgr; } else { connectionManager = createClientConnectionManager(false); } return new DefaultHttpClient(connectionManager, sm_httpParams); } private HttpClient createHttpClient(String userId, String password) { DefaultHttpClient retval = createDefaultHttpClient(); Credentials defaultcreds = new UsernamePasswordCredentials(userId, password); retval.getCredentialsProvider().setCredentials(AuthScope.ANY, defaultcreds); retval.addRequestInterceptor(sm_preemptiveAuth, 0); return retval; } public WeaveResponse execDeleteMethod(String username, String password, URI uri) throws IOException, WeaveException { HttpDelete method = new HttpDelete(uri); return execGenericMethod(username, password, uri, method); } private WeaveResponse execGenericMethod(HttpClient client, URI uri, HttpRequestBase method) throws IOException, WeaveException { setMethodHeaders(method); MyResponseHandler responseHandler = sm_responseHandler; String scheme = uri.getScheme(); String hostname = uri.getHost(); int port = uri.getPort(); HttpHost httpHost = new HttpHost(hostname, port, scheme); WeaveResponseHeaders responseHeaders = null; try { WeaveResponse response = client.execute(httpHost, method, responseHandler); response.setUri(uri); responseHeaders = response.getResponseHeaders(); return response; } catch (WeaveResponseException e) { responseHeaders = e.getResponseHeaders(); throw e; } finally { if (responseHeaders != null) { // long backoff = responseHeaders.getBackoffSeconds(); // if (backoff > 0) { // long newbackoff = System.currentTimeMillis() + backoff; // m_backoff.set(newbackoff); // } } } } private WeaveResponse execGenericMethod(String username, String password, URI uri, HttpRequestBase method) throws IOException, WeaveException { HttpClient client = null; try { client = createHttpClient(username, password); return execGenericMethod(client, uri, method); // } catch (IOException e) { // throw new // WeaveException("Unable to communicate with Weave server.", e); } finally { if (m_clientConMgr == null && client != null) { client.getConnectionManager().shutdown(); } } } public WeaveResponse execGetMethod(String username, String password, URI uri) throws IOException, WeaveException { HttpGet method = new HttpGet(uri); return execGenericMethod(username, password, uri, method); } public WeaveResponse execPostMethod(String username, String password, URI uri, HttpEntity entity) throws IOException, WeaveException { HttpPost method = new HttpPost(uri); method.setEntity(entity); return execGenericMethod(username, password, uri, method); } public WeaveResponse execPutMethod(String username, String password, URI uri, HttpEntity entity) throws IOException, WeaveException { HttpPut method = new HttpPut(uri); method.setEntity(entity); return execGenericMethod(username, password, uri, method); } private void setMethodHeaders(HttpMessage method) { method.addHeader("Pragma", "no-cache"); method.addHeader("Cache-Control", "no-cache"); } public void shutdown() { // if (m_clientConMgr != null) // m_clientConMgr.shutdown(); } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveTransport.java
Java
gpl3
12,747
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLEncoder; import java.util.Arrays; import java.util.Date; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HTTP; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; /** * @author Patrick Woodworth */ public class WeaveUtil { public static class UriBuilder { private String m_val; public UriBuilder(URI uri) { m_val = uri.toASCIIString(); } public void appendEncodedPath(String s) { if (m_val.charAt(m_val.length() - 1) != '/') m_val += "/"; m_val += s; } public URI build() { try { return URI.create(m_val); } catch (IllegalArgumentException e) { Dbg.w("BAD URI: %s", m_val); throw e; } } } private static final String JSON_STREAM_TYPE = "application/json"; private static final String ENTITY_CHARSET_NAME = "UTF-8"; public static UriBuilder buildUpon(URI serverUri) { return new UriBuilder(serverUri); } @SuppressWarnings({}) public static void checkNull(String str) { if (str == null || str.trim().length() < 1) { Dbg.w(new IllegalArgumentException( "checkNull(String) had empty arg")); } } @SuppressWarnings({}) public static void checkNull(URI uri) { if (uri == null) { Dbg.w(new IllegalArgumentException("checkNull(URI) had null arg")); } else if (uri.getHost() == null || uri.getHost().length() < 1) { Dbg.w(new IllegalArgumentException("checkNull(URI) had empty host")); } } public static void dump(JSONObject jsonObject) { try { String out = jsonObject.toString(2); System.out.println(out); } catch (JSONException e) { e.printStackTrace(); } } public static String encodeUriSegment(String segment) { try { return URLEncoder.encode(segment, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } public static byte[] toAsciiBytes(String data) { try { return data == null ? null : data.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } public static String toAsciiString(byte[] data) { try { return data == null ? null : new String(data, "US-ASCII"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } @SuppressWarnings("unused") private static HttpEntity toHttpEntity(JSONArray jsonArray) throws JSONException { try { StringEntity entity = new StringEntity(jsonArray.toString(0), ENTITY_CHARSET_NAME); entity.setContentType(JSON_STREAM_TYPE + HTTP.CHARSET_PARAM + ENTITY_CHARSET_NAME); return entity; } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } @SuppressWarnings("unused") private static HttpEntity toHttpEntity(WeaveBasicObject wbo) throws JSONException { try { StringEntity entity = new StringEntity(wbo.toJSONObjectString(), ENTITY_CHARSET_NAME); entity.setContentType(JSON_STREAM_TYPE + HTTP.CHARSET_PARAM + ENTITY_CHARSET_NAME); return entity; } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } public static Date toModifiedTimeDate(double modDouble) { try { long mod = Math.round(modDouble * 1000); return new Date(mod); } catch (Exception e) { return null; } } public static Date toModifiedTimeDate(String modified) { @SuppressWarnings("unused") long now = System.currentTimeMillis(); try { double modDouble = Double.parseDouble(modified) * 1000; long mod = Math.round(modDouble); // Dbg.printf("mod: %d ; cur : %d ; delta : %d\n", mod, now, now - // mod); return new Date(mod); } catch (Exception e) { return new Date(); // todo buggy ? } } public static String toModifiedTimeString(Date modified) { long time = modified.getTime(); double timed = time / 1000.0; String retval = String.format(Locale.ENGLISH, "%.2f", timed); // Dbg.debug("TIME: " + retval); return retval; } public static String toString(URI uri) { checkNull(uri); String retval = uri == null ? null : uri.toString(); checkNull(retval); return retval; } public static byte[] toUtf8Bytes(String data) { try { return data == null ? null : data.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } public static String toUtf8String(byte[] data) { try { return data == null ? null : new String(data, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } public static void zeroize(char[] secret) { if (secret != null) Arrays.fill(secret, '\0'); } private WeaveUtil() { // no instantiation } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveUtil.java
Java
gpl3
5,452
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.io.IOException; import java.net.URI; import java.util.Date; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.util.EntityUtils; /** * @author Patrick Woodworth */ public class WeaveResponse { private final WeaveTransport.WeaveResponseHeaders m_responseHeaders; private final String m_body; private URI m_uri; public WeaveResponse(HttpResponse response) throws IOException { m_responseHeaders = new WeaveTransport.WeaveResponseHeaders(response); HttpEntity entity = response.getEntity(); m_body = entity == null ? null : EntityUtils.toString(entity); } public long getBackoffSeconds() { return m_responseHeaders.getBackoffSeconds(); } public String getBody() { return m_body; } public WeaveTransport.WeaveResponseHeaders getResponseHeaders() { return m_responseHeaders; } public Date getServerTimestamp() { return m_responseHeaders.getServerTimestamp(); } public URI getUri() { return m_uri; } public void setUri(URI uri) { m_uri = uri; } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveResponse.java
Java
gpl3
1,688
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.net.URI; import java.util.Date; /** * @author Patrick Woodworth */ public class QueryResult<T> { private final URI m_uri; private Date m_serverTimestamp; private T m_value; QueryResult(WeaveResponse response) { this(response, null); } QueryResult(WeaveResponse response, T value) { m_uri = response.getUri(); m_serverTimestamp = response.getServerTimestamp(); m_value = value; } public Date getServerTimestamp() { return m_serverTimestamp; } public long getServerTimestampInSeconds() { if (m_serverTimestamp != null) return m_serverTimestamp.getTime(); return 0; } public URI getUri() { return m_uri; } public T getValue() { return m_value; } void setValue(T value) { m_value = value; } }
zyh3290-proxy
src/org/emergent/android/weave/client/QueryResult.java
Java
gpl3
1,398
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.util.Date; /** * @author Patrick Woodworth */ public class QueryParams { private Date m_older; private Date m_newer; private boolean m_full = true; private String m_sort = "newest"; public QueryParams() { } public Date getNewer() { return m_newer; } public Date getOlder() { return m_older; } public String getSort() { return m_sort; } public boolean isFull() { return m_full; } public QueryParams setFull(boolean full) { m_full = full; return this; } public QueryParams setNewer(Date newer) { m_newer = newer; return this; } public QueryParams setOlder(Date older) { m_older = older; return this; } public QueryParams setSort(String sort) { m_sort = sort; return this; } public String toQueryString() { StringBuffer retval = new StringBuffer(); retval.append("?full=").append(m_full ? "1" : "0"); if (m_sort != null) retval.append("&sort=").append(m_sort); if (m_older != null) retval.append("&older=").append( WeaveUtil.toModifiedTimeString(m_older)); if (m_newer != null) retval.append("&newer=").append( WeaveUtil.toModifiedTimeString(m_newer)); return retval.toString(); } @Override public String toString() { return toQueryString(); } }
zyh3290-proxy
src/org/emergent/android/weave/client/QueryParams.java
Java
gpl3
1,901
package org.emergent.android.weave.client; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.logging.Logger; /** * @author Patrick Woodworth */ class Dbg { @SuppressWarnings("serial") public static class DebugLogRecord extends LogRecord { /** * @serial Class that issued logging call */ private String sourceClassName; /** * @serial Method that issued logging call */ private String sourceMethodName; private transient boolean needToInferCaller = true; DebugLogRecord(Level level, String msg) { super(level, msg); } /** * {@inheritDoc} */ @Override public String getSourceClassName() { if (sourceClassName == null) { inferCaller(); } return sourceClassName; } /** * {@inheritDoc} */ @Override public String getSourceMethodName() { if (needToInferCaller) { inferCaller(); } return sourceMethodName; } private void inferCaller() { // Get the stack trace. StackTraceElement stack[] = (new Throwable()).getStackTrace(); // First, search back to a method in the Logger class. int ix = 0; while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (cname.equals(Dbg.class.getName())) { break; } ix++; } // Now search for the first frame before the "Logger" class. while (ix < stack.length) { StackTraceElement frame = stack[ix]; String cname = frame.getClassName(); if (!cname.equals(Dbg.class.getName())) { // We've found the relevant frame. setSourceClassName(cname); setSourceMethodName(frame.getMethodName()); return; } ix++; } // We haven't found a suitable frame, so just punt. This is // OK as we are only committed to making a "best effort" here. } /** * {@inheritDoc} */ @Override public void setSourceClassName(String sourceClassName) { this.sourceClassName = sourceClassName; needToInferCaller = false; } /** * {@inheritDoc} */ @Override public void setSourceMethodName(String sourceMethodName) { this.sourceMethodName = sourceMethodName; needToInferCaller = false; } } private static final Level LEVEL_ANDROID_VERBOSE = Level.FINE; // should // never // ship // using // this private static final Level LEVEL_ANDROID_DEBUG = Level.CONFIG; // stripped // at // runtime // (except // on // emulator?) @SuppressWarnings("unused") private static final Level LEVEL_ANDROID_INFO = Level.INFO; private static final Level LEVEL_ANDROID_WARN = Level.WARNING; @SuppressWarnings("unused") private static final Level LEVEL_ANDROID_ERROR = Level.SEVERE; @SuppressWarnings("unused") private static final Level LEVEL_V = LEVEL_ANDROID_VERBOSE; // private static final Level LEVEL_D = LEVEL_ANDROID_INFO; private static final Level LEVEL_D = LEVEL_ANDROID_DEBUG; private static final Level LEVEL_W = LEVEL_ANDROID_WARN; private static final Logger sm_logger = Logger .getLogger(WeaveConstants.LOGGER_NAME_FULL); public static void d(String fmt, Object... args) { logf(LEVEL_D, fmt, args); } public static void d(Throwable e) { log(LEVEL_D, e); } public static void d(Throwable e, String fmt, Object... args) { logf(LEVEL_D, e, fmt, args); } private static void log(Level level, Throwable e) { if (!sm_logger.isLoggable(level)) return; LogRecord lr = new DebugLogRecord(level, "Something was thrown!"); lr.setThrown(e); lr.setLoggerName(sm_logger.getName()); sm_logger.log(lr); } private static void logf(Level level, String msg, Object... params) { if (!sm_logger.isLoggable(level)) return; LogRecord lr = new DebugLogRecord(level, String.format(msg, params)); lr.setLoggerName(sm_logger.getName()); sm_logger.log(lr); } private static void logf(Level level, Throwable e, String msg, Object... params) { if (!sm_logger.isLoggable(level)) return; LogRecord lr = new DebugLogRecord(level, String.format(msg, params)); lr.setThrown(e); lr.setLoggerName(sm_logger.getName()); sm_logger.log(lr); } public static void v(String fmt, Object... args) { // logf(LEVEL_V, fmt, args); } public static void v(Throwable e) { // log(LEVEL_V, e); } public static void v(Throwable e, String fmt, Object... args) { // logf(LEVEL_V, e, fmt, args); } public static void w(String fmt, Object... args) { logf(LEVEL_W, fmt, args); } public static void w(Throwable e) { log(LEVEL_W, e); } public static void w(Throwable e, String fmt, Object... args) { logf(LEVEL_W, e, fmt, args); } private Dbg() { // no instantiation } }
zyh3290-proxy
src/org/emergent/android/weave/client/Dbg.java
Java
gpl3
4,641
package org.emergent.android.weave.client; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.Key; import java.security.interfaces.RSAPublicKey; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import javax.crypto.spec.SecretKeySpec; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class UserWeave { public enum CollectionNode { STORAGE_BOOKMARKS("bookmarks"), STORAGE_PASSWORDS("passwords"), ; public final String engineName; public final String nodePath; CollectionNode(String engineName) { this.engineName = engineName; this.nodePath = "/storage/" + this.engineName; } } public enum HashNode { INFO_COLLECTIONS(false, "/info/collections"), META_GLOBAL(false, "/storage/meta/global"), ; public final boolean userServer; public final String nodePath; HashNode(boolean userServer, String path) { this.userServer = userServer; this.nodePath = path; } } protected static URI buildSyncUriFromSubpath(URI clusterUri, String userId, QueryParams params, String pathSection) { String subpath = pathSection; if (params != null) subpath = subpath + params.toQueryString(); WeaveUtil.checkNull(clusterUri); WeaveUtil.UriBuilder builder = WeaveUtil.buildUpon(clusterUri); builder.appendEncodedPath(WeaveConstants.WEAVE_API_VERSION + "/" + userId); while (subpath.startsWith("/")) { subpath = subpath.substring(1); } builder.appendEncodedPath(subpath); return builder.build(); } protected static URI buildSyncUriFromSubpath(URI clusterUri, String userId, String subpath) { return buildSyncUriFromSubpath(clusterUri, userId, null, subpath); } protected static URI buildUserUriFromSubpath(URI authUri, String userId, String subpath) { WeaveUtil.checkNull(authUri); WeaveUtil.UriBuilder builder = WeaveUtil.buildUpon(authUri); builder.appendEncodedPath("user/" + WeaveConstants.WEAVE_API_VERSION + "/" + userId); while (subpath.startsWith("/")) { subpath = subpath.substring(1); } builder.appendEncodedPath(subpath); return builder.build(); } private final WeaveTransport m_transport; private final URI m_authUri; @SuppressWarnings("unused") private final String m_userId; private final String m_password; private final String m_legalUsername; private final AtomicReference<URI> m_clusterUri; UserWeave(WeaveTransport transport, URI authUri, String userId, String password) { this(transport, authUri, userId, password, null); } protected UserWeave(WeaveTransport transport, URI authUri, String userId, String password, URI clusterUri) { m_authUri = authUri; m_userId = userId; m_legalUsername = WeaveCryptoUtil.getInstance() .legalizeUsername(userId); m_password = password; m_transport = transport; m_clusterUri = new AtomicReference<URI>(clusterUri); } public void authenticate() throws WeaveException { JSONObject jsonObj = getNode(HashNode.INFO_COLLECTIONS).getValue(); jsonObj.has("foo"); } public void authenticateSecret(char[] secret) throws WeaveException { authenticate(); } public URI buildSyncUriFromSubpath(String subpath) throws WeaveException { return buildSyncUriFromSubpath(getClusterUri(), getLegalUsername(), subpath); } public URI buildUserUriFromSubpath(String subpath) { return buildUserUriFromSubpath(m_authUri, getLegalUsername(), subpath); } public boolean checkUsernameAvailable() throws WeaveException { try { String nodePath = "/"; String nodeStrVal = getUserNode(nodePath).getBody(); return Integer.parseInt(nodeStrVal) == 0; } catch (NumberFormatException e) { throw new WeaveException(e); } } protected BulkKeyCouplet getBulkKeyPair(byte[] syncKey) throws GeneralSecurityException, WeaveException { try { byte[] keyBytes = WeaveCryptoUtil.deriveSyncKey(syncKey, getLegalUsername()); Key bulkKey = new SecretKeySpec(keyBytes, "AES"); byte[] hmkeyBytes = WeaveCryptoUtil.deriveSyncHmacKey(syncKey, keyBytes, getLegalUsername()); Key hmbulkKey = new SecretKeySpec(hmkeyBytes, "AES"); JSONObject ckwbojsonobj = getCryptoKeys(); WeaveBasicObject.WeaveEncryptedObject weo = new WeaveBasicObject.WeaveEncryptedObject( ckwbojsonobj); JSONObject ckencPayload = weo.decryptObject(bulkKey, hmbulkKey); JSONArray jsonArray = ckencPayload.getJSONArray("default"); String bkey2str = jsonArray.getString(0); String bhmac2str = jsonArray.getString(1); byte[] bkey2bytes = Base64.decode(bkey2str); Key bulkKey2 = new SecretKeySpec(bkey2bytes, "AES"); byte[] bhmac2bytes = Base64.decode(bhmac2str); Key bulkHmacKey2 = new SecretKeySpec(bhmac2bytes, "AES"); return new BulkKeyCouplet(bulkKey2, bulkHmacKey2); } catch (JSONException e) { throw new WeaveException(e); } } public final URI getClusterUri() throws WeaveException { return getClusterUri(true); } public final URI getClusterUri(boolean useCache) throws WeaveException { URI cached = null; if (useCache && ((cached = m_clusterUri.get()) != null)) return cached; URI retval = getClusterUriSafe(); m_clusterUri.compareAndSet(cached, retval); return retval; } private URI getClusterUriSafe() { URI retval = m_authUri; try { URI unsafeResult = getClusterUriUnsafe(); if (unsafeResult != null) retval = unsafeResult; } catch (Exception ignored) { // Dbg.v(e); } return retval; } private URI getClusterUriUnsafe() throws WeaveException { try { String nodePath = "/node/weave"; String nodeWeaveVal = getUserNode(nodePath).getBody(); return new URI(nodeWeaveVal); } catch (URISyntaxException e) { throw new WeaveException(e); } } protected JSONObject getCryptoKeys() throws WeaveException { try { URI nodeUri = buildSyncUriFromSubpath("/storage/crypto/keys"); WeaveBasicObject nodeObj = new WeaveBasicObject(nodeUri, new JSONObject(getNode(nodeUri).getBody())); return nodeObj.getPayload(); } catch (JSONException e) { throw new WeaveException(e); } } public String getLegalUsername() { return m_legalUsername; } public QueryResult<JSONObject> getNode(HashNode node) throws WeaveException { try { URI nodeUri = node.userServer ? buildUserUriFromSubpath(node.nodePath) : buildSyncUriFromSubpath(node.nodePath); WeaveResponse result = getNode(nodeUri); return new QueryResult<JSONObject>(result, new JSONObject( result.getBody())); } catch (JSONException e) { throw new WeaveException(e); } } protected final WeaveResponse getNode(URI nodeUri) throws WeaveException { try { return m_transport.execGetMethod(getLegalUsername(), m_password, nodeUri); } catch (IOException e) { throw new WeaveException(e); } } protected RSAPublicKey getPublicKey() throws WeaveException { try { URI nodeUri = buildSyncUriFromSubpath("/storage/keys/pubkey"); WeaveBasicObject nodeObj = new WeaveBasicObject(nodeUri, new JSONObject(getNode(nodeUri).getBody())); JSONObject payloadObj = nodeObj.getPayload(); String pubKey = payloadObj.getString("keyData"); return WeaveCryptoUtil.getInstance().readCertificatePubKey(pubKey); } catch (GeneralSecurityException e) { throw new WeaveException(e); } catch (JSONException e) { throw new WeaveException(e); } } protected final WeaveResponse getUserNode(String path) throws WeaveException { URI nodeUri = buildUserUriFromSubpath(path); return getNode(nodeUri); } public QueryResult<List<WeaveBasicObject>> getWboCollection(URI uri) throws WeaveException { try { WeaveResponse response = getNode(uri); QueryResult<List<WeaveBasicObject>> result = new QueryResult<List<WeaveBasicObject>>( response); JSONArray jsonPassArray = new JSONArray(response.getBody()); List<WeaveBasicObject> records = new ArrayList<WeaveBasicObject>(); for (int ii = 0; ii < jsonPassArray.length(); ii++) { JSONObject jsonObj = jsonPassArray.getJSONObject(ii); WeaveBasicObject wbo = new WeaveBasicObject(uri, jsonObj); records.add(wbo); } result.setValue(records); return result; } catch (JSONException e) { throw new WeaveException(e); } } public final URI setClusterUri(URI clusterUri) { return m_clusterUri.getAndSet(clusterUri); } public void shutdown() { m_transport.shutdown(); } }
zyh3290-proxy
src/org/emergent/android/weave/client/UserWeave.java
Java
gpl3
8,484
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import org.apache.http.conn.scheme.LayeredSocketFactory; import org.apache.http.conn.scheme.SocketFactory; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * This socket factory will create ssl socket that uses configurable validation * of certificates (e.g. allowing self-signed). */ class WeaveSSLSocketFactory implements SocketFactory, LayeredSocketFactory { private static class WeaveX509TrustManager implements X509TrustManager { private X509TrustManager m_standardTrustManager = null; // private static boolean sm_issued = false; public WeaveX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException { super(); TrustManagerFactory factory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); factory.init(keystore); TrustManager[] trustmanagers = factory.getTrustManagers(); if (trustmanagers.length == 0) { throw new NoSuchAlgorithmException("no trust manager found"); } m_standardTrustManager = (X509TrustManager) trustmanagers[0]; } /** * @see X509TrustManager#checkClientTrusted(X509Certificate[],String) */ @Override public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException { m_standardTrustManager.checkClientTrusted(certificates, authType); } /** * @see X509TrustManager#checkServerTrusted(X509Certificate[],String) */ @Override public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException { // if (ENUMERATE_TRUSTED_CAS && !sm_issued) { // Dbg.d("CA certs:"); // X509Certificate[] cas = getAcceptedIssuers(); // for (X509Certificate ca : cas) { // Dbg.d(" " + ca.getSubjectDN()); // } // sm_issued = true; // } if (DISABLE_SERVER_CERT_CHECK) return; // if ((certificates != null) && (certificates.length == 1)) { // // self-signed check // certificates[0].checkValidity(); // } else { // // normal check // m_standardTrustManager.checkServerTrusted(certificates, // authType); // } } /** * @see X509TrustManager#getAcceptedIssuers() */ @Override public X509Certificate[] getAcceptedIssuers() { return this.m_standardTrustManager.getAcceptedIssuers(); } } // private static final boolean ENUMERATE_TRUSTED_CAS = false; private static final boolean DISABLE_SERVER_CERT_CHECK = true; // todo look // into this private static SSLContext createEasySSLContext() throws IOException { try { SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new WeaveX509TrustManager( null) }, null); return context; } catch (Exception e) { throw new IOException(e.getMessage()); } } private SSLContext m_sslcontext = null; /** * @see SocketFactory#connectSocket(Socket, String, int, InetAddress, int, * HttpParams) */ @Override public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException { int connTimeout = HttpConnectionParams.getConnectionTimeout(params); int soTimeout = HttpConnectionParams.getSoTimeout(params); InetSocketAddress remoteAddress = new InetSocketAddress(host, port); SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket()); if ((localAddress != null) || (localPort > 0)) { if (localPort < 0) { localPort = 0; } InetSocketAddress isa = new InetSocketAddress(localAddress, localPort); sslsock.bind(isa); } sslsock.connect(remoteAddress, connTimeout); sslsock.setSoTimeout(soTimeout); return sslsock; } /** * @see SocketFactory#createSocket() */ @Override public Socket createSocket() throws IOException { return getSSLContext().getSocketFactory().createSocket(); } /** * @see LayeredSocketFactory#createSocket(Socket, String, int, boolean) */ @Override public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException { return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose); } @Override public boolean equals(Object obj) { return ((obj != null) && obj.getClass().equals( WeaveSSLSocketFactory.class)); } private synchronized SSLContext getSSLContext() throws IOException { if (m_sslcontext == null) { m_sslcontext = createEasySSLContext(); } return m_sslcontext; } @Override public int hashCode() { return WeaveSSLSocketFactory.class.hashCode(); } /** * @see SocketFactory#isSecure(Socket) */ @Override public boolean isSecure(Socket socket) throws IllegalArgumentException { return true; } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveSSLSocketFactory.java
Java
gpl3
5,919
package org.emergent.android.weave.client; import java.io.IOException; import java.io.OutputStream; class Base64Encoder { protected final byte[] encodingTable = { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }; protected byte padding = (byte) '='; /* * set up the decoding table. */ protected final byte[] decodingTable = new byte[128]; public Base64Encoder() { initialiseDecodingTable(); } /** * decode the base 64 encoded byte data writing it to the given output * stream, whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode(byte[] data, int off, int length, OutputStream out) throws IOException { byte b1, b2, b3, b4; int outLen = 0; int end = off + length; while (end > off) { if (!ignore((char) data[end - 1])) { break; } end--; } int i = off; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data[i++]]; i = nextI(data, i, finish); b2 = decodingTable[data[i++]]; i = nextI(data, i, finish); b3 = decodingTable[data[i++]]; i = nextI(data, i, finish); b4 = decodingTable[data[i++]]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); outLen += 3; i = nextI(data, i, finish); } outLen += decodeLastBlock(out, (char) data[end - 4], (char) data[end - 3], (char) data[end - 2], (char) data[end - 1]); return outLen; } /** * decode the base 64 encoded String data writing it to the given output * stream, whitespace characters will be ignored. * * @return the number of bytes produced. */ public int decode(String data, OutputStream out) throws IOException { byte b1, b2, b3, b4; int length = 0; int end = data.length(); while (end > 0) { if (!ignore(data.charAt(end - 1))) { break; } end--; } int i = 0; int finish = end - 4; i = nextI(data, i, finish); while (i < finish) { b1 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b2 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b3 = decodingTable[data.charAt(i++)]; i = nextI(data, i, finish); b4 = decodingTable[data.charAt(i++)]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); length += 3; i = nextI(data, i, finish); } length += decodeLastBlock(out, data.charAt(end - 4), data.charAt(end - 3), data.charAt(end - 2), data.charAt(end - 1)); return length; } private int decodeLastBlock(OutputStream out, char c1, char c2, char c3, char c4) throws IOException { byte b1, b2, b3, b4; if (c3 == padding) { b1 = decodingTable[c1]; b2 = decodingTable[c2]; out.write((b1 << 2) | (b2 >> 4)); return 1; } else if (c4 == padding) { b1 = decodingTable[c1]; b2 = decodingTable[c2]; b3 = decodingTable[c3]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); return 2; } else { b1 = decodingTable[c1]; b2 = decodingTable[c2]; b3 = decodingTable[c3]; b4 = decodingTable[c4]; out.write((b1 << 2) | (b2 >> 4)); out.write((b2 << 4) | (b3 >> 2)); out.write((b3 << 6) | b4); return 3; } } /** * encode the input data producing a base 64 output stream. * * @return the number of bytes produced. */ public int encode(byte[] data, int off, int length, OutputStream out) throws IOException { int modulus = length % 3; int dataLength = (length - modulus); int a1, a2, a3; for (int i = off; i < off + dataLength; i += 3) { a1 = data[i] & 0xff; a2 = data[i + 1] & 0xff; a3 = data[i + 2] & 0xff; out.write(encodingTable[(a1 >>> 2) & 0x3f]); out.write(encodingTable[((a1 << 4) | (a2 >>> 4)) & 0x3f]); out.write(encodingTable[((a2 << 2) | (a3 >>> 6)) & 0x3f]); out.write(encodingTable[a3 & 0x3f]); } /* * process the tail end. */ int b1, b2, b3; int d1, d2; switch (modulus) { case 0: /* nothing left to do */ break; case 1: d1 = data[off + dataLength] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = (d1 << 4) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(padding); out.write(padding); break; case 2: d1 = data[off + dataLength] & 0xff; d2 = data[off + dataLength + 1] & 0xff; b1 = (d1 >>> 2) & 0x3f; b2 = ((d1 << 4) | (d2 >>> 4)) & 0x3f; b3 = (d2 << 2) & 0x3f; out.write(encodingTable[b1]); out.write(encodingTable[b2]); out.write(encodingTable[b3]); out.write(padding); break; } return (dataLength / 3) * 4 + ((modulus == 0) ? 0 : 4); } private boolean ignore(char c) { return (c == '\n' || c == '\r' || c == '\t' || c == ' '); } protected void initialiseDecodingTable() { for (int i = 0; i < encodingTable.length; i++) { decodingTable[encodingTable[i]] = (byte) i; } } private int nextI(byte[] data, int i, int finish) { while ((i < finish) && ignore((char) data[i])) { i++; } return i; } private int nextI(String data, int i, int finish) { while ((i < finish) && ignore(data.charAt(i))) { i++; } return i; } }
zyh3290-proxy
src/org/emergent/android/weave/client/Base64Encoder.java
Java
gpl3
5,947
package org.emergent.android.weave.client; import java.net.URI; import java.net.URISyntaxException; import org.json.JSONException; import org.json.JSONObject; /** * @author Patrick Woodworth */ public class WeaveAccountInfo { public static WeaveAccountInfo createWeaveAccountInfo(String authtoken) { try { JSONObject retval = new JSONObject(authtoken); URI server = URI.create(retval.getString("server")); String username = retval.getString("username"); String password = retval.getString("password"); char[] secret = retval.getString("secret").toCharArray(); return createWeaveAccountInfo(server, username, password, secret); } catch (JSONException e) { throw new IllegalStateException(e); } } public static WeaveAccountInfo createWeaveAccountInfo(String serverUri, String username, String password, char[] encsecret) throws URISyntaxException { return createWeaveAccountInfo(new URI(serverUri), username, password, encsecret); } public static WeaveAccountInfo createWeaveAccountInfo(URI serverUri, String username, String password, char[] encsecret) { return new WeaveAccountInfo(serverUri, username, password, encsecret); } private final URI m_server; private final String m_username; private final String m_password; private final char[] m_secret; private WeaveAccountInfo(URI server, String username, String password, char[] secret) { if (server == null) throw new NullPointerException("server was null"); if (username == null) throw new NullPointerException("username was null"); if (password == null) throw new NullPointerException("password was null"); if (secret == null) throw new NullPointerException("secret was null"); m_server = server; m_username = username; m_password = password; m_secret = secret; } public String getPassword() { return m_password; } public char[] getSecret() { return m_secret; } public String getSecretAsString() { return m_secret == null ? null : new String(m_secret); } public URI getServer() { return m_server; } public String getServerAsString() { return WeaveUtil.toString(getServer()); } public String getUsername() { return m_username; } public String toAuthToken() { try { JSONObject retval = new JSONObject(); retval.put("server", getServerAsString()); retval.put("username", getUsername()); retval.put("password", getPassword()); retval.put("secret", getSecretAsString()); return retval.toString(); } catch (JSONException e) { throw new IllegalStateException(e); } } @Override public String toString() { try { return toAuthToken(); } catch (Exception ignored) { } return super.toString(); } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveAccountInfo.java
Java
gpl3
2,715
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.net.URI; /** * @author Patrick Woodworth */ public class WeaveFactory { private WeaveTransport m_transport; private final boolean m_acceptInvalidCerts; private final boolean m_useConnectionPool; public WeaveFactory(boolean acceptInvalidCerts) { m_acceptInvalidCerts = acceptInvalidCerts; m_useConnectionPool = WeaveConstants.CONNECTION_POOL_ENABLED_DEFAULT; } public UserWeave createUserWeave(URI server, String username, String password) { return new UserWeave(getWeaveTransport(), server, username, password); } protected WeaveTransport createWeaveTransport() { return new WeaveTransport(isConnectionPoolEnabled(), isInvalidCertsAccepted()); } protected synchronized WeaveTransport getWeaveTransport() { if (m_transport == null) { m_transport = createWeaveTransport(); } return m_transport; } public boolean isConnectionPoolEnabled() { return m_useConnectionPool; } public boolean isInvalidCertsAccepted() { return m_acceptInvalidCerts; } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveFactory.java
Java
gpl3
1,652
package org.emergent.android.weave.client; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; class Base64 { private static final Base64Encoder encoder = new Base64Encoder(); /** * decode the base 64 encoded input data. It is assumed the input data is * valid. * * @return a byte array representing the decoded data. */ public static byte[] decode(byte[] data) { int len = data.length / 4 * 3; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode(String data) { int len = data.length() / 4 * 3; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding base64 string: " + e); } return bOut.toByteArray(); } /** * decode the base 64 encoded String data writing it to the given output * stream, whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode(String data, OutputStream out) throws IOException { return encoder.decode(data, out); } /** * encode the input data producing a base 64 encoded byte array. * * @return a byte array containing the base 64 encoded data. */ public static byte[] encode(byte[] data) { int len = (data.length + 2) / 3 * 4; ByteArrayOutputStream bOut = new ByteArrayOutputStream(len); try { encoder.encode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding base64 string: " + e); } return bOut.toByteArray(); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode(byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, off, length, out); } /** * Encode the byte data to base 64 writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode(byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } }
zyh3290-proxy
src/org/emergent/android/weave/client/Base64.java
Java
gpl3
2,518
package org.emergent.android.weave.client; import java.io.ByteArrayInputStream; import java.security.GeneralSecurityException; import java.security.Key; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.Provider; import java.security.Security; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.util.regex.Pattern; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * @author Patrick Woodworth */ class WeaveCryptoUtil { private static final String PROVIDER_NAME = "BC"; private static final String PROVIDER_CLASS = "org.bouncycastle.jce.provider.BouncyCastleProvider"; private static final byte[] HMAC_INPUT = WeaveUtil .toAsciiBytes("Sync-AES_256_CBC-HMAC256"); private static final Pattern ILLEGAL_USERNAME_PATTERN = Pattern.compile( "[^A-Z0-9._-]", Pattern.CASE_INSENSITIVE); private static final WeaveCryptoUtil sm_instance = new WeaveCryptoUtil(); static { initProvider(PROVIDER_NAME, PROVIDER_CLASS); } /** * This code basically inlines usage of the BouncyCastle private API and is * equivalent to the following code. * * <pre> * { * &#064;code * PBEParametersGenerator generator = new PKCS5S2ParametersGenerator(); * generator.init(PBEParametersGenerator.PKCS5PasswordToBytes(secret), salt, * 4096); * CipherParameters keyParam = generator.generateDerivedParameters(256); * return ((KeyParameter) keyParam).getKey(); * } * </pre> */ private static byte[] derivePKCS5S2(char[] secret, byte[] salt) throws GeneralSecurityException { byte[] secretBytes = passwordPKCS5ToBytes(secret); int keySizeInBytes = 256 / 8; final int iterations = 4096; Mac hMac = Mac.getInstance("HMACSHA1"); int hLen = hMac.getMacLength(); int l = (keySizeInBytes + hLen - 1) / hLen; byte[] iBuf = new byte[4]; byte[] dKey = new byte[l * hLen]; for (int i = 1; i <= l; i++) { intToOctet(iBuf, i); derivePKCS5S2Helper(hMac, secretBytes, salt, iterations, iBuf, dKey, (i - 1) * hLen); } byte[] retval = new byte[keySizeInBytes]; System.arraycopy(dKey, 0, retval, 0, keySizeInBytes); return retval; } private static void derivePKCS5S2Helper(Mac hMac, byte[] P, byte[] S, int c, byte[] iBuf, byte[] out, int outOff) throws GeneralSecurityException { byte[] state = new byte[hMac.getMacLength()]; SecretKeySpec param = new SecretKeySpec(P, "SHA1"); hMac.init(param); if (S != null) { hMac.update(S, 0, S.length); } hMac.update(iBuf, 0, iBuf.length); hMac.doFinal(state, 0); System.arraycopy(state, 0, out, outOff, state.length); if (c == 0) { throw new IllegalArgumentException( "iteration count must be at least 1."); } for (int count = 1; count < c; count++) { hMac.init(param); hMac.update(state, 0, state.length); hMac.doFinal(state, 0); for (int j = 0; j != state.length; j++) { out[outOff + j] ^= state[j]; } } } public static byte[] deriveSyncHmacKey(byte[] secretBytes, byte[] bkbytes, String username) throws GeneralSecurityException { int keySizeInBytes = 256 / 8; Mac hMac = Mac.getInstance("HMACSHA256"); byte[] state = new byte[hMac.getMacLength()]; SecretKeySpec param = new SecretKeySpec(secretBytes, "SHA256"); hMac.init(param); hMac.update(bkbytes); // hMac.update(WeaveUtil.toAsciiBytes(bkstr)); hMac.update(HMAC_INPUT); hMac.update(WeaveUtil.toAsciiBytes(username)); hMac.update((byte) 0x2); hMac.doFinal(state, 0); byte[] retval = new byte[keySizeInBytes]; System.arraycopy(state, 0, retval, 0, keySizeInBytes); return retval; } public static byte[] deriveSyncKey(byte[] secretBytes, String username) throws GeneralSecurityException { int keySizeInBytes = 256 / 8; Mac hMac = Mac.getInstance("HMACSHA256"); byte[] state = new byte[hMac.getMacLength()]; SecretKeySpec param = new SecretKeySpec(secretBytes, "SHA256"); hMac.init(param); hMac.update(HMAC_INPUT); hMac.update(WeaveUtil.toAsciiBytes(username)); hMac.update((byte) 0x1); hMac.doFinal(state, 0); byte[] retval = new byte[keySizeInBytes]; System.arraycopy(state, 0, retval, 0, keySizeInBytes); return retval; } public static WeaveCryptoUtil getInstance() { return sm_instance; } @SuppressWarnings("unchecked") protected static boolean initProvider(String providerName, String className) { try { Provider provider = Security.getProvider(providerName); if (provider == null) { Class clazz = Class.forName(className); provider = (Provider) clazz.newInstance(); Security.addProvider(provider); } return true; } catch (Throwable ignored) { } return false; } private static void intToOctet(byte[] buf, int i) { buf[0] = (byte) (i >>> 24); buf[1] = (byte) (i >>> 16); buf[2] = (byte) (i >>> 8); buf[3] = (byte) i; } private static byte[] passwordPKCS5ToBytes(char[] password) { byte[] bytes = new byte[password.length]; for (int ii = 0; ii != bytes.length; ii++) { bytes[ii] = (byte) password[ii]; } return bytes; } private WeaveCryptoUtil() { } private void checkMac(Key secKey, String ciphertext, String hmac) throws GeneralSecurityException { String hmac2 = createMac(secKey, ciphertext); if (!hmac.equalsIgnoreCase(hmac2)) throw new GeneralSecurityException("mac failed"); } private String createMac(Key secKey, String ciphertext) throws GeneralSecurityException { Mac mac = Mac.getInstance("HMACSHA256", PROVIDER_NAME); // mac.init(new SecretKeySpec(Base64.encode(secKey.getEncoded()), // "AES")); mac.init(secKey); byte[] hmacBytes = mac.doFinal(WeaveUtil.toAsciiBytes(ciphertext)); return WeaveUtil.toAsciiString(Hex.encode(hmacBytes)); } public RSAPrivateKey decodePrivateKeyFromPKCSBytes(byte[] keySpecBytes) throws GeneralSecurityException { KeySpec keySpec = new PKCS8EncodedKeySpec(keySpecBytes); KeyFactory keyFact = KeyFactory.getInstance("RSA", PROVIDER_NAME); return (RSAPrivateKey) keyFact.generatePrivate(keySpec); } public byte[] decrypt(Key secKey, Key hmacKey, String ciphertext, String iv, String hmac) throws GeneralSecurityException { checkMac(hmacKey, ciphertext, hmac); byte[] ciphertextbytes = Base64.decode(ciphertext); byte[] ivBytes = Base64.decode(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME); cipher.init(Cipher.DECRYPT_MODE, secKey, new IvParameterSpec(ivBytes)); return cipher.doFinal(ciphertextbytes); } public byte[] decrypt(Key secKey, String ciphertext, String iv, String hmac) throws GeneralSecurityException { // checkMac(secKey, ciphertext, hmac); byte[] ciphertextbytes = Base64.decode(ciphertext); byte[] ivBytes = Base64.decode(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME); cipher.init(Cipher.DECRYPT_MODE, secKey, new IvParameterSpec(ivBytes)); return cipher.doFinal(ciphertextbytes); } private byte[] encrypt(Key secKey, byte[] plaintext, String iv) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME); cipher.init(Cipher.ENCRYPT_MODE, secKey, new IvParameterSpec(Base64.decode(iv))); return cipher.doFinal(plaintext); } @SuppressWarnings("unused") private byte[] encrypt(Key secKey, String plaintext, String iv) throws GeneralSecurityException { byte[] plaintextbytes = Base64.decode(plaintext); return encrypt(secKey, plaintextbytes, iv); } protected Key getKeyDecryptionKey(char[] secret, byte[] salt) throws GeneralSecurityException { byte[] keyBytes = derivePKCS5S2(secret, salt); return new SecretKeySpec(keyBytes, "AES"); } public String legalizeUsername(String friendlyUsername) { try { if (!ILLEGAL_USERNAME_PATTERN.matcher(friendlyUsername).find()) return friendlyUsername; MessageDigest digest = MessageDigest.getInstance("SHA1"); digest.update(WeaveUtil.toAsciiBytes(friendlyUsername.toLowerCase())); byte[] baseEncodedBytes = Base32.encode(digest.digest()); return WeaveUtil.toAsciiString(baseEncodedBytes); } catch (GeneralSecurityException e) { throw new Error(e); } } public X509Certificate readCertificate(byte[] certBytes) throws GeneralSecurityException { CertificateFactory certFact = CertificateFactory.getInstance("X.509", PROVIDER_NAME); return (X509Certificate) certFact .generateCertificate(new ByteArrayInputStream(certBytes)); } public RSAPublicKey readCertificatePubKey(String base64EncodedCert) throws GeneralSecurityException { byte[] certBytes = Base64.decode(base64EncodedCert); // X509EncodedKeySpec keySpec = new X509EncodedKeySpec(certBytes); // KeyFactory certFact = KeyFactory.getInstance("RSA", PROVIDER_NAME); // return (RSAPublicKey)certFact.generatePublic(keySpec); return (RSAPublicKey) readCertificate(certBytes); } public byte[] readPrivateKeyToPKCSBytes(char[] encpass, String salt, String iv, String keyData) throws GeneralSecurityException { Key key = getKeyDecryptionKey(encpass, Base64.decode(salt)); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING", PROVIDER_NAME); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(Base64.decode(iv))); return cipher.doFinal(Base64.decode(keyData)); } public Key unwrapSecretKey(RSAPrivateKey privKey, String wrapped) throws GeneralSecurityException { byte[] wrappedBytes = Base64.decode(wrapped); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", PROVIDER_NAME); cipher.init(Cipher.UNWRAP_MODE, privKey); return cipher.unwrap(wrappedBytes, "AES", Cipher.SECRET_KEY); } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveCryptoUtil.java
Java
gpl3
9,892
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; /** * @author Patrick Woodworth */ public class WeaveConstants { private static final String PACKAGE_NAME = WeaveConstants.class .getPackage().getName(); private static final String APP_NAME = "EmergentWeave"; private static final double APP_VERSION = 0.9; private static final String APP_VERSION_STRING = String.format("%1.1f", APP_VERSION); private static final String USER_AGENT_DEFAULT = APP_NAME + "/" + APP_VERSION_STRING; private static final String LOGGER_NAME_DEFAULT = APP_NAME; // maps to // android log // tag private static final String LOGGER_NAME = getProperty("logger_name", LOGGER_NAME_DEFAULT); static final String WEAVE_API_VERSION = "1.0"; static final int UNAUTHORIZED_HTTP_STATUS_CODE = 401; public static final boolean ALLOW_INVALID_CERTS_DEFAULT = true; // todo this // should be // false static final boolean CONNECTION_POOL_ENABLED_DEFAULT = true; public static final String LOGGER_NAME_FULL = getProperty( "logger_name_full", PACKAGE_NAME + "." + LOGGER_NAME); public static final String USER_AGENT = getProperty("user_agent", USER_AGENT_DEFAULT); private static String getFullyQualifiedKey(String key) { return PACKAGE_NAME + "." + key; } private static String getProperty(String key, String def) { return System.getProperty(getFullyQualifiedKey(key), def); } private WeaveConstants() { // no instantiation } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveConstants.java
Java
gpl3
2,110
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.security.GeneralSecurityException; import java.security.Key; import java.util.Date; import org.json.JSONException; import org.json.JSONObject; /** * @author Patrick Woodworth */ public class WeaveBasicObject { public static class WeaveEncryptedObject { private final JSONObject m_nodeObj; public WeaveEncryptedObject(JSONObject nodeObj) { m_nodeObj = nodeObj; } public JSONObject decryptObject(BulkKeyCouplet keyPair) throws GeneralSecurityException, JSONException { return decryptObject(keyPair.cipherKey, keyPair.hmacKey); } public JSONObject decryptObject(Key key, Key hmacKey) throws GeneralSecurityException, JSONException { byte[] bytes = WeaveCryptoUtil.getInstance().decrypt(key, hmacKey, getCiphertext(), getIv(), getHmac()); return new JSONObject(WeaveUtil.toUtf8String(bytes)); } public String getCiphertext() throws JSONException { return m_nodeObj.getString("ciphertext"); } public String getHmac() throws JSONException { return m_nodeObj.getString("hmac"); } public String getIv() throws JSONException { return m_nodeObj.getString("IV"); } } private URI m_uri = null; private final URI m_queryUri; private final JSONObject m_nodeObj; public WeaveBasicObject(URI queryUri, JSONObject nodeObj) { m_queryUri = queryUri; m_nodeObj = nodeObj; } public JSONObject getEncryptedPayload(Key bulkKey, Key hmacKey) throws JSONException, IOException, GeneralSecurityException, WeaveException { WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); return weo.decryptObject(bulkKey, hmacKey); } public JSONObject getEncryptedPayload(UserWeave weave, char[] secret) throws JSONException, IOException, GeneralSecurityException, WeaveException { WeaveEncryptedObject weo = new WeaveEncryptedObject(getPayload()); byte[] syncKey = Base32.decodeModified(new String(secret)); // todo // don't // convert // to string BulkKeyCouplet bulkKeyPair = weave.getBulkKeyPair(syncKey); return weo.decryptObject(bulkKeyPair); } public String getId() throws JSONException { return m_nodeObj.getString("id"); } public String getModified() throws JSONException { return m_nodeObj.getString("modified"); } public Date getModifiedDate() throws JSONException { return WeaveUtil.toModifiedTimeDate(getModified()); } public JSONObject getPayload() throws JSONException { return new JSONObject(m_nodeObj.getString("payload")); } public String getSortIndex() throws JSONException { return m_nodeObj.getString("sortindex"); } public URI getUri() throws JSONException { if (m_uri == null) { try { String baseUriStr = m_queryUri.toASCIIString(); String queryPart = m_queryUri.getRawQuery(); if (queryPart != null) baseUriStr = baseUriStr.substring(0, baseUriStr.indexOf(queryPart) - 1); if (!baseUriStr.endsWith("/")) baseUriStr += "/"; String nodeUriStr = baseUriStr + new URI(null, null, getId(), null).toASCIIString(); m_uri = new URI(nodeUriStr); } catch (URISyntaxException e) { throw new JSONException(e.getMessage()); } } return m_uri; } public JSONObject toJSONObject() { return m_nodeObj; } public String toJSONObjectString() throws JSONException { return toJSONObject().toString(0); } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveBasicObject.java
Java
gpl3
4,094
/* (PD) 2001 The Bitzi Corporation * Please see http://bitzi.com/publicdomain for more info. * * As modified by Patrick Woodworth: * * Copyright 2011 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; /** * Base32 - encodes and decodes RFC3548 Base32 (see * http://www.faqs.org/rfcs/rfc3548.html ) * * @author Robert Kaye * @author Gordon Mohr */ public class Base32 { private static final String base32Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; private static final int[] base32Lookup = { 0xFF, 0xFF, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, // '0', '1', '2', '3', '4', '5', '6', '7' 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // '8', '9', ':', // ';', '<', '=', // '>', '?' 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '@', 'A', 'B', // 'C', 'D', 'E', // 'F', 'G' 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'H', 'I', 'J', // 'K', 'L', 'M', // 'N', 'O' 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'P', 'Q', 'R', // 'S', 'T', 'U', // 'V', 'W' 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, // 'X', 'Y', 'Z', // '[', '\', ']', // '^', '_' 0xFF, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, // '`', 'a', 'b', // 'c', 'd', 'e', // 'f', 'g' 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, // 'h', 'i', 'j', // 'k', 'l', 'm', // 'n', 'o' 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, // 'p', 'q', 'r', // 's', 't', 'u', // 'v', 'w' 0x17, 0x18, 0x19, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF // 'x', 'y', 'z', // '{', '|', '}', // '~', 'DEL' }; /** * Decodes the given Base32 String to a raw byte array. * * @param base32 * @return Decoded <code>base32</code> String as a raw byte array. */ static public byte[] decode(final String base32) { int i, index, lookup, offset, digit; byte[] bytes = new byte[base32.length() * 5 / 8]; for (i = 0, index = 0, offset = 0; i < base32.length(); i++) { lookup = base32.charAt(i) - '0'; /* Skip chars outside the lookup table */ if (lookup < 0 || lookup >= base32Lookup.length) { continue; } digit = base32Lookup[lookup]; /* If this digit is not in the table, ignore it */ if (digit == 0xFF) { continue; } if (index <= 3) { index = (index + 5) % 8; if (index == 0) { bytes[offset] |= digit; offset++; if (offset >= bytes.length) break; } else { bytes[offset] |= digit << (8 - index); } } else { index = (index + 5) % 8; bytes[offset] |= (digit >>> index); offset++; if (offset >= bytes.length) { break; } bytes[offset] |= digit << (8 - index); } } return bytes; } public static byte[] decodeModified(String data) { return decode(data.replace('8', 'L').replace('9', 'O')); } public static byte[] encode(byte[] data) { return WeaveUtil.toAsciiBytes(encodeOriginal(data).toLowerCase()); } /** * Encodes byte array to Base32 String. * * @param bytes * Bytes to encode. * @return Encoded byte array <code>bytes</code> as a String. * */ static public String encodeOriginal(final byte[] bytes) { int i = 0, index = 0, digit = 0; int currByte, nextByte; StringBuffer base32 = new StringBuffer((bytes.length + 7) * 8 / 5); while (i < bytes.length) { currByte = (bytes[i] >= 0) ? bytes[i] : (bytes[i] + 256); // unsign /* Is the current digit going to span a byte boundary? */ if (index > 3) { if ((i + 1) < bytes.length) { nextByte = (bytes[i + 1] >= 0) ? bytes[i + 1] : (bytes[i + 1] + 256); } else { nextByte = 0; } digit = currByte & (0xFF >> index); index = (index + 5) % 8; digit <<= index; digit |= nextByte >> (8 - index); i++; } else { digit = (currByte >> (8 - (index + 5))) & 0x1F; index = (index + 5) % 8; if (index == 0) i++; } base32.append(base32Chars.charAt(digit)); } return base32.toString(); } /** * For testing, take a command-line argument in Base32, decode, print in * hex, encode, print * * @param args */ static public void main(String[] args) { if (args.length == 0) { System.out.println("Supply a Base32-encoded argument."); return; } System.out.println(" Original: " + args[0]); byte[] decoded = Base32.decode(args[0]); System.out.print(" Hex: "); for (int i = 0; i < decoded.length; i++) { int b = decoded[i]; if (b < 0) { b += 256; } System.out.print((Integer.toHexString(b + 256)).substring(1)); } System.out.println(); System.out.println("Reencoded: " + Base32.encode(decoded)); } }
zyh3290-proxy
src/org/emergent/android/weave/client/Base32.java
Java
gpl3
5,375
package org.emergent.android.weave.client; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; class Hex { private static final HexEncoder encoder = new HexEncoder(); /** * decode the Hex encoded input data. It is assumed the input data is valid. * * @return a byte array representing the decoded data. */ public static byte[] decode(byte[] data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, 0, data.length, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding Hex string: " + e); } return bOut.toByteArray(); } /** * decode the Hex encoded String data - whitespace will be ignored. * * @return a byte array representing the decoded data. */ public static byte[] decode(String data) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.decode(data, bOut); } catch (IOException e) { throw new RuntimeException("exception decoding Hex string: " + e); } return bOut.toByteArray(); } /** * decode the Hex encoded String data writing it to the given output stream, * whitespace characters will be ignored. * * @return the number of bytes produced. */ public static int decode(String data, OutputStream out) throws IOException { return encoder.decode(data, out); } /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] encode(byte[] data) { return encode(data, 0, data.length); } /** * encode the input data producing a Hex encoded byte array. * * @return a byte array containing the Hex encoded data. */ public static byte[] encode(byte[] data, int off, int length) { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); try { encoder.encode(data, off, length, bOut); } catch (IOException e) { throw new RuntimeException("exception encoding Hex string: " + e); } return bOut.toByteArray(); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode(byte[] data, int off, int length, OutputStream out) throws IOException { return encoder.encode(data, off, length, out); } /** * Hex encode the byte data writing it to the given output stream. * * @return the number of bytes produced. */ public static int encode(byte[] data, OutputStream out) throws IOException { return encoder.encode(data, 0, data.length, out); } }
zyh3290-proxy
src/org/emergent/android/weave/client/Hex.java
Java
gpl3
2,586
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import java.security.Key; /** * @author Patrick Woodworth */ class BulkKeyCouplet { public final Key cipherKey; public final Key hmacKey; public BulkKeyCouplet(Key cipherKey, Key hmacKey) { this.cipherKey = cipherKey; this.hmacKey = hmacKey; } }
zyh3290-proxy
src/org/emergent/android/weave/client/BulkKeyCouplet.java
Java
gpl3
899
/* * Copyright 2010 Patrick Woodworth * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.emergent.android.weave.client; import org.apache.http.client.HttpResponseException; /** * @author Patrick Woodworth */ @SuppressWarnings("serial") public class WeaveException extends Exception { public enum ExceptionType { GENERAL, BACKOFF, ; } public static boolean isAuthFailure(HttpResponseException e) { int statusCode = e.getStatusCode(); if (WeaveConstants.UNAUTHORIZED_HTTP_STATUS_CODE == statusCode) return true; return false; } private final WeaveException.ExceptionType m_type; public WeaveException() { this(WeaveException.ExceptionType.GENERAL); } public WeaveException(String message) { this(WeaveException.ExceptionType.GENERAL, message); } public WeaveException(String message, Throwable cause) { this(WeaveException.ExceptionType.GENERAL, message, cause); } public WeaveException(Throwable cause) { this(WeaveException.ExceptionType.GENERAL, cause); } public WeaveException(WeaveException.ExceptionType type) { m_type = type; } public WeaveException(WeaveException.ExceptionType type, String message) { super(message); m_type = type; } public WeaveException(WeaveException.ExceptionType type, String message, Throwable cause) { super(message, cause); m_type = type; } public WeaveException(WeaveException.ExceptionType type, Throwable cause) { super(cause); m_type = type; } public WeaveException.ExceptionType getType() { return m_type; } }
zyh3290-proxy
src/org/emergent/android/weave/client/WeaveException.java
Java
gpl3
2,047
/* * Copyright (C) 2010 Cyril Mottier (http://www.cyrilmottier.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.greendroid; import java.util.ArrayList; import java.util.List; import org.gaeproxy.R; import android.content.Context; import android.graphics.Color; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.PopupWindow; /** * Abstraction of a {@link QuickAction} wrapper. A QuickActionWidget is * displayed on top of the user interface (it overlaps all UI elements but the * notification bar). Clients may listen to user actions using a * {@link OnQuickActionClickListener} . * * @author Benjamin Fellous * @author Cyril Mottier */ public abstract class QuickActionWidget extends PopupWindow { /** * Interface that may be used to listen to clicks on quick actions. * * @author Benjamin Fellous * @author Cyril Mottier */ public static interface OnQuickActionClickListener { /** * Clients may implement this method to be notified of a click on a * particular quick action. * * @param position * Position of the quick action that have been clicked. */ void onQuickActionClicked(QuickActionWidget widget, int position); } private static final int MEASURE_AND_LAYOUT_DONE = 1 << 1; private final int[] mLocation = new int[2]; private final Rect mRect = new Rect(); private int mPrivateFlags; private Context mContext; private boolean mDismissOnClick; private int mArrowOffsetY; private int mPopupY; private boolean mIsOnTop; private int mScreenHeight; private int mScreenWidth; private boolean mIsDirty; private OnQuickActionClickListener mOnQuickActionClickListener; private ArrayList<QuickAction> mQuickActions = new ArrayList<QuickAction>(); /** * Creates a new QuickActionWidget for the given context. * * @param context * The context in which the QuickActionWidget is running in */ public QuickActionWidget(Context context) { super(context); mContext = context; initializeDefault(); setFocusable(true); setTouchable(true); setOutsideTouchable(true); setWidth(LayoutParams.WRAP_CONTENT); setHeight(LayoutParams.WRAP_CONTENT); final WindowManager windowManager = (WindowManager) mContext .getSystemService(Context.WINDOW_SERVICE); mScreenWidth = windowManager.getDefaultDisplay().getWidth(); mScreenHeight = windowManager.getDefaultDisplay().getHeight(); } /** * Add a new QuickAction to this {@link QuickActionWidget}. Adding a new * {@link QuickAction} while the {@link QuickActionWidget} is currently * being shown does nothing. The new {@link QuickAction} will be displayed * on the next call to {@link #show(View)}. * * @param action * The new {@link QuickAction} to add */ public void addQuickAction(QuickAction action) { if (action != null) { mQuickActions.add(action); mIsDirty = true; } } /** * Removes all {@link QuickAction} from this {@link QuickActionWidget}. */ public void clearAllQuickActions() { if (!mQuickActions.isEmpty()) { mQuickActions.clear(); mIsDirty = true; } } protected void clearQuickActions() { if (!mQuickActions.isEmpty()) { onClearQuickActions(); } } /** * Returns the arrow offset for the Y axis. * * @see {@link #setArrowOffsetY(int)} * @return The arrow offset. */ public int getArrowOffsetY() { return mArrowOffsetY; } protected Context getContext() { return mContext; } public boolean getDismissOnClick() { return mDismissOnClick; } protected OnQuickActionClickListener getOnQuickActionClickListener() { return mOnQuickActionClickListener; } /** * Returns the height of the screen. * * @return The height of the screen */ protected int getScreenHeight() { return mScreenHeight; } /** * Returns the width of the screen. * * @return The width of the screen */ protected int getScreenWidth() { return mScreenWidth; } private void initializeDefault() { mDismissOnClick = true; mArrowOffsetY = mContext.getResources().getDimensionPixelSize( R.dimen.gd_arrow_offset); } protected void onClearQuickActions() { } protected abstract void onMeasureAndLayout(Rect anchorRect, View contentView); protected abstract void populateQuickActions(List<QuickAction> quickActions); private void prepareAnimationStyle() { final int screenWidth = mScreenWidth; final boolean onTop = mIsOnTop; final int arrowPointX = mRect.centerX(); if (arrowPointX <= screenWidth / 4) { setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Left : R.style.GreenDroid_Animation_PopDown_Left); } else if (arrowPointX >= 3 * screenWidth / 4) { setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Right : R.style.GreenDroid_Animation_PopDown_Right); } else { setAnimationStyle(onTop ? R.style.GreenDroid_Animation_PopUp_Center : R.style.GreenDroid_Animation_PopDown_Center); } } /** * Sets the arrow offset to a new value. Setting an arrow offset may be * particular useful to warn which view the QuickActionWidget is related to. * By setting a positive offset, the arrow will overlap the view given by * {@link #show(View)}. The default value is 5dp. * * @param offsetY * The offset for the Y axis */ public void setArrowOffsetY(int offsetY) { mArrowOffsetY = offsetY; } /** * Equivalent to {@link PopupWindow#setContentView(View)} but with a layout * identifier. * * @param layoutId * The layout identifier of the view to use. */ public void setContentView(int layoutId) { setContentView(LayoutInflater.from(mContext).inflate(layoutId, null)); } /** * By default, a {@link QuickActionWidget} is dismissed once the user * clicked on a {@link QuickAction}. This behavior can be changed using this * method. * * @param dismissOnClick * True if you want the {@link QuickActionWidget} to be dismissed * on click else false. */ public void setDismissOnClick(boolean dismissOnClick) { mDismissOnClick = dismissOnClick; } /** * @param listener */ public void setOnQuickActionClickListener( OnQuickActionClickListener listener) { mOnQuickActionClickListener = listener; } protected void setWidgetSpecs(int popupY, boolean isOnTop) { mPopupY = popupY; mIsOnTop = isOnTop; mPrivateFlags |= MEASURE_AND_LAYOUT_DONE; } /** * Call that method to display the {@link QuickActionWidget} anchored to the * given view. * * @param anchor * The view the {@link QuickActionWidget} will be anchored to. */ public void show(View anchor) { final View contentView = getContentView(); if (contentView == null) { throw new IllegalStateException( "You need to set the content view using the setContentView method"); } // Replaces the background of the popup with a cleared background setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); final int[] loc = mLocation; anchor.getLocationOnScreen(loc); mRect.set(loc[0], loc[1], loc[0] + anchor.getWidth(), loc[1] + anchor.getHeight()); if (mIsDirty) { clearQuickActions(); populateQuickActions(mQuickActions); } onMeasureAndLayout(mRect, contentView); if ((mPrivateFlags & MEASURE_AND_LAYOUT_DONE) != MEASURE_AND_LAYOUT_DONE) { throw new IllegalStateException( "onMeasureAndLayout() did not set the widget specification by calling" + " setWidgetSpecs()"); } showArrow(); prepareAnimationStyle(); showAtLocation(anchor, Gravity.NO_GRAVITY, 0, mPopupY); } private void showArrow() { final View contentView = getContentView(); final int arrowId = mIsOnTop ? R.id.gdi_arrow_down : R.id.gdi_arrow_up; final View arrow = contentView.findViewById(arrowId); final View arrowUp = contentView.findViewById(R.id.gdi_arrow_up); final View arrowDown = contentView.findViewById(R.id.gdi_arrow_down); if (arrowId == R.id.gdi_arrow_up) { arrowUp.setVisibility(View.VISIBLE); arrowDown.setVisibility(View.INVISIBLE); } else if (arrowId == R.id.gdi_arrow_down) { arrowUp.setVisibility(View.INVISIBLE); arrowDown.setVisibility(View.VISIBLE); } ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) arrow .getLayoutParams(); param.leftMargin = mRect.centerX() - (arrow.getMeasuredWidth()) / 2; } }
zyh3290-proxy
src/org/greendroid/QuickActionWidget.java
Java
gpl3
9,448
/* * Copyright (C) 2010 Cyril Mottier (http://www.cyrilmottier.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.greendroid; import java.util.List; import org.gaeproxy.R; import android.content.Context; import android.graphics.Rect; import android.view.LayoutInflater; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.BaseAdapter; import android.widget.GridView; import android.widget.TextView; /** * A {@link QuickActionGrid} is an implementation of a {@link QuickActionWidget} * that displays {@link QuickAction}s in a grid manner. This is usually used to * create a shortcut to jump between different type of information on screen. * * @author Benjamin Fellous * @author Cyril Mottier */ public class QuickActionGrid extends QuickActionWidget { private GridView mGridView; private OnItemClickListener mInternalItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { getOnQuickActionClickListener().onQuickActionClicked( QuickActionGrid.this, position); if (getDismissOnClick()) { dismiss(); } } }; public QuickActionGrid(Context context) { super(context); setContentView(R.layout.gd_quick_action_grid); final View v = getContentView(); mGridView = (GridView) v.findViewById(R.id.gdi_grid); } @Override protected void onMeasureAndLayout(Rect anchorRect, View contentView) { contentView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); contentView.measure(MeasureSpec.makeMeasureSpec(getScreenWidth(), MeasureSpec.EXACTLY), LayoutParams.WRAP_CONTENT); int rootHeight = contentView.getMeasuredHeight(); int offsetY = getArrowOffsetY(); int dyTop = anchorRect.top; int dyBottom = getScreenHeight() - anchorRect.bottom; boolean onTop = (dyTop > dyBottom); int popupY = (onTop) ? anchorRect.top - rootHeight + offsetY : anchorRect.bottom - offsetY; setWidgetSpecs(popupY, onTop); } @Override protected void populateQuickActions(final List<QuickAction> quickActions) { mGridView.setAdapter(new BaseAdapter() { @Override public int getCount() { return quickActions.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View view, ViewGroup parent) { TextView textView = (TextView) view; if (view == null) { final LayoutInflater inflater = LayoutInflater .from(getContext()); textView = (TextView) inflater.inflate( R.layout.gd_quick_action_grid_item, mGridView, false); } QuickAction quickAction = quickActions.get(position); textView.setText(quickAction.mTitle); textView.setCompoundDrawablesWithIntrinsicBounds(null, quickAction.mDrawable, null, null); return textView; } }); mGridView.setOnItemClickListener(mInternalItemClickListener); } }
zyh3290-proxy
src/org/greendroid/QuickActionGrid.java
Java
gpl3
3,894
/* * Copyright (C) 2010 Cyril Mottier (http://www.cyrilmottier.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.greendroid; import java.lang.ref.WeakReference; import android.content.Context; import android.graphics.drawable.Drawable; import android.view.View; /** * A QuickAction implements an item in a {@link QuickActionWidget}. A * QuickAction represents a single action and may contain a text and an icon. * * @author Benjamin Fellous * @author Cyril Mottier */ public class QuickAction { public Drawable mDrawable; public CharSequence mTitle; /* package */WeakReference<View> mView; public QuickAction(Context ctx, Drawable d, int titleId) { mDrawable = d; mTitle = ctx.getResources().getString(titleId); } public QuickAction(Context ctx, int drawableId, CharSequence title) { mDrawable = ctx.getResources().getDrawable(drawableId); mTitle = title; } public QuickAction(Context ctx, int drawableId, int titleId) { mDrawable = ctx.getResources().getDrawable(drawableId); mTitle = ctx.getResources().getString(titleId); } public QuickAction(Drawable d, CharSequence title) { mDrawable = d; mTitle = title; } }
zyh3290-proxy
src/org/greendroid/QuickAction.java
Java
gpl3
1,741
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.adapters; import org.gaeproxy.R; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.provider.Browser; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; /** * Cursor adapter for bookmarks. */ public class BookmarksCursorAdapter extends SimpleCursorAdapter { private int mFaviconSize; /** * Constructor. * * @param context * The context. * @param layout * The layout. * @param c * The Cursor. * @param from * Input array. * @param to * Output array. */ public BookmarksCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int faviconSize) { super(context, layout, c, from, to); mFaviconSize = faviconSize; } @Override public View getView(int position, View convertView, ViewGroup parent) { View superView = super.getView(position, convertView, parent); ImageView thumbnailView = (ImageView) superView .findViewById(R.id.BookmarkRow_Thumbnail); byte[] favicon = getCursor().getBlob( getCursor().getColumnIndex(Browser.BookmarkColumns.FAVICON)); if (favicon != null) { BitmapDrawable icon = new BitmapDrawable( BitmapFactory.decodeByteArray(favicon, 0, favicon.length)); Bitmap bm = Bitmap.createBitmap(mFaviconSize, mFaviconSize, Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); icon.setBounds(0, 0, mFaviconSize, mFaviconSize); icon.draw(canvas); thumbnailView.setImageBitmap(bm); } else { thumbnailView.setImageResource(R.drawable.fav_icn_unknown); } return superView; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/adapters/BookmarksCursorAdapter.java
Java
gpl3
2,401
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.adapters; import org.gaeproxy.R; import org.gaeproxy.zirco.model.items.HistoryItem; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.BitmapDrawable; import android.provider.BaseColumns; import android.provider.Browser; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.webkit.DateSorter; import android.widget.AbsListView; import android.widget.BaseExpandableListAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; /** * Custom adapter for displaying history, splitted in bins. Adapted from: * https:/ * /github.com/CyanogenMod/android_packages_apps_Browser/blob/gingerbread/ * src/com/android/browser/BrowserHistoryPage.java * http://grepcode.com/file/repository * .grepcode.com/java/ext/com.google.android/android * -apps/2.2_r1.1/com/android/browser * /DateSortedExpandableListAdapter.java/?v=source */ public class HistoryExpandableListAdapter extends BaseExpandableListAdapter { private LayoutInflater mInflater = null; private int[] mItemMap; private int mNumberOfBins; private int mIdIndex; private DateSorter mDateSorter; private Context mContext; private Cursor mCursor; private int mDateIndex; private int mFaviconSize; /** * Constructor. * * @param context * The current context. * @param cursor * The data cursor. * @param dateIndex * The date index ? */ public HistoryExpandableListAdapter(Context context, Cursor cursor, int dateIndex, int faviconSize) { mContext = context; mCursor = cursor; mDateIndex = dateIndex; mFaviconSize = faviconSize; mDateSorter = new DateSorter(mContext); mIdIndex = cursor.getColumnIndexOrThrow(BaseColumns._ID); mInflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); buildMap(); } /** * Split the data in the cursor into several "bins": today, yesterday, last * 7 days, last month, older. */ private void buildMap() { int[] array = new int[DateSorter.DAY_COUNT]; // Zero out the array. for (int j = 0; j < DateSorter.DAY_COUNT; j++) { array[j] = 0; } mNumberOfBins = 0; int dateIndex = -1; if (mCursor.moveToFirst() && mCursor.getCount() > 0) { while (!mCursor.isAfterLast()) { long date = getLong(mDateIndex); int index = mDateSorter.getIndex(date); if (index > dateIndex) { mNumberOfBins++; if (index == DateSorter.DAY_COUNT - 1) { // We are already in the last bin, so it will // include all the remaining items array[index] = mCursor.getCount() - mCursor.getPosition(); break; } dateIndex = index; } array[dateIndex]++; mCursor.moveToNext(); } } mItemMap = array; } @Override public Object getChild(int groupPosition, int childPosition) { moveCursorToChildPosition(groupPosition, childPosition); String title = mCursor .getString(Browser.HISTORY_PROJECTION_TITLE_INDEX); if (title.length() > 11) title = title.substring(0, 10) + "..."; return new HistoryItem( mCursor.getLong(Browser.HISTORY_PROJECTION_ID_INDEX), title, mCursor.getString(Browser.HISTORY_PROJECTION_URL_INDEX), mCursor.getBlob(Browser.HISTORY_PROJECTION_FAVICON_INDEX)); } @Override public long getChildId(int groupPosition, int childPosition) { if (moveCursorToChildPosition(groupPosition, childPosition)) { return getLong(mIdIndex); } return 0; } @Override public int getChildrenCount(int groupPosition) { return mItemMap[groupPositionToBin(groupPosition)]; } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View view = getCustomChildView(); TextView titleView = (TextView) view .findViewById(R.id.HistoryRow_Title); HistoryItem item = (HistoryItem) getChild(groupPosition, childPosition); titleView.setText(item.getTitle()); TextView urlView = (TextView) view.findViewById(R.id.HistoryRow_Url); urlView.setText(item.getUrl()); ImageView faviconView = (ImageView) view .findViewById(R.id.HistoryRow_Thumbnail); Bitmap favicon = item.getFavicon(); if (favicon != null) { BitmapDrawable icon = new BitmapDrawable(favicon); Bitmap bm = Bitmap.createBitmap(mFaviconSize, mFaviconSize, Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); icon.setBounds(0, 0, mFaviconSize, mFaviconSize); icon.draw(canvas); faviconView.setImageBitmap(bm); // faviconView.setImageBitmap(item.getFavicon()); } else { faviconView.setImageResource(R.drawable.fav_icn_unknown); } return view; } /** * Create a new child view. * * @return The created view. */ private View getCustomChildView() { LinearLayout view = (LinearLayout) mInflater.inflate( R.layout.history_row, null, false); return view; } /** * Create a new view. * * @return The created view. */ private TextView getGenericView() { // Layout parameters for the ExpandableListView AbsListView.LayoutParams lp = new AbsListView.LayoutParams( ViewGroup.LayoutParams.FILL_PARENT, (int) (45 * mContext .getResources().getDisplayMetrics().density)); TextView textView = new TextView(mContext); textView.setLayoutParams(lp); // Center the text vertically textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT); // Set the text starting position textView.setPadding((int) (35 * mContext.getResources() .getDisplayMetrics().density), 0, 0, 0); return textView; } @Override public Object getGroup(int groupPosition) { int binIndex = groupPositionToBin(groupPosition); switch (binIndex) { case 0: return mContext.getResources().getString( R.string.HistoryListActivity_Today); case 1: return mContext.getResources().getString( R.string.HistoryListActivity_Yesterday); case 2: return mContext.getResources().getString( R.string.HistoryListActivity_LastSevenDays); case 3: return mContext.getResources().getString( R.string.HistoryListActivity_LastMonth); default: return mContext.getResources().getString( R.string.HistoryListActivity_Older); } } @Override public int getGroupCount() { return mNumberOfBins; } @Override public long getGroupId(int groupPosition) { return groupPosition; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { TextView textView = getGenericView(); textView.setText(getGroup(groupPosition).toString()); return textView; } /** * Get a long-typed data from mCursor. * * @param cursorIndex * The column index. * @return The long data. */ private long getLong(int cursorIndex) { return mCursor.getLong(cursorIndex); } /** * Translates from a group position in the ExpandableList to a bin. This is * necessary because some groups have no history items, so we do not include * those in the ExpandableList. * * @param groupPosition * Position in the ExpandableList's set of groups * @return The corresponding bin that holds that group. */ private int groupPositionToBin(int groupPosition) { if (groupPosition < 0 || groupPosition >= DateSorter.DAY_COUNT) { throw new AssertionError("group position out of range"); } if (DateSorter.DAY_COUNT == mNumberOfBins || 0 == mNumberOfBins) { // In the first case, we have exactly the same number of bins // as our maximum possible, so there is no need to do a // conversion // The second statement is in case this method gets called when // the array is empty, in which case the provided groupPosition // will do fine. return groupPosition; } int arrayPosition = -1; while (groupPosition > -1) { arrayPosition++; if (mItemMap[arrayPosition] != 0) { groupPosition--; } } return arrayPosition; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } /** * Move the cursor to the record corresponding to the given group position * and child position. * * @param groupPosition * The group position. * @param childPosition * The child position. * @return True if the move has succeeded. */ private boolean moveCursorToChildPosition(int groupPosition, int childPosition) { if (mCursor.isClosed()) { return false; } groupPosition = groupPositionToBin(groupPosition); int index = childPosition; for (int i = 0; i < groupPosition; i++) { index += mItemMap[i]; } return mCursor.moveToPosition(index); } /** * Determine which group an item belongs to. * * @param childId * ID of the child view in question. * @return int Group position of the containing group. */ /* * private int groupFromChildId(long childId) { int group = -1; for * (mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) { * if (getLong(mIdIndex) == childId) { int bin = * mDateSorter.getIndex(getLong(mDateIndex)); // bin is the same as the * group if the number of bins is the // same as DateSorter if * (DateSorter.DAY_COUNT == mNumberOfBins) return bin; // There are some * empty bins. Find the corresponding group. group = 0; for (int i = 0; i < * bin; i++) { if (mItemMap[i] != 0) group++; } break; } } return group; } * * private boolean moveCursorToPackedChildPosition(long packedPosition) { if * (ExpandableListView.getPackedPositionType(packedPosition) != * ExpandableListView.PACKED_POSITION_TYPE_CHILD) { return false; } int * groupPosition = ExpandableListView.getPackedPositionGroup( * packedPosition); int childPosition = * ExpandableListView.getPackedPositionChild( packedPosition); return * moveCursorToChildPosition(groupPosition, childPosition); } */ }
zyh3290-proxy
src/org/gaeproxy/zirco/model/adapters/HistoryExpandableListAdapter.java
Java
gpl3
10,635
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.adapters; import org.gaeproxy.R; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; /** * Adapter for suggestions. */ public class UrlSuggestionCursorAdapter extends SimpleCursorAdapter { public static final String URL_SUGGESTION_ID = "_id"; public static final String URL_SUGGESTION_TITLE = "URL_SUGGESTION_TITLE"; public static final String URL_SUGGESTION_URL = "URL_SUGGESTION_URL"; public static final String URL_SUGGESTION_TYPE = "URL_SUGGESTION_TYPE"; /** * Constructor. * * @param context * The context. * @param layout * The layout. * @param c * The Cursor. * @param from * Input array. * @param to * Output array. */ public UrlSuggestionCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); } @Override public View getView(int position, View convertView, ViewGroup parent) { View superView = super.getView(position, convertView, parent); ImageView iconView = (ImageView) superView .findViewById(R.id.AutocompleteImageView); int resultType; try { resultType = Integer.parseInt(getCursor().getString( getCursor().getColumnIndex(URL_SUGGESTION_TYPE))); } catch (Exception e) { resultType = 0; } switch (resultType) { case 1: iconView.setImageResource(R.drawable.ic_tab_history_unselected); break; case 2: iconView.setImageResource(R.drawable.ic_tab_bookmarks_unselected); break; case 3: iconView.setImageResource(R.drawable.ic_tab_weave_unselected); break; default: break; } return superView; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/adapters/UrlSuggestionCursorAdapter.java
Java
gpl3
2,353
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.adapters; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.gaeproxy.R; import org.gaeproxy.zirco.model.items.DownloadItem; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; /** * The adapter for the download UI list. */ public class DownloadListAdapter extends BaseAdapter { private Context mContext; private List<DownloadItem> mDownloads; private Map<DownloadItem, TextView> mTitleMap; private Map<DownloadItem, ProgressBar> mBarMap; private Map<DownloadItem, ImageButton> mButtonMap; /** * Constructor. * * @param context * The current context. * @param downloads * The download list. */ public DownloadListAdapter(Context context, List<DownloadItem> downloads) { mContext = context; mDownloads = downloads; mTitleMap = new Hashtable<DownloadItem, TextView>(); mBarMap = new Hashtable<DownloadItem, ProgressBar>(); mButtonMap = new Hashtable<DownloadItem, ImageButton>(); } /** * Get a map of download item related to the UI progress bar component. * * @return A Map<DownloadItem, ProgressBar>. */ public Map<DownloadItem, ProgressBar> getBarMap() { return mBarMap; } /** * Get a map of download item related to the UI cancel button component. * * @return A Map<DownloadItem, ImageButton>. */ public Map<DownloadItem, ImageButton> getButtonMap() { return mButtonMap; } @Override public int getCount() { return mDownloads.size(); } @Override public Object getItem(int position) { return mDownloads.get(position); } @Override public long getItemId(int position) { return position; } /** * Get a map of download item related to the UI text component representing * the download title. * * @return A Map<DownloadItem, TextView>. */ public Map<DownloadItem, TextView> getTitleMap() { return mTitleMap; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) mContext .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.download_row, null); } final DownloadItem item = mDownloads.get(position); final ProgressBar progressBar = (ProgressBar) convertView .findViewById(R.id.DownloadRow_ProgressBar); final TextView fileNameView = (TextView) convertView .findViewById(R.id.DownloadRow_FileName); TextView urlView = (TextView) convertView .findViewById(R.id.DownloadRow_Url); final ImageButton stopButton = (ImageButton) convertView .findViewById(R.id.DownloadRow_StopBtn); progressBar.setIndeterminate(false); progressBar.setMax(100); progressBar.setProgress(item.getProgress()); if (item.isAborted()) { fileNameView.setText(String.format(mContext.getResources() .getString(R.string.DownloadListActivity_Aborted), item .getFileName())); stopButton.setEnabled(false); } else if (item.isFinished()) { fileNameView.setText(String.format(mContext.getResources() .getString(R.string.DownloadListActivity_Finished), item .getFileName())); stopButton.setEnabled(false); } else { fileNameView.setText(item.getFileName()); } urlView.setText(item.getUrl()); stopButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { item.abortDownload(); stopButton.setEnabled(false); fileNameView.setText(String.format(mContext.getResources() .getString(R.string.DownloadListActivity_Aborted), item .getFileName())); progressBar.setProgress(progressBar.getMax()); } }); mTitleMap.put(item, fileNameView); mBarMap.put(item, progressBar); mButtonMap.put(item, stopButton); return convertView; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/adapters/DownloadListAdapter.java
Java
gpl3
4,577
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.adapters; import org.gaeproxy.R; import org.gaeproxy.zirco.providers.WeaveColumns; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SimpleCursorAdapter; import android.widget.TextView; public class WeaveBookmarksCursorAdapter extends SimpleCursorAdapter { public WeaveBookmarksCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); } @Override public View getView(int position, View convertView, ViewGroup parent) { View superView = super.getView(position, convertView, parent); Cursor c = getCursor(); boolean isFolder = c.getInt(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_FOLDER)) > 0 ? true : false; ImageView iconView = (ImageView) superView .findViewById(R.id.BookmarkRow_Thumbnail); TextView urlView = (TextView) superView .findViewById(R.id.BookmarkRow_Url); if (isFolder) { urlView.setVisibility(View.GONE); iconView.setImageResource(R.drawable.folder_icon); } else { urlView.setVisibility(View.VISIBLE); iconView.setImageResource(R.drawable.fav_icn_default); } return superView; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/adapters/WeaveBookmarksCursorAdapter.java
Java
gpl3
1,827
package org.gaeproxy.zirco.model.items; /** * Represent a bookmark. */ public class BookmarkItem { private String mTitle; private String mUrl; /** * Constructor. * * @param title * The bookmark title. * @param url * The bookmark url. */ public BookmarkItem(String title, String url) { mTitle = title; mUrl = url; } /** * Get the bookmark title. * * @return The bookmark title. */ public String getTitle() { return mTitle; } /** * Get the bookmark url. * * @return The bookmark url. */ public String getUrl() { return mUrl; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/items/BookmarkItem.java
Java
gpl3
651
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.items; import java.util.Random; import org.gaeproxy.R; import org.gaeproxy.zirco.events.EventConstants; import org.gaeproxy.zirco.events.EventController; import org.gaeproxy.zirco.ui.activities.DownloadsListActivity; import org.gaeproxy.zirco.ui.runnables.DownloadRunnable; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; /** * Represent a download item. */ public class DownloadItem { private Context mContext; private String mUrl; private String mFileName; private int mProgress; private String mErrorMessage; private DownloadRunnable mRunnable; private boolean mIsFinished; private boolean mIsAborted; private NotificationManager mNotificationManager; private Notification mNotification; private int mNotificationId; /** * Constructor. * * @param context * The current context. * @param url * The download url. */ public DownloadItem(Context context, String url) { mContext = context; mUrl = url; mFileName = mUrl.substring(mUrl.lastIndexOf("/") + 1); mProgress = 0; mRunnable = null; mErrorMessage = null; mIsFinished = false; mIsAborted = false; Random r = new Random(); mNotificationId = r.nextInt(); mNotification = null; mNotificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); } /** * Abort the current download. */ public void abortDownload() { if (mRunnable != null) { mRunnable.abort(); } mIsAborted = true; } /** * Create the download notification. */ private void createNotification() { mNotification = new Notification( R.drawable.download_anim, mContext.getString(R.string.DownloadNotification_DownloadStart), System.currentTimeMillis()); Intent notificationIntent = new Intent( mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity( mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification .setLatestEventInfo( mContext.getApplicationContext(), mContext.getString(R.string.DownloadNotification_DownloadInProgress), mFileName, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } /** * Gets the error message for this download. * * @return The error message. */ public String getErrorMessage() { return mErrorMessage; } /** * Gets the filename on disk. * * @return The filename on disk. */ public String getFileName() { return mFileName; } /** * Gets the download progress. * * @return The download progress. */ public int getProgress() { return mProgress; } /** * Gets the download url. * * @return The download url. */ public String getUrl() { return mUrl; } /** * Check if the download is aborted. * * @return True if the download is aborted. */ public boolean isAborted() { return mIsAborted; } /** * Check if the download is finished. * * @return True if the download is finished. */ public boolean isFinished() { return mIsFinished; } /** * Set this item is download finished state. Trigger a finished download * event. */ public void onFinished() { mProgress = 100; mRunnable = null; mIsFinished = true; updateNotificationOnEnd(); EventController.getInstance().fireDownloadEvent( EventConstants.EVT_DOWNLOAD_ON_FINISHED, this); } /** * Set the current progress. Trigger a progress download event. * * @param progress * The current progress. */ public void onProgress(int progress) { mProgress = progress; EventController.getInstance().fireDownloadEvent( EventConstants.EVT_DOWNLOAD_ON_PROGRESS, this); } /** * Trigger a start download event. */ public void onStart() { createNotification(); EventController.getInstance().fireDownloadEvent( EventConstants.EVT_DOWNLOAD_ON_START, this); } /** * Set the current error message for this download. * * @param errorMessage * The error message. */ public void setErrorMessage(String errorMessage) { mErrorMessage = errorMessage; } /** * Start the current download. */ public void startDownload() { if (mRunnable != null) { mRunnable.abort(); } mRunnable = new DownloadRunnable(this); new Thread(mRunnable).start(); } /** * Update the download notification at the end of download. */ private void updateNotificationOnEnd() { if (mNotification != null) { mNotificationManager.cancel(mNotificationId); } String message; if (mIsAborted) { message = mContext .getString(R.string.DownloadNotification_DownloadCanceled); } else { message = mContext .getString(R.string.DownloadNotification_DownloadComplete); } mNotification = new Notification( R.drawable.stat_sys_download, mContext.getString(R.string.DownloadNotification_DownloadComplete), System.currentTimeMillis()); mNotification.flags |= Notification.FLAG_AUTO_CANCEL; Intent notificationIntent = new Intent( mContext.getApplicationContext(), DownloadsListActivity.class); PendingIntent contentIntent = PendingIntent.getActivity( mContext.getApplicationContext(), 0, notificationIntent, 0); mNotification.setLatestEventInfo(mContext.getApplicationContext(), mFileName, message, contentIntent); mNotificationManager.notify(mNotificationId, mNotification); } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/items/DownloadItem.java
Java
gpl3
6,096
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.items; import android.graphics.Bitmap; import android.graphics.BitmapFactory; /** * Represent an history element. */ public class HistoryItem { private long mId; private String mTitle; private String mUrl; private Bitmap mFavicon; /** * Constructor. * * @param id * The element id. * @param title * The title. * @param url * The url. * @param faviconData * The favicon. */ public HistoryItem(long id, String title, String url, byte[] faviconData) { mId = id; mTitle = title; mUrl = url; if (faviconData != null) { mFavicon = BitmapFactory.decodeByteArray(faviconData, 0, faviconData.length); } else { mFavicon = null; } } /** * Get the favicon. * * @return The favicon. */ public Bitmap getFavicon() { return mFavicon; } /** * Get the id. * * @return The id. */ public long getId() { return mId; } /** * Get the title. * * @return The title. */ public String getTitle() { return mTitle; } /** * Get the url. * * @return The url. */ public String getUrl() { return mUrl; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/items/HistoryItem.java
Java
gpl3
1,706
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model.items; /** * Store a suggestion item. */ public class UrlSuggestionItem { private static final float TITLE_COEFFICIENT = 2; private static final float URL_COEFFICIENT = 1; private static final float BOOKMARK_COEFFICIENT = 3; private static final float WEAVE_COEFFICIENT = 1; private static final float HISTORY_COEFFICIENT = 1; private String mPattern; private String mTitle; private String mUrl; private int mType; private float mNote; private boolean mNoteComputed = false; /** * Constructor. * * @param pattern * The parent pattern. * @param title * The item's title. * @param url * The item's url. * @param type * The item's type (1 -> history, 2 -> bookmark). */ public UrlSuggestionItem(String pattern, String title, String url, int type) { mPattern = pattern; mTitle = title; mUrl = url; mType = type; } /** * Compute the note of the current item. The principle is to count the * number of occurence of the pattern in the title and in the url, and to do * a weighted sum. A match in title weight more than a match in url, and a * match in bookmark weight more than a match in history. */ private void computeNote() { String pattern = mPattern.toLowerCase(); // Count the number of match in a string, did not find a cleaner way. int titleMatchCount; String title = mTitle.toLowerCase(); if (title.equals(pattern)) { titleMatchCount = 1; } else { titleMatchCount = title.split(pattern).length - 1; } String url = mUrl.toLowerCase(); int urlMatchCount = url.split("\\Q" + pattern + "\\E").length - 1; mNote = (titleMatchCount * TITLE_COEFFICIENT) + (urlMatchCount * URL_COEFFICIENT); switch (mType) { case 1: mNote = mNote * HISTORY_COEFFICIENT; break; case 2: mNote = mNote * BOOKMARK_COEFFICIENT; break; case 3: mNote = mNote * WEAVE_COEFFICIENT; break; default: break; } } /** * Get the note of this item. Compute it if not already done. * * @return The note. */ public float getNote() { if (!mNoteComputed) { computeNote(); mNoteComputed = true; } return mNote; } /** * Get the item's title. * * @return The title. */ public String getTitle() { return mTitle; } /** * Get the item's type. * * @return The type. */ public int getType() { return mType; } /** * Get the item's url. * * @return The url. */ public String getUrl() { return mUrl; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/items/UrlSuggestionItem.java
Java
gpl3
3,070
package org.gaeproxy.zirco.model.items; public class WeaveBookmarkItem { private String mTitle; private String mUrl; private boolean mIsFolder; private String mWeaveId; public WeaveBookmarkItem(String title, String url, String weaveId, boolean isFolder) { mTitle = title; mUrl = url; mWeaveId = weaveId; mIsFolder = isFolder; } public String getTitle() { return mTitle; } public String getUrl() { return mUrl; } public String getWeaveId() { return mWeaveId; } public boolean isFolder() { return mIsFolder; } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/items/WeaveBookmarkItem.java
Java
gpl3
551
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model; import java.util.Comparator; import org.gaeproxy.zirco.model.items.UrlSuggestionItem; /** * Comparator for UrlSuggestionItem. */ public class UrlSuggestionItemComparator implements Comparator<UrlSuggestionItem> { @Override public int compare(UrlSuggestionItem object1, UrlSuggestionItem object2) { Float value1 = new Float(object1.getNote()); Float value2 = new Float(object2.getNote()); return value2.compareTo(value1); } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/UrlSuggestionItemComparator.java
Java
gpl3
1,012
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.gaeproxy.zirco.ui.runnables.XmlHistoryBookmarksExporter; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.DateUtils; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.MatrixCursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.provider.Browser; import android.util.Log; /** * Implementation of the database adapter. */ public class DbAdapter { /** * DatabaseHelper. */ private static class DatabaseHelper extends SQLiteOpenHelper { private DbAdapter mParent; /** * Constructor. * * @param context * The current context. * @param parent * The DbAdapter parent. */ public DatabaseHelper(Context context, DbAdapter parent) { super(context, DATABASE_NAME, null, DATABASE_VERSION); mParent = parent; } /** * Export bookmarks from the old database. Transform the query result * into a MatrixCursor following the stock bookmarks database, so it can * be exported with the XmlHistoryBookmarksExporter without any change * on it. * * @param db * The database. */ private void exportOldBookmarks(SQLiteDatabase db) { Log.i("DbAdapter", "Start export of old bookmarks."); try { if (ApplicationUtils.checkCardState(mParent.mContext, false)) { Log.i("DbAdapter", "Export of old bookmarks: SDCard checked."); MatrixCursor cursor = null; Cursor c = db.query("BOOKMARKS", new String[] { "_id", "title", "url", "creation_date", "count" }, null, null, null, null, null); if (c != null) { if (c.moveToFirst()) { cursor = new MatrixCursor(new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.VISITS, Browser.BookmarkColumns.DATE, Browser.BookmarkColumns.CREATED, Browser.BookmarkColumns.BOOKMARK }); int titleColumn = c.getColumnIndex("title"); int urlColumn = c.getColumnIndex("url"); int creationDateColumn = c .getColumnIndex("creation_date"); int countColumn = c.getColumnIndex("count"); while (!c.isAfterLast()) { Date date = DateUtils.convertFromDatabase( mParent.mContext, c.getString(creationDateColumn)); Object[] data = new Object[6]; data[0] = c.getString(titleColumn); data[1] = c.getString(urlColumn); data[2] = c.getInt(countColumn); data[3] = date.getTime(); data[4] = date.getTime(); data[5] = 1; cursor.addRow(data); c.moveToNext(); } } c.close(); } if (cursor != null) { Log.i("DbAdapter", "Export of old bookmarks: Writing file."); new Thread(new XmlHistoryBookmarksExporter(null, "auto-export.xml", cursor, null)).start(); } } } catch (Exception e) { Log.i("DbAdapter", "Export of old bookmarks failed: " + e.getMessage()); } Log.i("DbAdapter", "End of export of old bookmarks."); } @Override public void onCreate(SQLiteDatabase db) { // db.execSQL(BOOKMARKS_DATABASE_CREATE); // db.execSQL(HISTORY_DATABASE_CREATE); db.execSQL(ADBLOCK_WHITELIST_DATABASE_CREATE); db.execSQL(MOBILE_VIEW_DATABASE_CREATE); mParent.mAdBlockListNeedPopulate = true; } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "Upgrading database."); switch (oldVersion) { case 1: // db.execSQL("ALTER TABLE " + BOOKMARKS_DATABASE_TABLE + // " ADD " + BOOKMARKS_THUMBNAIL + " BLOB;"); case 2: // db.execSQL("ALTER TABLE " + BOOKMARKS_DATABASE_TABLE + // " ADD " + BOOKMARKS_COUNT + // " INTEGER NOT NULL DEFAULT 0;"); case 3: db.execSQL(ADBLOCK_WHITELIST_DATABASE_CREATE); mParent.mAdBlockListNeedPopulate = true; case 4: db.execSQL(MOBILE_VIEW_DATABASE_CREATE); case 5: // Export old bookmarks before dropping table. exportOldBookmarks(db); db.execSQL("DROP TABLE IF EXISTS BOOKMARKS;"); db.execSQL("DROP TABLE IF EXISTS HISTORY;"); default: break; } } } private static final String TAG = "DbAdapter"; private static final String DATABASE_NAME = "ZIRCO"; private static final int DATABASE_VERSION = 6; /** * Adblock white list table. */ public static final String ADBLOCK_ROWID = "_id"; public static final String ADBLOCK_URL = "url"; private static final String ADBLOCK_WHITELIST_DATABASE_TABLE = "ADBLOCK_WHITELIST"; private static final String ADBLOCK_WHITELIST_DATABASE_CREATE = "CREATE TABLE " + ADBLOCK_WHITELIST_DATABASE_TABLE + " (" + ADBLOCK_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + ADBLOCK_URL + " TEXT NOT NULL);"; /** * Mobile view url table. */ public static final String MOBILE_VIEW_URL_ROWID = "_id"; public static final String MOBILE_VIEW_URL_URL = "url"; private static final String MOBILE_VIEW_DATABASE_TABLE = "MOBILE_VIEW_URL"; private static final String MOBILE_VIEW_DATABASE_CREATE = "CREATE TABLE " + MOBILE_VIEW_DATABASE_TABLE + " (" + MOBILE_VIEW_URL_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + MOBILE_VIEW_URL_URL + " TEXT NOT NULL);"; protected boolean mAdBlockListNeedPopulate = false; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private final Context mContext; /** * Constructor. * * @param ctx * The current context. */ public DbAdapter(Context ctx) { this.mContext = ctx; } /** * Clear the mobile view url list. */ public void clearMobileViewUrlList() { mDb.execSQL("DELETE FROM " + MOBILE_VIEW_DATABASE_TABLE + ";"); } /** * Delete all records from the white list. */ public void clearWhiteList() { mDb.execSQL("DELETE FROM " + ADBLOCK_WHITELIST_DATABASE_TABLE + ";"); } /******************************************************************************************************************************************************* * Adblock white list. */ /** * Close the database helper. */ public void close() { mDbHelper.close(); } /** * Delete an url from the mobile view url list. * * @param id * The id of the url to delete. */ public void deleteFromMobileViewUrlList(long id) { mDb.execSQL("DELETE FROM " + MOBILE_VIEW_DATABASE_TABLE + " WHERE " + MOBILE_VIEW_URL_ROWID + " = " + id + ";"); } /** * Delete an item in white list given its id. * * @param id * The id to delete. */ public void deleteFromWhiteList(long id) { mDb.execSQL("DELETE FROM " + ADBLOCK_WHITELIST_DATABASE_TABLE + " WHERE " + ADBLOCK_ROWID + " = " + id + ";"); } public SQLiteDatabase getDatabase() { return mDb; } /** * Get a Cursor to the mobile view url list. * * @return A Cursor to the mobile view url list. */ public Cursor getMobileViewUrlCursor() { return mDb.query(MOBILE_VIEW_DATABASE_TABLE, new String[] { MOBILE_VIEW_URL_ROWID, MOBILE_VIEW_URL_URL }, null, null, null, null, null); } /** * Get an url from the mobile view list from its id. * * @param rowId * The id. * @return The url. */ public String getMobileViewUrlItemById(long rowId) { Cursor cursor = mDb.query(true, MOBILE_VIEW_DATABASE_TABLE, new String[] { MOBILE_VIEW_URL_ROWID, MOBILE_VIEW_URL_URL }, MOBILE_VIEW_URL_ROWID + "=" + rowId, null, null, null, null, null); if (cursor.moveToFirst()) { String result; result = cursor.getString(cursor .getColumnIndex(MOBILE_VIEW_URL_URL)); cursor.close(); return result; } else { cursor.close(); return null; } } /******************************************************************************************************************************************************* * Mobile view list. */ /** * Get a list of all urls in mobile view list. * * @return A list of url. */ public List<String> getMobileViewUrlList() { List<String> result = new ArrayList<String>(); Cursor cursor = getMobileViewUrlCursor(); if (cursor.moveToFirst()) { do { result.add(cursor.getString(cursor .getColumnIndex(MOBILE_VIEW_URL_URL))); } while (cursor.moveToNext()); } cursor.close(); return result; } /** * Get the list of url presents in white list. * * @return The list of url presents in white list. */ public List<String> getWhiteList() { List<String> result = new ArrayList<String>(); Cursor cursor = getWhiteListCursor(); if (cursor.moveToFirst()) { do { result.add(cursor.getString(cursor.getColumnIndex(ADBLOCK_URL))); } while (cursor.moveToNext()); } cursor.close(); return result; } /** * Get a cursor to the list of url presents in white list. * * @return A cursor to the list of url presents in white list. */ public Cursor getWhiteListCursor() { return mDb.query(ADBLOCK_WHITELIST_DATABASE_TABLE, new String[] { ADBLOCK_ROWID, ADBLOCK_URL }, null, null, null, null, null); } /** * Get the white list url given its id. * * @param rowId * The id. * @return The white list url. */ public String getWhiteListItemById(long rowId) { Cursor cursor = mDb.query(true, ADBLOCK_WHITELIST_DATABASE_TABLE, new String[] { ADBLOCK_ROWID, ADBLOCK_URL }, ADBLOCK_ROWID + "=" + rowId, null, null, null, null, null); if (cursor.moveToFirst()) { String result; result = cursor.getString(cursor.getColumnIndex(ADBLOCK_URL)); cursor.close(); return result; } else { cursor.close(); return null; } } /** * Insert an url in the mobile view url list. * * @param url * The new url. */ public void insertInMobileViewUrlList(String url) { ContentValues initialValues = new ContentValues(); initialValues.put(MOBILE_VIEW_URL_URL, url); mDb.insert(MOBILE_VIEW_DATABASE_TABLE, null, initialValues); } /** * Insert an item in the white list. * * @param url * The url to insert. */ public void insertInWhiteList(String url) { ContentValues initialValues = new ContentValues(); initialValues.put(ADBLOCK_URL, url); mDb.insert(ADBLOCK_WHITELIST_DATABASE_TABLE, null, initialValues); } /** * Open the database helper. * * @return The current database adapter. */ public DbAdapter open() { mDbHelper = new DatabaseHelper(mContext, this); mDb = mDbHelper.getWritableDatabase(); if (mAdBlockListNeedPopulate) { populateDefaultWhiteList(); mAdBlockListNeedPopulate = false; } return this; } /** * Populate the white list with default values. */ private void populateDefaultWhiteList() { insertInWhiteList("google.com/reader"); } }
zyh3290-proxy
src/org/gaeproxy/zirco/model/DbAdapter.java
Java
gpl3
11,503
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.events; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * Implementation of the EventController. */ public final class EventController { /** * Holder for singleton implementation. */ private static class EventControllerHolder { private static final EventController INSTANCE = new EventController(); } /** * Get the unique instance of the Controller. * * @return The instance of the Controller */ public static EventController getInstance() { return EventControllerHolder.INSTANCE; } private List<IDownloadEventsListener> mDownloadListeners; /** * Private Constructor. */ private EventController() { mDownloadListeners = new ArrayList<IDownloadEventsListener>(); } /** * Add a listener for download events. * * @param listener * The listener to add. */ public synchronized void addDownloadListener( IDownloadEventsListener listener) { if (!mDownloadListeners.contains(listener)) { mDownloadListeners.add(listener); } } /** * Trigger a download event. * * @param event * The event. * @param data * Additional data. */ public synchronized void fireDownloadEvent(String event, Object data) { Iterator<IDownloadEventsListener> iter = mDownloadListeners.iterator(); while (iter.hasNext()) { iter.next().onDownloadEvent(event, data); } } /** * Remove a listener for download events. * * @param listener * The listener to remove. */ public synchronized void removeDownloadListener( IDownloadEventsListener listener) { mDownloadListeners.remove(listener); } }
zyh3290-proxy
src/org/gaeproxy/zirco/events/EventController.java
Java
gpl3
2,207
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.events; /** * Interface for object listening to download events. */ public interface IDownloadEventsListener { /** * The method run on download events. * * @param event * The event. * @param data * Additional data. */ void onDownloadEvent(String event, Object data); }
zyh3290-proxy
src/org/gaeproxy/zirco/events/IDownloadEventsListener.java
Java
gpl3
875
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.events; /** * This class defines events constants. */ public class EventConstants { public static final String EVT_DOWNLOAD_ON_START = "EVT_DOWNLOAD_ON_START"; public static final String EVT_DOWNLOAD_ON_FINISHED = "EVT_DOWNLOAD_ON_FINISHED"; public static final String EVT_DOWNLOAD_ON_PROGRESS = "EVT_DOWNLOAD_ON_PROGRESS"; }
zyh3290-proxy
src/org/gaeproxy/zirco/events/EventConstants.java
Java
gpl3
896
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.providers; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class WeaveContentProvider extends ContentProvider { private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(WEAVE_BOOKMARKS_TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } } public static final String AUTHORITY = "org.gaeproxy.zirco.providers.weavecontentprovider"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_NAME = "weave.db"; public static final String WEAVE_BOOKMARKS_TABLE = "WEAVE_BOOKMARKS"; private static final String WEAVE_BOOKMARKS_TABLE_CREATE = "CREATE TABLE " + WEAVE_BOOKMARKS_TABLE + " (" + WeaveColumns.WEAVE_BOOKMARKS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID + " TEXT, " + WeaveColumns.WEAVE_BOOKMARKS_WEAVE_PARENT_ID + " TEXT, " + WeaveColumns.WEAVE_BOOKMARKS_TITLE + " TEXT, " + WeaveColumns.WEAVE_BOOKMARKS_URL + " TEXT, " + WeaveColumns.WEAVE_BOOKMARKS_FOLDER + " BOOLEAN);"; private static final int WEAVE_BOOKMARKS = 1; private static final int WEAVE_BOOKMARKS_BY_ID = 2; private static final UriMatcher sUriMatcher; private SQLiteDatabase mDb; private DatabaseHelper mDbHelper; private Context mContext; static { sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); sUriMatcher.addURI(AUTHORITY, WEAVE_BOOKMARKS_TABLE, WEAVE_BOOKMARKS); sUriMatcher.addURI(AUTHORITY, WEAVE_BOOKMARKS_TABLE + "/#", WEAVE_BOOKMARKS_BY_ID); } @Override public int delete(Uri uri, String whereClause, String[] whereArgs) { int count = 0; switch (sUriMatcher.match(uri)) { case WEAVE_BOOKMARKS: count = mDb.delete(WEAVE_BOOKMARKS_TABLE, whereClause, whereArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (count > 0) { mContext.getContentResolver().notifyChange(uri, null); } return count; } @Override public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case WEAVE_BOOKMARKS: return WeaveColumns.CONTENT_TYPE; case WEAVE_BOOKMARKS_BY_ID: return WeaveColumns.CONTENT_ITEM_TYPE; default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public Uri insert(Uri uri, ContentValues values) { switch (sUriMatcher.match(uri)) { case WEAVE_BOOKMARKS: long rowId = mDb.insert(WEAVE_BOOKMARKS_TABLE, null, values); if (rowId > 0) { Uri rowUri = ContentUris.withAppendedId( WeaveColumns.CONTENT_URI, rowId); mContext.getContentResolver().notifyChange(rowUri, null); return rowUri; } throw new SQLException("Failed to insert row into " + uri); default: throw new IllegalArgumentException("Unknown URI " + uri); } } @Override public boolean onCreate() { mContext = getContext(); mDbHelper = new DatabaseHelper(mContext); mDb = mDbHelper.getWritableDatabase(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); switch (sUriMatcher.match(uri)) { case WEAVE_BOOKMARKS: qb.setTables(WEAVE_BOOKMARKS_TABLE); break; case WEAVE_BOOKMARKS_BY_ID: qb.setTables(WEAVE_BOOKMARKS_TABLE); qb.appendWhere(WeaveColumns.WEAVE_BOOKMARKS_ID + " = " + uri.getPathSegments().get(1)); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } Cursor c = qb.query(mDb, projection, selection, selectionArgs, null, null, sortOrder); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = 0; switch (sUriMatcher.match(uri)) { case WEAVE_BOOKMARKS: count = mDb.update(WEAVE_BOOKMARKS_TABLE, values, selection, selectionArgs); break; default: throw new IllegalArgumentException("Unknown URI " + uri); } if (count > 0) { mContext.getContentResolver().notifyChange(uri, null); } return count; } }
zyh3290-proxy
src/org/gaeproxy/zirco/providers/WeaveContentProvider.java
Java
gpl3
5,422
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.providers; import android.net.Uri; import android.provider.BaseColumns; public class WeaveColumns implements BaseColumns { public static final Uri CONTENT_URI = Uri.parse("content://" + WeaveContentProvider.AUTHORITY + "/" + WeaveContentProvider.WEAVE_BOOKMARKS_TABLE); public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.zirco.weave"; public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.zirco.weave"; public static final String WEAVE_BOOKMARKS_ID = "_id"; public static final String WEAVE_BOOKMARKS_WEAVE_ID = "weave_id"; public static final String WEAVE_BOOKMARKS_WEAVE_PARENT_ID = "weave_parent_id"; public static final String WEAVE_BOOKMARKS_TITLE = "title"; public static final String WEAVE_BOOKMARKS_URL = "url"; public static final String WEAVE_BOOKMARKS_FOLDER = "folder"; public static final String[] WEAVE_BOOKMARKS_PROJECTION = { WEAVE_BOOKMARKS_ID, WEAVE_BOOKMARKS_WEAVE_ID, WEAVE_BOOKMARKS_WEAVE_PARENT_ID, WEAVE_BOOKMARKS_TITLE, WEAVE_BOOKMARKS_URL, WEAVE_BOOKMARKS_FOLDER }; private WeaveColumns() { } }
zyh3290-proxy
src/org/gaeproxy/zirco/providers/WeaveColumns.java
Java
gpl3
1,708
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.providers; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import org.gaeproxy.zirco.model.UrlSuggestionItemComparator; import org.gaeproxy.zirco.model.adapters.UrlSuggestionCursorAdapter; import org.gaeproxy.zirco.model.items.BookmarkItem; import org.gaeproxy.zirco.model.items.HistoryItem; import org.gaeproxy.zirco.model.items.UrlSuggestionItem; import org.gaeproxy.zirco.model.items.WeaveBookmarkItem; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.database.Cursor; import android.database.MatrixCursor; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.provider.BaseColumns; import android.provider.Browser; import android.util.Log; public class BookmarksProviderWrapper { private static String[] sHistoryBookmarksProjection = new String[] { Browser.BookmarkColumns._ID, Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.VISITS, Browser.BookmarkColumns.DATE, Browser.BookmarkColumns.CREATED, Browser.BookmarkColumns.BOOKMARK, Browser.BookmarkColumns.FAVICON }; /** * Clear the history/bookmarks table. * * @param contentResolver * The content resolver. * @param clearHistory * If true, history items will be cleared. * @param clearBookmarks * If true, bookmarked items will be cleared. */ public static void clearHistoryAndOrBookmarks( ContentResolver contentResolver, boolean clearHistory, boolean clearBookmarks) { if (!clearHistory && !clearBookmarks) { return; } String whereClause = null; if (clearHistory && clearBookmarks) { whereClause = null; } else if (clearHistory) { whereClause = "(" + Browser.BookmarkColumns.BOOKMARK + " = 0) OR (" + Browser.BookmarkColumns.BOOKMARK + " IS NULL)"; } else if (clearBookmarks) { whereClause = Browser.BookmarkColumns.BOOKMARK + " = 1"; } contentResolver.delete(Browser.BOOKMARKS_URI, whereClause, null); } public static void clearWeaveBookmarks(ContentResolver contentResolver) { contentResolver.delete(WeaveColumns.CONTENT_URI, null, null); } /** * Delete an history record, e.g. reset the visited count and visited date * if its a bookmark, or delete it if not. * * @param contentResolver * The content resolver. * @param id * The history id. */ public static void deleteHistoryRecord(ContentResolver contentResolver, long id) { String whereClause = BaseColumns._ID + " = " + id; Cursor cursor = contentResolver.query( android.provider.Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, whereClause, null, null); if (cursor != null) { if (cursor.moveToFirst()) { if (cursor.getInt(cursor .getColumnIndex(Browser.BookmarkColumns.BOOKMARK)) == 1) { // The record is a bookmark, so we cannot delete it. // Instead, reset its visited count and last visited date. ContentValues values = new ContentValues(); values.put(Browser.BookmarkColumns.VISITS, 0); values.putNull(Browser.BookmarkColumns.DATE); contentResolver.update(Browser.BOOKMARKS_URI, values, whereClause, null); } else { // The record is not a bookmark, we can delete it. contentResolver.delete(Browser.BOOKMARKS_URI, whereClause, null); } } cursor.close(); } } public static void deleteStockBookmark(ContentResolver contentResolver, long id) { String whereClause = BaseColumns._ID + " = " + id; Cursor c = contentResolver.query(Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, whereClause, null, null); if (c != null) { if (c.moveToFirst()) { if (c.getInt(c.getColumnIndex(Browser.BookmarkColumns.BOOKMARK)) == 1) { if (c.getInt(c .getColumnIndex(Browser.BookmarkColumns.VISITS)) > 0) { // If this record has been visited, keep it in history, // but remove its bookmark flag. ContentValues values = new ContentValues(); values.put(Browser.BookmarkColumns.BOOKMARK, 0); values.putNull(Browser.BookmarkColumns.CREATED); contentResolver.update(Browser.BOOKMARKS_URI, values, whereClause, null); } else { // never visited, it can be deleted. contentResolver.delete(Browser.BOOKMARKS_URI, whereClause, null); } } } c.close(); } } public static void deleteWeaveBookmarkByWeaveId( ContentResolver contentResolver, String weaveId) { String whereClause = WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID + " = \"" + weaveId + "\""; contentResolver.delete(WeaveColumns.CONTENT_URI, whereClause, null); } /** * Stock History/Bookmarks management. */ /** * Get a Cursor on the whole content of the history/bookmarks database. * * @param contentResolver * The content resolver. * @return A Cursor. * @see Cursor */ public static Cursor getAllStockRecords(ContentResolver contentResolver) { return contentResolver.query(Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, null, null, null); } public static BookmarkItem getStockBookmarkById( ContentResolver contentResolver, long id) { BookmarkItem result = null; String whereClause = BaseColumns._ID + " = " + id; Cursor c = contentResolver.query(Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, whereClause, null, null); if (c != null) { if (c.moveToFirst()) { String title = c.getString(c .getColumnIndex(Browser.BookmarkColumns.TITLE)); String url = c.getString(c .getColumnIndex(Browser.BookmarkColumns.URL)); result = new BookmarkItem(title, url); } c.close(); } return result; } public static Cursor getStockBookmarks(ContentResolver contentResolver, int sortMode) { String whereClause = Browser.BookmarkColumns.BOOKMARK + " = 1"; String orderClause; switch (sortMode) { case 0: orderClause = Browser.BookmarkColumns.VISITS + " DESC, " + Browser.BookmarkColumns.TITLE + " COLLATE NOCASE"; break; case 1: orderClause = Browser.BookmarkColumns.TITLE + " COLLATE NOCASE"; break; case 2: orderClause = Browser.BookmarkColumns.CREATED + " DESC"; break; default: orderClause = Browser.BookmarkColumns.TITLE + " COLLATE NOCASE"; break; } return contentResolver.query(Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, whereClause, null, orderClause); } /** * Get a list of most visited bookmarks items, limited in size. * * @param contentResolver * The content resolver. * @param limit * The size limit. * @return A list of BookmarkItem. */ public static List<BookmarkItem> getStockBookmarksWithLimit( ContentResolver contentResolver, int limit) { List<BookmarkItem> result = new ArrayList<BookmarkItem>(); String whereClause = Browser.BookmarkColumns.BOOKMARK + " = 1"; String orderClause = Browser.BookmarkColumns.VISITS + " DESC"; String[] colums = new String[] { BaseColumns._ID, Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.FAVICON }; Cursor cursor = contentResolver.query( android.provider.Browser.BOOKMARKS_URI, colums, whereClause, null, orderClause); if (cursor != null) { if (cursor.moveToFirst()) { int columnTitle = cursor .getColumnIndex(Browser.BookmarkColumns.TITLE); int columnUrl = cursor .getColumnIndex(Browser.BookmarkColumns.URL); int count = 0; while (!cursor.isAfterLast() && (count < limit)) { BookmarkItem item = new BookmarkItem( cursor.getString(columnTitle), cursor.getString(columnUrl)); result.add(item); count++; cursor.moveToNext(); } } cursor.close(); } return result; } public static Cursor getStockHistory(ContentResolver contentResolver) { String whereClause = Browser.BookmarkColumns.VISITS + " > 0"; String orderClause = Browser.BookmarkColumns.DATE + " DESC"; return contentResolver.query(Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, whereClause, null, orderClause); } /** * Get a list of most recent history items, limited in size. * * @param contentResolver * The content resolver. * @param limit * The size limit. * @return A list of HistoryItem. */ public static List<HistoryItem> getStockHistoryWithLimit( ContentResolver contentResolver, int limit) { List<HistoryItem> result = new ArrayList<HistoryItem>(); String whereClause = Browser.BookmarkColumns.VISITS + " > 0"; String orderClause = Browser.BookmarkColumns.DATE + " DESC"; Cursor cursor = contentResolver.query( android.provider.Browser.BOOKMARKS_URI, Browser.HISTORY_PROJECTION, whereClause, null, orderClause); if (cursor != null) { if (cursor.moveToFirst()) { int columnId = cursor.getColumnIndex(BaseColumns._ID); int columnTitle = cursor .getColumnIndex(Browser.BookmarkColumns.TITLE); int columnUrl = cursor .getColumnIndex(Browser.BookmarkColumns.URL); int count = 0; while (!cursor.isAfterLast() && (count < limit)) { HistoryItem item = new HistoryItem( cursor.getLong(columnId), cursor.getString(columnTitle), cursor.getString(columnUrl), null); result.add(item); count++; cursor.moveToNext(); } } cursor.close(); } return result; } /** * Suggestions. */ /** * Get a cursor for suggestions, given a search pattern. Search on history * and bookmarks, on title and url. The result list is sorted based on each * result note. * * @see UrlSuggestionItem for how a note is computed. * @param contentResolver * The content resolver. * @param pattern * The pattern to search for. * @param lookInWeaveBookmarks * If true, suggestions will include bookmarks from weave. * @return A cursor of suggections. */ public static Cursor getUrlSuggestions(ContentResolver contentResolver, String pattern, boolean lookInWeaveBookmarks) { MatrixCursor cursor = new MatrixCursor(new String[] { UrlSuggestionCursorAdapter.URL_SUGGESTION_ID, UrlSuggestionCursorAdapter.URL_SUGGESTION_TITLE, UrlSuggestionCursorAdapter.URL_SUGGESTION_URL, UrlSuggestionCursorAdapter.URL_SUGGESTION_TYPE }); if ((pattern != null) && (pattern.length() > 0)) { String sqlPattern = "%" + pattern + "%"; List<UrlSuggestionItem> results = new ArrayList<UrlSuggestionItem>(); Cursor stockCursor = contentResolver.query(Browser.BOOKMARKS_URI, sHistoryBookmarksProjection, Browser.BookmarkColumns.TITLE + " LIKE '" + sqlPattern + "' OR " + Browser.BookmarkColumns.URL + " LIKE '" + sqlPattern + "'", null, null); if (stockCursor != null) { if (stockCursor.moveToFirst()) { int titleId = stockCursor .getColumnIndex(Browser.BookmarkColumns.TITLE); int urlId = stockCursor .getColumnIndex(Browser.BookmarkColumns.URL); int bookmarkId = stockCursor .getColumnIndex(Browser.BookmarkColumns.BOOKMARK); do { boolean isFolder = stockCursor.getInt(bookmarkId) > 0 ? true : false; results.add(new UrlSuggestionItem(pattern, stockCursor .getString(titleId), stockCursor .getString(urlId), isFolder ? 2 : 1)); } while (stockCursor.moveToNext()); } stockCursor.close(); } if (lookInWeaveBookmarks) { Cursor weaveCursor = contentResolver.query( WeaveColumns.CONTENT_URI, null, WeaveColumns.WEAVE_BOOKMARKS_FOLDER + " = 0 AND (" + WeaveColumns.WEAVE_BOOKMARKS_TITLE + " LIKE '" + sqlPattern + "' OR " + WeaveColumns.WEAVE_BOOKMARKS_URL + " LIKE '" + sqlPattern + "')", null, null); if (weaveCursor != null) { if (weaveCursor.moveToFirst()) { int weaveTitleId = weaveCursor .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_TITLE); int weaveUrlId = weaveCursor .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_URL); do { results.add(new UrlSuggestionItem(pattern, weaveCursor.getString(weaveTitleId), weaveCursor.getString(weaveUrlId), 3)); } while (weaveCursor.moveToNext()); } weaveCursor.close(); } } // Sort results. Collections.sort(results, new UrlSuggestionItemComparator()); // Log.d("Results", Integer.toString(results.size())); // Copy results to the output MatrixCursor. int idCounter = -1; for (UrlSuggestionItem item : results) { idCounter++; String[] row = new String[4]; row[0] = Integer.toString(idCounter); row[1] = item.getTitle(); row[2] = item.getUrl(); row[3] = Integer.toString(item.getType()); cursor.addRow(row); } } return cursor; } public static WeaveBookmarkItem getWeaveBookmarkById( ContentResolver contentResolver, long id) { WeaveBookmarkItem result = null; Uri uri = ContentUris.withAppendedId(WeaveColumns.CONTENT_URI, id); Cursor c = contentResolver.query(uri, null, null, null, null); if (c != null) { if (c.moveToFirst()) { String title = c.getString(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_TITLE)); String url = c.getString(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_URL)); String weaveId = c.getString(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID)); boolean isFolder = c.getInt(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_FOLDER)) > 0 ? true : false; result = new WeaveBookmarkItem(title, url, weaveId, isFolder); } c.close(); } return result; } public static long getWeaveBookmarkIdByWeaveId( ContentResolver contentResolver, String weaveId) { long result = -1; String whereClause = WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID + " = \"" + weaveId + "\""; Cursor c = contentResolver.query(WeaveColumns.CONTENT_URI, null, whereClause, null, null); if (c != null) { if (c.moveToFirst()) { result = c.getLong(c .getColumnIndex(WeaveColumns.WEAVE_BOOKMARKS_ID)); } c.close(); } return result; } /** * Weave bookmarks management. */ public static Cursor getWeaveBookmarksByParentId( ContentResolver contentResolver, String parentId) { String whereClause = WeaveColumns.WEAVE_BOOKMARKS_WEAVE_PARENT_ID + " = \"" + parentId + "\""; String orderClause = WeaveColumns.WEAVE_BOOKMARKS_FOLDER + " DESC, " + WeaveColumns.WEAVE_BOOKMARKS_TITLE + " COLLATE NOCASE"; return contentResolver.query(WeaveColumns.CONTENT_URI, WeaveColumns.WEAVE_BOOKMARKS_PROJECTION, whereClause, null, orderClause); } /** * Insert a full record in history/bookmarks database. * * @param contentResolver * The content resolver. * @param title * The record title. * @param url * The record url. * @param visits * The record visit count. * @param date * The record last visit date. * @param created * The record bookmark creation date. * @param bookmark * The bookmark flag. */ public static void insertRawRecord(ContentResolver contentResolver, String title, String url, int visits, long date, long created, int bookmark) { ContentValues values = new ContentValues(); values.put(Browser.BookmarkColumns.TITLE, title); values.put(Browser.BookmarkColumns.URL, url); values.put(Browser.BookmarkColumns.VISITS, visits); if (date > 0) { values.put(Browser.BookmarkColumns.DATE, date); } else { values.putNull(Browser.BookmarkColumns.DATE); } if (created > 0) { values.put(Browser.BookmarkColumns.CREATED, created); } else { values.putNull(Browser.BookmarkColumns.CREATED); } if (bookmark > 0) { values.put(Browser.BookmarkColumns.BOOKMARK, 1); } else { values.put(Browser.BookmarkColumns.BOOKMARK, 0); } contentResolver.insert(Browser.BOOKMARKS_URI, values); } public static void insertWeaveBookmark(ContentResolver contentResolver, ContentValues values) { contentResolver.insert(WeaveColumns.CONTENT_URI, values); } /** * Modify a bookmark/history record. If an id is provided, it look for it * and update its values. If not, values will be inserted. If no id is * provided, it look for a record with the given url. It found, its values * are updated. If not, values will be inserted. * * @param contentResolver * The content resolver. * @param id * The record id to look for. * @param title * The record title. * @param url * The record url. * @param isBookmark * If True, the record will be a bookmark. */ public static void setAsBookmark(ContentResolver contentResolver, long id, String title, String url, boolean isBookmark) { boolean bookmarkExist = false; if (id != -1) { String[] colums = new String[] { BaseColumns._ID }; String whereClause = BaseColumns._ID + " = " + id; Cursor cursor = contentResolver.query( android.provider.Browser.BOOKMARKS_URI, colums, whereClause, null, null); bookmarkExist = (cursor != null) && (cursor.moveToFirst()); } else { String[] colums = new String[] { BaseColumns._ID }; String whereClause = Browser.BookmarkColumns.URL + " = \"" + url + "\""; Cursor cursor = contentResolver.query( android.provider.Browser.BOOKMARKS_URI, colums, whereClause, null, null); bookmarkExist = (cursor != null) && (cursor.moveToFirst()); if (bookmarkExist) { id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID)); } } ContentValues values = new ContentValues(); if (title != null) { values.put(Browser.BookmarkColumns.TITLE, title); } if (url != null) { values.put(Browser.BookmarkColumns.URL, url); } if (isBookmark) { values.put(Browser.BookmarkColumns.BOOKMARK, 1); values.put(Browser.BookmarkColumns.CREATED, new Date().getTime()); } else { values.put(Browser.BookmarkColumns.BOOKMARK, 0); } if (bookmarkExist) { contentResolver.update(android.provider.Browser.BOOKMARKS_URI, values, BaseColumns._ID + " = " + id, null); } else { contentResolver.insert(android.provider.Browser.BOOKMARKS_URI, values); } } /** * Remove from history values prior to now minus the number of days defined * in preferences. Only delete history items, not bookmarks. * * @param contentResolver * The content resolver. */ public static void truncateHistory(ContentResolver contentResolver, String prefHistorySize) { int historySize; try { historySize = Integer.parseInt(prefHistorySize); } catch (NumberFormatException e) { historySize = 90; } Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); c.add(Calendar.DAY_OF_YEAR, -historySize); String whereClause = "(" + Browser.BookmarkColumns.BOOKMARK + " = 0 OR " + Browser.BookmarkColumns.BOOKMARK + " IS NULL) AND " + Browser.BookmarkColumns.DATE + " < " + c.getTimeInMillis(); try { contentResolver.delete(Browser.BOOKMARKS_URI, whereClause, null); } catch (Exception e) { e.printStackTrace(); Log.w("BookmarksProviderWrapper", "Unable to truncate history: " + e.getMessage()); } } /** * Update the favicon in history/bookmarks database. * * @param currentActivity * The current acitivity. * @param url * The url. * @param originalUrl * The original url. * @param favicon * The favicon. */ public static void updateFavicon(Activity currentActivity, String url, String originalUrl, Bitmap favicon) { String whereClause; if (!url.equals(originalUrl)) { whereClause = Browser.BookmarkColumns.URL + " = \"" + url + "\" OR " + Browser.BookmarkColumns.URL + " = \"" + originalUrl + "\""; } else { whereClause = Browser.BookmarkColumns.URL + " = \"" + url + "\""; } // BitmapDrawable icon = // ApplicationUtils.getNormalizedFaviconForBookmarks(currentActivity, // favicon); BitmapDrawable icon = new BitmapDrawable(favicon); ByteArrayOutputStream os = new ByteArrayOutputStream(); icon.getBitmap().compress(Bitmap.CompressFormat.PNG, 100, os); ContentValues values = new ContentValues(); values.put(Browser.BookmarkColumns.FAVICON, os.toByteArray()); try { currentActivity.getContentResolver().update( android.provider.Browser.BOOKMARKS_URI, values, whereClause, null); } catch (Exception e) { e.printStackTrace(); Log.w("BookmarksProviderWrapper", "Unable to update favicon: " + e.getMessage()); } } /** * Update the history: visit count and last visited date. * * @param contentResolver * The content resolver. * @param title * The title. * @param url * The url. * @param originalUrl * The original url */ public static void updateHistory(ContentResolver contentResolver, String title, String url, String originalUrl) { String[] colums = new String[] { BaseColumns._ID, Browser.BookmarkColumns.URL, Browser.BookmarkColumns.BOOKMARK, Browser.BookmarkColumns.VISITS }; String whereClause = Browser.BookmarkColumns.URL + " = \"" + url + "\" OR " + Browser.BookmarkColumns.URL + " = \"" + originalUrl + "\""; Cursor cursor = contentResolver.query(Browser.BOOKMARKS_URI, colums, whereClause, null, null); if (cursor != null) { if (cursor.moveToFirst()) { long id = cursor .getLong(cursor.getColumnIndex(BaseColumns._ID)); int visits = cursor.getInt(cursor .getColumnIndex(Browser.BookmarkColumns.VISITS)) + 1; ContentValues values = new ContentValues(); // If its not a bookmark, we can update the title. If we were // doing it on bookmarks, we would override the title choosen by // the user. if (cursor.getInt(cursor .getColumnIndex(Browser.BookmarkColumns.BOOKMARK)) != 1) { values.put(Browser.BookmarkColumns.TITLE, title); } values.put(Browser.BookmarkColumns.DATE, new Date().getTime()); values.put(Browser.BookmarkColumns.VISITS, visits); contentResolver.update(android.provider.Browser.BOOKMARKS_URI, values, BaseColumns._ID + " = " + id, null); } else { ContentValues values = new ContentValues(); values.put(Browser.BookmarkColumns.TITLE, title); values.put(Browser.BookmarkColumns.URL, url); values.put(Browser.BookmarkColumns.DATE, new Date().getTime()); values.put(Browser.BookmarkColumns.VISITS, 1); values.put(Browser.BookmarkColumns.BOOKMARK, 0); contentResolver.insert(android.provider.Browser.BOOKMARKS_URI, values); } cursor.close(); } } public static void updateWeaveBookmark(ContentResolver contentResolver, long id, ContentValues values) { String whereClause = WeaveColumns.WEAVE_BOOKMARKS_ID + " = " + id; contentResolver.update(WeaveColumns.CONTENT_URI, values, whereClause, null); } }
zyh3290-proxy
src/org/gaeproxy/zirco/providers/BookmarksProviderWrapper.java
Java
gpl3
24,636
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.controllers; import java.util.ArrayList; import java.util.List; import org.gaeproxy.zirco.model.DbAdapter; import org.gaeproxy.zirco.model.items.DownloadItem; import org.gaeproxy.zirco.ui.components.CustomWebView; import android.content.Context; import android.content.SharedPreferences; /** * Controller implementation. */ public final class Controller { /** * Holder for singleton implementation. */ private static final class ControllerHolder { private static final Controller INSTANCE = new Controller(); /** * Private Constructor. */ private ControllerHolder() { } } /** * Get the unique instance of the Controller. * * @return The instance of the Controller */ public static Controller getInstance() { return ControllerHolder.INSTANCE; } private SharedPreferences mPreferences; private List<CustomWebView> mWebViewList; private List<DownloadItem> mDownloadList; private List<String> mAdBlockWhiteList = null; private List<String> mMobileViewUrlList = null; /** * Private Constructor. */ private Controller() { mDownloadList = new ArrayList<DownloadItem>(); } /** * Add an item to the download list. * * @param item * The new item. */ public void addToDownload(DownloadItem item) { mDownloadList.add(item); } public synchronized void clearCompletedDownloads() { List<DownloadItem> newList = new ArrayList<DownloadItem>(); for (DownloadItem item : mDownloadList) { if (!item.isFinished()) { newList.add(item); } } mDownloadList.clear(); mDownloadList = newList; } /** * Get the list of white-listed url for the AdBlocker. * * @param context * The current context. * @return A list of String url. */ public List<String> getAdBlockWhiteList(Context context) { if (mAdBlockWhiteList == null) { DbAdapter db = new DbAdapter(context); db.open(); mAdBlockWhiteList = db.getWhiteList(); db.close(); } return mAdBlockWhiteList; } /** * Get the current download list. * * @return The current download list. */ public List<DownloadItem> getDownloadList() { return mDownloadList; } /** * Get the list of mobile view urls. * * @param context * The current context. * @return A list of String url. */ public List<String> getMobileViewUrlList(Context context) { if (mMobileViewUrlList == null) { DbAdapter db = new DbAdapter(context); db.open(); mMobileViewUrlList = db.getMobileViewUrlList(); db.close(); } return mMobileViewUrlList; } /** * Get a SharedPreferences instance. * * @return The SharedPreferences instance. */ public SharedPreferences getPreferences() { return mPreferences; } /** * Get the list of current WebViews. * * @return The list of current WebViews. */ public List<CustomWebView> getWebViewList() { return mWebViewList; } /** * Reset the AdBlock white list, so that it will be reloaded. */ public void resetAdBlockWhiteList() { mAdBlockWhiteList = null; } /** * Reset the mobile view url list, so that it will be reloaded. */ public void resetMobileViewUrlList() { mMobileViewUrlList = null; } /** * Set the SharedPreferences instance. * * @param preferences * The SharedPreferences instance. */ public void setPreferences(SharedPreferences preferences) { this.mPreferences = preferences; } /** * Set the list of current WebViews. * * @param list * The list of current WebViews. */ public void setWebViewList(List<CustomWebView> list) { mWebViewList = list; } }
zyh3290-proxy
src/org/gaeproxy/zirco/controllers/Controller.java
Java
gpl3
4,166
package org.gaeproxy.zirco.sync; import java.io.IOException; import java.net.URI; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.emergent.android.weave.client.QueryParams; import org.emergent.android.weave.client.QueryResult; import org.emergent.android.weave.client.UserWeave; import org.emergent.android.weave.client.WeaveAccountInfo; import org.emergent.android.weave.client.WeaveBasicObject; import org.emergent.android.weave.client.WeaveException; import org.emergent.android.weave.client.WeaveFactory; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.providers.WeaveColumns; import org.gaeproxy.zirco.utils.Constants; import org.json.JSONException; import org.json.JSONObject; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.os.AsyncTask; import android.preference.PreferenceManager; public class WeaveSyncTask extends AsyncTask<WeaveAccountInfo, Integer, Throwable> { private static final String WEAVE_PATH = "/storage/bookmarks"; private static final String WEAVE_HEADER_TYPE = "type"; private static final String WEAVE_VALUE_BOOKMARK = "bookmark"; private static final String WEAVE_VALUE_FOLDER = "folder"; private static final String WEAVE_VALUE_ITEM = "item"; private static final String WEAVE_VALUE_ID = "id"; private static final String WEAVE_VALUE_PARENT_ID = "parentid"; private static final String WEAVE_VALUE_TITLE = "title"; private static final String WEAVE_VALUE_URI = "bmkUri"; private static final String WEAVE_VALUE_DELETED = "deleted"; private static WeaveFactory mWeaveFactory = null; private static WeaveFactory getWeaveFactory() { if (mWeaveFactory == null) { mWeaveFactory = new WeaveFactory(true); } return mWeaveFactory; } private Context mContext; private ContentResolver mContentResolver; private ISyncListener mListener; private boolean mFullSync = false; public WeaveSyncTask(Context context, ISyncListener listener) { mContext = context; mContentResolver = context.getContentResolver(); mListener = listener; } @Override protected Throwable doInBackground(WeaveAccountInfo... arg0) { Throwable result = null; try { publishProgress(0, 0, 0); WeaveAccountInfo accountInfo = arg0[0]; UserWeave userWeave = getWeaveFactory().createUserWeave( accountInfo.getServer(), accountInfo.getUsername(), accountInfo.getPassword()); long lastModifiedDate = getLastModified(userWeave).getTime(); long lastSyncDate = PreferenceManager.getDefaultSharedPreferences( mContext).getLong( Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE, -1); if (lastModifiedDate > lastSyncDate) { publishProgress(1, 0, 0); mFullSync = lastSyncDate <= 0; QueryResult<List<WeaveBasicObject>> queryResult; QueryParams parms = null; if (!mFullSync) { parms = new QueryParams(); parms.setFull(false); parms.setNewer(new Date(lastSyncDate)); } else { BookmarksProviderWrapper .clearWeaveBookmarks(mContentResolver); } queryResult = getCollection(userWeave, WEAVE_PATH, parms); List<WeaveBasicObject> wboList = queryResult.getValue(); if (mFullSync) { doSync(accountInfo, userWeave, wboList); } else { doSyncByDelta(accountInfo, userWeave, wboList); } } } catch (WeaveException e) { e.printStackTrace(); result = e; } catch (JSONException e) { e.printStackTrace(); result = e; } catch (IOException e) { e.printStackTrace(); result = e; } catch (GeneralSecurityException e) { e.printStackTrace(); result = e; } return result; } private void doSync(WeaveAccountInfo accountInfo, UserWeave userWeave, List<WeaveBasicObject> wboList) throws WeaveException, JSONException, IOException, GeneralSecurityException { int i = 0; int count = wboList.size(); List<ContentValues> values = new ArrayList<ContentValues>(); mContext.getContentResolver().delete(WeaveColumns.CONTENT_URI, null, null); for (WeaveBasicObject wbo : wboList) { JSONObject decryptedPayload = wbo.getEncryptedPayload(userWeave, accountInfo.getSecret()); i++; // if (i > 30) break; // Log.d("Decrypted:", decryptedPayload.toString()); if (decryptedPayload.has(WEAVE_HEADER_TYPE) && ((decryptedPayload.getString(WEAVE_HEADER_TYPE) .equals(WEAVE_VALUE_BOOKMARK)) || (decryptedPayload .getString(WEAVE_HEADER_TYPE) .equals(WEAVE_VALUE_FOLDER)))) { if (decryptedPayload.has(WEAVE_VALUE_TITLE)) { boolean isFolder = decryptedPayload.getString( WEAVE_HEADER_TYPE).equals(WEAVE_VALUE_FOLDER); String title = decryptedPayload .getString(WEAVE_VALUE_TITLE); String weaveId = decryptedPayload.has(WEAVE_VALUE_ID) ? decryptedPayload .getString(WEAVE_VALUE_ID) : null; String parentId = decryptedPayload .has(WEAVE_VALUE_PARENT_ID) ? decryptedPayload .getString(WEAVE_VALUE_PARENT_ID) : null; if ((title != null) && (title.length() > 0)) { ContentValues value = new ContentValues(); value.put(WeaveColumns.WEAVE_BOOKMARKS_TITLE, title); value.put(WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID, weaveId); value.put(WeaveColumns.WEAVE_BOOKMARKS_WEAVE_PARENT_ID, parentId); if (isFolder) { value.put(WeaveColumns.WEAVE_BOOKMARKS_FOLDER, true); } else { String url = decryptedPayload .getString(WEAVE_VALUE_URI); value.put(WeaveColumns.WEAVE_BOOKMARKS_FOLDER, false); value.put(WeaveColumns.WEAVE_BOOKMARKS_URL, url); } values.add(value); } } } publishProgress(2, i, count); if (isCancelled()) { break; } } int j = 0; ContentValues[] valuesArray = new ContentValues[values.size()]; for (ContentValues value : values) { valuesArray[j++] = value; } publishProgress(3, 0, 0); mContext.getContentResolver().bulkInsert(WeaveColumns.CONTENT_URI, valuesArray); } private void doSyncByDelta(WeaveAccountInfo accountInfo, UserWeave userWeave, List<WeaveBasicObject> wboList) throws WeaveException, JSONException, IOException, GeneralSecurityException { int i = 0; int count = wboList.size(); for (WeaveBasicObject wbo : wboList) { JSONObject decryptedPayload = wbo.getEncryptedPayload(userWeave, accountInfo.getSecret()); i++; if (decryptedPayload.has(WEAVE_HEADER_TYPE)) { if (decryptedPayload.getString(WEAVE_HEADER_TYPE).equals( WEAVE_VALUE_ITEM) && decryptedPayload.has(WEAVE_VALUE_DELETED) && decryptedPayload.getBoolean(WEAVE_VALUE_DELETED)) { String weaveId = decryptedPayload.has(WEAVE_VALUE_ID) ? decryptedPayload .getString(WEAVE_VALUE_ID) : null; if ((weaveId != null) && (weaveId.length() > 0)) { // mDbAdapter.deleteWeaveBookmarkByWeaveId(weaveId); BookmarksProviderWrapper.deleteWeaveBookmarkByWeaveId( mContentResolver, weaveId); } } else if (decryptedPayload.getString(WEAVE_HEADER_TYPE) .equals(WEAVE_VALUE_BOOKMARK) || decryptedPayload.getString(WEAVE_HEADER_TYPE) .equals(WEAVE_VALUE_FOLDER)) { String weaveId = decryptedPayload.has(WEAVE_VALUE_ID) ? decryptedPayload .getString(WEAVE_VALUE_ID) : null; if ((weaveId != null) && (weaveId.length() > 0)) { boolean isFolder = decryptedPayload.getString( WEAVE_HEADER_TYPE).equals(WEAVE_VALUE_FOLDER); String title = decryptedPayload .getString(WEAVE_VALUE_TITLE); String parentId = decryptedPayload .has(WEAVE_VALUE_PARENT_ID) ? decryptedPayload .getString(WEAVE_VALUE_PARENT_ID) : null; ContentValues values = new ContentValues(); values.put(WeaveColumns.WEAVE_BOOKMARKS_WEAVE_ID, weaveId); values.put( WeaveColumns.WEAVE_BOOKMARKS_WEAVE_PARENT_ID, parentId); values.put(WeaveColumns.WEAVE_BOOKMARKS_TITLE, title); if (isFolder) { values.put(WeaveColumns.WEAVE_BOOKMARKS_FOLDER, true); } else { String url = decryptedPayload .getString(WEAVE_VALUE_URI); values.put(WeaveColumns.WEAVE_BOOKMARKS_FOLDER, false); values.put(WeaveColumns.WEAVE_BOOKMARKS_URL, url); } long id = BookmarksProviderWrapper .getWeaveBookmarkIdByWeaveId(mContentResolver, weaveId);// mDbAdapter.getIdByWeaveId(weaveId); if (id == -1) { // Insert. BookmarksProviderWrapper.insertWeaveBookmark( mContentResolver, values); } else { // Update. BookmarksProviderWrapper.updateWeaveBookmark( mContentResolver, id, values); } } } } // Log.d("Decrypted:", decryptedPayload.toString()); publishProgress(2, i, count); if (isCancelled()) { break; } } } private QueryResult<List<WeaveBasicObject>> getCollection(UserWeave weave, String name, QueryParams params) throws WeaveException { if (params == null) params = new QueryParams(); URI uri = weave.buildSyncUriFromSubpath(name + params.toQueryString()); return weave.getWboCollection(uri); } private Date getLastModified(UserWeave userWeave) throws WeaveException { try { JSONObject infoCol = userWeave.getNode( UserWeave.HashNode.INFO_COLLECTIONS).getValue(); if (infoCol.has("bookmarks")) { long modLong = infoCol.getLong("bookmarks"); return new Date(modLong * 1000); } return null; } catch (JSONException e) { throw new WeaveException(e); } } public boolean isFullSync() { return mFullSync; } @Override protected void onCancelled() { mListener.onSyncCancelled(); super.onCancelled(); } @Override protected void onPostExecute(Throwable result) { mListener.onSyncEnd(result); } @Override protected void onProgressUpdate(Integer... values) { mListener.onSyncProgress(values[0], values[1], values[2]); } }
zyh3290-proxy
src/org/gaeproxy/zirco/sync/WeaveSyncTask.java
Java
gpl3
10,059
package org.gaeproxy.zirco.sync; public interface ISyncListener { void onSyncCancelled(); void onSyncEnd(Throwable result); void onSyncProgress(int step, int done, int total); }
zyh3290-proxy
src/org/gaeproxy/zirco/sync/ISyncListener.java
Java
gpl3
186
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import org.gaeproxy.R; import android.content.Context; import android.util.Log; /** * Utilities for date / time management. */ public class DateUtils { /** * Parse a string representation of a date in default format to a Date * object. * * @param context * The current context. * @param date * The date to convert. * @return The converted date. If an error occurs during conversion, will be * the current date. */ public static Date convertFromDatabase(Context context, String date) { SimpleDateFormat sdf = new SimpleDateFormat(getDefaultFormat(context)); try { return sdf.parse(date); } catch (ParseException e) { Log.w(DateUtils.class.toString(), "Error parsing date (" + date + "): " + e.getMessage()); return new Date(); } } /** * Get the default date format. * * @param context * The current context. * @return The default date format. */ private static String getDefaultFormat(Context context) { return context.getResources().getString(R.string.DATE_FORMAT_ISO8601); } /** * Get a string representation of the current date / time in a format * suitable for a file name. * * @return A string representation of the current date / time. */ public static String getNowForFileName() { Calendar c = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); return sdf.format(c.getTime()); } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/DateUtils.java
Java
gpl3
2,158
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import android.view.animation.AccelerateInterpolator; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; /** * Holder for animation objects. */ public final class AnimationManager { /** * Holder for singleton implementation. */ private static class AnimationManagerHolder { private static final AnimationManager INSTANCE = new AnimationManager(); } private static final int BARS_ANIMATION_DURATION = 150; private static final int ANIMATION_DURATION = 350; /** * Get the unique instance of the Controller. * * @return The instance of the Controller */ public static AnimationManager getInstance() { return AnimationManagerHolder.INSTANCE; } private Animation mTopBarShowAnimation = null; private Animation mTopBarHideAnimation = null; private Animation mBottomBarShowAnimation = null; private Animation mBottomBarHideAnimation = null; private Animation mPreviousTabViewShowAnimation = null; private Animation mPreviousTabViewHideAnimation = null; private Animation mNextTabViewShowAnimation = null; private Animation mNextTabViewHideAnimation = null; private Animation mInFromRightAnimation; private Animation mOutToLeftAnimation; private Animation mInFromLeftAnimation; private Animation mOutToRightAnimation; /** * Contructor. */ private AnimationManager() { mTopBarShowAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); mTopBarShowAnimation.setDuration(BARS_ANIMATION_DURATION); mTopBarHideAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f); mTopBarHideAnimation.setDuration(BARS_ANIMATION_DURATION); mBottomBarShowAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f); mBottomBarShowAnimation.setDuration(BARS_ANIMATION_DURATION); mBottomBarHideAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f); mBottomBarHideAnimation.setDuration(BARS_ANIMATION_DURATION); mPreviousTabViewShowAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); mPreviousTabViewShowAnimation.setDuration(BARS_ANIMATION_DURATION); mPreviousTabViewHideAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); mPreviousTabViewHideAnimation.setDuration(BARS_ANIMATION_DURATION); mNextTabViewShowAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); mNextTabViewShowAnimation.setDuration(BARS_ANIMATION_DURATION); mNextTabViewHideAnimation = new TranslateAnimation( Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f); mNextTabViewHideAnimation.setDuration(BARS_ANIMATION_DURATION); mInFromRightAnimation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); mInFromRightAnimation.setDuration(ANIMATION_DURATION); mInFromRightAnimation.setInterpolator(new AccelerateInterpolator()); mOutToLeftAnimation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); mOutToLeftAnimation.setDuration(ANIMATION_DURATION); mOutToLeftAnimation.setInterpolator(new AccelerateInterpolator()); mInFromLeftAnimation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, -1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); mInFromLeftAnimation.setDuration(ANIMATION_DURATION); mInFromLeftAnimation.setInterpolator(new AccelerateInterpolator()); mOutToRightAnimation = new TranslateAnimation( Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, +1.0f, Animation.RELATIVE_TO_PARENT, 0.0f, Animation.RELATIVE_TO_PARENT, 0.0f); mOutToRightAnimation.setDuration(ANIMATION_DURATION); mOutToRightAnimation.setInterpolator(new AccelerateInterpolator()); } public Animation getBottomBarHideAnimation() { return mBottomBarHideAnimation; } public Animation getBottomBarShowAnimation() { return mBottomBarShowAnimation; } /** * Get the in from left animation object. * * @return The animation object. */ public Animation getInFromLeftAnimation() { return mInFromLeftAnimation; } /** * Get the in from right animation object. * * @return The animation object. */ public Animation getInFromRightAnimation() { return mInFromRightAnimation; } public Animation getNextTabViewHideAnimation() { return mNextTabViewHideAnimation; } public Animation getNextTabViewShowAnimation() { return mNextTabViewShowAnimation; } /** * Get the out to left animation object. * * @return The animation object. */ public Animation getOutToLeftAnimation() { return mOutToLeftAnimation; } /** * Get the out to right animation object. * * @return The animation object. */ public Animation getOutToRightAnimation() { return mOutToRightAnimation; } public Animation getPreviousTabViewHideAnimation() { return mPreviousTabViewHideAnimation; } public Animation getPreviousTabViewShowAnimation() { return mPreviousTabViewShowAnimation; } public Animation getTopBarHideAnimation() { return mTopBarHideAnimation; } public Animation getTopBarShowAnimation() { return mTopBarShowAnimation; } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/AnimationManager.java
Java
gpl3
6,844
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import java.util.Iterator; import org.gaeproxy.zirco.controllers.Controller; import android.content.Context; import android.preference.PreferenceManager; /** * Url management utils. */ public class UrlUtils { /** * Check if there is an item in the mobile view url list that match a given * url. * * @param context * The current context. * @param url * The url to check. * @return True if an item in the list match the given url. */ public static boolean checkInMobileViewUrlList(Context context, String url) { if (url != null) { boolean inList = false; Iterator<String> iter = Controller.getInstance() .getMobileViewUrlList(context).iterator(); while ((iter.hasNext()) && (!inList)) { if (url.contains(iter.next())) { inList = true; } } return inList; } else { return false; } } /** * Check en url. Add http:// before if missing. * * @param url * The url to check. * @return The modified url if necessary. */ public static String checkUrl(String url) { if ((url != null) && (url.length() > 0)) { if ((!url.startsWith("http://")) && (!url.startsWith("https://")) && (!url.startsWith(Constants.URL_ABOUT_BLANK)) && (!url.startsWith(Constants.URL_ABOUT_START))) { url = "http://" + url; } } return url; } /** * Get the current search url. * * @param context * The current context. * @param searchTerms * The terms to search for. * @return The search url. */ public static String getSearchUrl(Context context, String searchTerms) { String currentSearchUrl = PreferenceManager .getDefaultSharedPreferences(context).getString( Constants.PREFERENCES_GENERAL_SEARCH_URL, Constants.URL_SEARCH_GOOGLE); return String.format(currentSearchUrl, searchTerms); } /** * Check if a string is an url. For now, just consider that if a string * contains a dot, it is an url. * * @param url * The url to check. * @return True if the string is an url. */ public static boolean isUrl(String url) { return url.equals(Constants.URL_ABOUT_BLANK) || url.equals(Constants.URL_ABOUT_START) || url.contains("."); } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/UrlUtils.java
Java
gpl3
2,808
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import org.gaeproxy.R; import android.content.Context; /** * Defines constants. */ public class Constants { public static final String EXTRA_ID_NEW_TAB = "EXTRA_ID_NEW_TAB"; public static final String EXTRA_ID_URL = "EXTRA_ID_URL"; public static final String EXTRA_ID_BOOKMARK_ID = "EXTRA_ID_BOOKMARK_ID"; public static final String EXTRA_ID_BOOKMARK_URL = "EXTRA_ID_BOOKMARK_URL"; public static final String EXTRA_ID_BOOKMARK_TITLE = "EXTRA_ID_BOOKMARK_TITLE"; public static final int BOOKMARK_THUMBNAIL_WIDTH_FACTOR = 70; public static final int BOOKMARK_THUMBNAIL_HEIGHT_FACTOR = 60; /** * Specials urls. */ public static final String URL_ABOUT_BLANK = "about:blank"; public static final String URL_ABOUT_START = "about:start"; public static final String URL_ACTION_SEARCH = "action:search?q="; public static final String URL_GOOGLE_MOBILE_VIEW = "http://www.google.com/gwt/x?u=%s"; public static final String URL_GOOGLE_MOBILE_VIEW_NO_FORMAT = "http://www.google.com/gwt/x?u="; /** * Search urls. */ public static String URL_SEARCH_GOOGLE = "http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=%s"; public static String URL_SEARCH_WIKIPEDIA = "http://en.wikipedia.org/w/index.php?search=%s&go=Go"; /** * User agents. */ public static String USER_AGENT_DEFAULT = ""; public static String USER_AGENT_DESKTOP = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/534.7 (KHTML, like Gecko) Chrome/7.0.517.44 Safari/534.7"; /** * Preferences. */ public static final String PREFERENCES_GENERAL_HOME_PAGE = "GeneralHomePage"; public static final String PREFERENCES_GENERAL_SEARCH_URL = "GeneralSearchUrl"; public static final String PREFERENCES_GENERAL_SWITCH_TABS_METHOD = "GeneralSwitchTabMethod"; public static final String PREFERENCES_GENERAL_BARS_DURATION = "GeneralBarsDuration"; public static final String PREFERENCES_GENERAL_BUBBLE_POSITION = "GeneralBubblePosition"; public static final String PREFERENCES_SHOW_FULL_SCREEN = "GeneralFullScreen"; public static final String PREFERENCES_GENERAL_HIDE_TITLE_BARS = "GeneralHideTitleBars"; public static final String PREFERENCES_SHOW_TOAST_ON_TAB_SWITCH = "GeneralShowToastOnTabSwitch"; public static final String PREFERENCES_UI_VOLUME_KEYS_BEHAVIOUR = "GeneralVolumeKeysBehaviour"; public static final String PREFERENCES_DEFAULT_ZOOM_LEVEL = "DefaultZoomLevel"; public static final String PREFERENCES_BROWSER_HISTORY_SIZE = "BrowserHistorySize"; public static final String PREFERENCES_BROWSER_ENABLE_JAVASCRIPT = "BrowserEnableJavascript"; public static final String PREFERENCES_BROWSER_ENABLE_IMAGES = "BrowserEnableImages"; public static final String PREFERENCES_BROWSER_USE_WIDE_VIEWPORT = "BrowserUseWideViewPort"; public static final String PREFERENCES_BROWSER_LOAD_WITH_OVERVIEW = "BrowserLoadWithOverview"; public static final String PREFERENCES_BROWSER_ENABLE_FORM_DATA = "BrowserEnableFormData"; public static final String PREFERENCES_BROWSER_ENABLE_PASSWORDS = "BrowserEnablePasswords"; public static final String PREFERENCES_BROWSER_ENABLE_COOKIES = "BrowserEnableCookies"; public static final String PREFERENCES_BROWSER_USER_AGENT = "BrowserUserAgent"; public static final String PREFERENCES_BROWSER_ENABLE_PLUGINS_ECLAIR = "BrowserEnablePluginsEclair"; public static final String PREFERENCES_BROWSER_ENABLE_PLUGINS = "BrowserEnablePlugins"; public static final String PREFERENCES_PRIVACY_CLEAR_CACHE_ON_EXIT = "PrivacyClearCacheOnExit"; public static final String PREFERENCES_ADBLOCKER_ENABLE = "AdBlockerEnable"; public static final String PREFERENCES_BOOKMARKS_SORT_MODE = "BookmarksSortMode"; public static final String PREFERENCES_LAST_VERSION_CODE = "LastVersionCode"; public static final String PREFERENCES_START_PAGE_SHOW_SEARCH = "StartPageEnableSearch"; public static final String PREFERENCES_START_PAGE_SHOW_BOOKMARKS = "StartPageEnableBookmarks"; public static final String PREFERENCES_START_PAGE_SHOW_HISTORY = "StartPageEnableHistory"; public static final String PREFERENCES_START_PAGE_BOOKMARKS_LIMIT = "StartPageBookmarksLimit"; public static final String PREFERENCES_START_PAGE_HISTORY_LIMIT = "StartPageHistoryLimit"; public static final String PREFERENCE_USE_WEAVE = "PREFERENCE_USE_WEAVE"; public static final String PREFERENCE_WEAVE_SERVER = "PREFERENCE_WEAVE_SERVER"; public static final String PREFERENCE_WEAVE_USERNAME = "PREFERENCE_WEAVE_USERNAME"; public static final String PREFERENCE_WEAVE_PASSWORD = "PREFERENCE_WEAVE_PASSWORD"; public static final String PREFERENCE_WEAVE_KEY = "PREFERENCE_WEAVE_KEY"; public static final String PREFERENCE_WEAVE_LAST_SYNC_DATE = "PREFERENCE_WEAVE_LAST_SYNC_DATE"; public static final String WEAVE_AUTH_TOKEN_SCHEME = "{\"secret\":\"%s\",\"password\":\"%s\",\"username\":\"%s\",\"server\":\"%s\"}"; public static final String WEAVE_DEFAULT_SERVER = "https://auth.services.mozilla.com/"; /** * Methods. */ /** * Initialize the search url "constants", which depends on the user local. * * @param context * The current context. */ public static void initializeConstantsFromResources(Context context) { URL_SEARCH_GOOGLE = context.getResources().getString( R.string.Constants_SearchUrlGoogle); URL_SEARCH_WIKIPEDIA = context.getResources().getString( R.string.Constants_SearchUrlWikipedia); } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/Constants.java
Java
gpl3
5,952
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import org.gaeproxy.R; import org.gaeproxy.zirco.model.items.BookmarkItem; import org.gaeproxy.zirco.model.items.HistoryItem; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Environment; import android.preference.PreferenceManager; import android.text.ClipboardManager; import android.util.DisplayMetrics; import android.util.Log; import android.widget.Toast; /** * Application utilities. */ public class ApplicationUtils { private static String mAdSweepString = null; private static String mRawStartPage = null; private static String mRawStartPageStyles = null; private static String mRawStartPageBookmarks = null; private static String mRawStartPageHistory = null; private static String mRawStartPageSearch = null; private static int mFaviconSize = -1; private static int mImageButtonSize = -1; private static int mFaviconSizeForBookmarks = -1; /** * Check if the SD card is available. Display an alert if not. * * @param context * The current context. * @param showMessage * If true, will display a message for the user. * @return True if the SD card is available, false otherwise. */ public static boolean checkCardState(Context context, boolean showMessage) { // Check to see if we have an SDCard String status = Environment.getExternalStorageState(); if (!status.equals(Environment.MEDIA_MOUNTED)) { int messageId; // Check to see if the SDCard is busy, same as the music app if (status.equals(Environment.MEDIA_SHARED)) { messageId = R.string.Commons_SDCardErrorSDUnavailable; } else { messageId = R.string.Commons_SDCardErrorNoSDMsg; } if (showMessage) { ApplicationUtils.showErrorDialog(context, R.string.Commons_SDCardErrorTitle, messageId); } return false; } return true; } /** * Copy a text to the clipboard. * * @param context * The current context. * @param text * The text to copy. * @param toastMessage * The message to show in a Toast notification. If empty or null, * does not display notification. */ public static void copyTextToClipboard(Context context, String text, String toastMessage) { ClipboardManager clipboard = (ClipboardManager) context .getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setText(text); if ((toastMessage != null) && (toastMessage.length() > 0)) { Toast.makeText(context, toastMessage, Toast.LENGTH_SHORT).show(); } } /** * Load the AdSweep script if necessary. * * @param context * The current context. * @return The AdSweep script. */ public static String getAdSweepString(Context context) { if (mAdSweepString == null) { InputStream is = context.getResources().openRawResource( R.raw.adsweep); if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { if ((line.length() > 0) && (!line.startsWith("//"))) { sb.append(line).append("\n"); } } } catch (IOException e) { Log.w("AdSweep", "Unable to load AdSweep: " + e.getMessage()); } finally { try { is.close(); } catch (IOException e) { Log.w("AdSweep", "Unable to load AdSweep: " + e.getMessage()); } } mAdSweepString = sb.toString(); } else { mAdSweepString = ""; } } return mAdSweepString; } /** * Get the application version code. * * @param context * The current context. * @return The application version code. */ public static int getApplicationVersionCode(Context context) { int result = -1; try { PackageManager manager = context.getPackageManager(); PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0); result = info.versionCode; } catch (NameNotFoundException e) { Log.w("ApplicationUtils", "Unable to get application version: " + e.getMessage()); result = -1; } return result; } /** * Build the html result of the most recent bookmarks. * * @param context * The current context. * @return The html result of the most recent bookmarks. */ private static String getBookmarksHtml(Context context) { String result = ""; StringBuilder bookmarksSb = new StringBuilder(); if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( Constants.PREFERENCES_START_PAGE_SHOW_BOOKMARKS, true)) { int limit; try { limit = Integer .parseInt(PreferenceManager .getDefaultSharedPreferences(context) .getString( Constants.PREFERENCES_START_PAGE_BOOKMARKS_LIMIT, "5")); } catch (Exception e) { limit = 5; } List<BookmarkItem> results = BookmarksProviderWrapper .getStockBookmarksWithLimit(context.getContentResolver(), limit); for (BookmarkItem item : results) { bookmarksSb.append(String.format( "<li><a href=\"%s\">%s</a></li>", item.getUrl(), item.getTitle())); } } result = String.format(mRawStartPageBookmarks, context.getResources() .getString(R.string.StartPage_Bookmarks), bookmarksSb .toString()); return result; } /** * Load the changelog string. * * @param context * The current context. * @return The changelog string. */ public static String getChangelogString(Context context) { return getStringFromRawResource(context, R.raw.changelog); } /** * Get the required size of the favicon, depending on current screen * density. * * @param activity * The current activity. * @return The size of the favicon, in pixels. */ public static int getFaviconSize(Activity activity) { if (mFaviconSize == -1) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); switch (metrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: mFaviconSize = 12; break; case DisplayMetrics.DENSITY_MEDIUM: mFaviconSize = 24; break; case DisplayMetrics.DENSITY_HIGH: mFaviconSize = 32; break; default: mFaviconSize = 24; } } return mFaviconSize; } /** * Get the required size of the favicon, depending on current screen * density. * * @param activity * The current activity. * @return The size of the favicon, in pixels. */ public static int getFaviconSizeForBookmarks(Activity activity) { if (mFaviconSizeForBookmarks == -1) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); switch (metrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: mFaviconSizeForBookmarks = 12; break; case DisplayMetrics.DENSITY_MEDIUM: mFaviconSizeForBookmarks = 16; break; case DisplayMetrics.DENSITY_HIGH: mFaviconSizeForBookmarks = 24; break; default: mFaviconSizeForBookmarks = 16; } } return mFaviconSizeForBookmarks; } /** * Build the html result of the most recent history. * * @param context * The current context. * @return The html result of the most recent history. */ private static String getHistoryHtml(Context context) { String result = ""; StringBuilder historySb = new StringBuilder(); if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( Constants.PREFERENCES_START_PAGE_SHOW_HISTORY, true)) { int limit; try { limit = Integer.parseInt(PreferenceManager .getDefaultSharedPreferences(context).getString( Constants.PREFERENCES_START_PAGE_HISTORY_LIMIT, "5")); } catch (Exception e) { limit = 5; } List<HistoryItem> results = BookmarksProviderWrapper .getStockHistoryWithLimit(context.getContentResolver(), limit); for (HistoryItem item : results) { historySb.append(String.format( "<li><a href=\"%s\">%s</a></li>", item.getUrl(), item.getTitle())); } } result = String.format(mRawStartPageHistory, context.getResources() .getString(R.string.StartPage_History), historySb.toString()); return result; } public static int getImageButtonSize(Activity activity) { if (mImageButtonSize == -1) { DisplayMetrics metrics = new DisplayMetrics(); activity.getWindowManager().getDefaultDisplay().getMetrics(metrics); switch (metrics.densityDpi) { case DisplayMetrics.DENSITY_LOW: mImageButtonSize = 16; break; case DisplayMetrics.DENSITY_MEDIUM: mImageButtonSize = 32; break; case DisplayMetrics.DENSITY_HIGH: mImageButtonSize = 48; break; default: mImageButtonSize = 32; } } return mImageButtonSize; } /** * Load the start page html. * * @param context * The current context. * @return The start page html. */ public static String getStartPage(Context context) { if (mRawStartPage == null) { mRawStartPage = getStringFromRawResource(context, R.raw.start); mRawStartPageStyles = getStringFromRawResource(context, R.raw.start_style); mRawStartPageBookmarks = getStringFromRawResource(context, R.raw.start_bookmarks); mRawStartPageHistory = getStringFromRawResource(context, R.raw.start_history); mRawStartPageSearch = getStringFromRawResource(context, R.raw.start_search); } String result = mRawStartPage; String bookmarksHtml = getBookmarksHtml(context); String historyHtml = getHistoryHtml(context); String searchHtml = ""; if (PreferenceManager.getDefaultSharedPreferences(context).getBoolean( Constants.PREFERENCES_START_PAGE_SHOW_SEARCH, false)) { searchHtml = String .format(mRawStartPageSearch, context.getResources().getString( R.string.StartPage_Search), context.getResources().getString( R.string.StartPage_SearchButton)); } String bodyHtml = searchHtml + bookmarksHtml + historyHtml; result = String .format(mRawStartPage, mRawStartPageStyles, context .getResources().getString(R.string.StartPage_Welcome), bodyHtml); return result; } /** * Load a raw string resource. * * @param context * The current context. * @param resourceId * The resource id. * @return The loaded string. */ private static String getStringFromRawResource(Context context, int resourceId) { String result = null; InputStream is = context.getResources().openRawResource(resourceId); if (is != null) { StringBuilder sb = new StringBuilder(); String line; try { BufferedReader reader = new BufferedReader( new InputStreamReader(is, "UTF-8")); while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } } catch (IOException e) { Log.w("ApplicationUtils", String.format( "Unable to load resource %s: %s", resourceId, e.getMessage())); } finally { try { is.close(); } catch (IOException e) { Log.w("ApplicationUtils", String.format( "Unable to load resource %s: %s", resourceId, e.getMessage())); } } result = sb.toString(); } else { result = ""; } return result; } public static String getWeaveAuthToken(Context context) { String server = PreferenceManager.getDefaultSharedPreferences(context) .getString(Constants.PREFERENCE_WEAVE_SERVER, Constants.WEAVE_DEFAULT_SERVER); String userName = PreferenceManager .getDefaultSharedPreferences(context).getString( Constants.PREFERENCE_WEAVE_USERNAME, null); String password = PreferenceManager .getDefaultSharedPreferences(context).getString( Constants.PREFERENCE_WEAVE_PASSWORD, null); String key = PreferenceManager.getDefaultSharedPreferences(context) .getString(Constants.PREFERENCE_WEAVE_KEY, null); boolean ok = (server != null) && (server.length() > 0) && (UrlUtils.isUrl(server)) && (userName != null) && (userName.length() > 0) && (password != null) && (password.length() > 0) && (key != null) && (key.length() > 0); if (ok) { return String.format(Constants.WEAVE_AUTH_TOKEN_SCHEME, key, password, userName, server); } else { return null; } } /** * Share a page. * * @param activity * The parent activity. * @param title * The page title. * @param url * The page url. */ public static void sharePage(Activity activity, String title, String url) { Intent shareIntent = new Intent(Intent.ACTION_SEND); shareIntent.setType("text/plain"); shareIntent.putExtra(Intent.EXTRA_TEXT, url); shareIntent.putExtra(Intent.EXTRA_SUBJECT, title); try { activity.startActivity(Intent.createChooser(shareIntent, activity.getString(R.string.Main_ShareChooserTitle))); } catch (android.content.ActivityNotFoundException ex) { // if no app handles it, do nothing } } /** * Display a continue / cancel dialog. * * @param context * The current context. * @param icon * The dialog icon. * @param title * The dialog title. * @param message * The dialog message. * @param onContinue * The dialog listener for the continue button. * @param onCancel * The dialog listener for the cancel button. */ public static void showContinueCancelDialog(Context context, int icon, String title, String message, DialogInterface.OnClickListener onContinue, DialogInterface.OnClickListener onCancel) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setIcon(icon); builder.setTitle(title); builder.setMessage(message); builder.setInverseBackgroundForced(true); builder.setPositiveButton( context.getResources().getString(R.string.Commons_Continue), onContinue); builder.setNegativeButton( context.getResources().getString(R.string.Commons_Cancel), onCancel); AlertDialog alert = builder.create(); alert.show(); } /** * Show an error dialog. * * @param context * The current context. * @param title * The title string id. * @param message * The message string id. */ public static void showErrorDialog(Context context, int title, int message) { new AlertDialog.Builder(context).setTitle(title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(message) .setPositiveButton(R.string.Commons_Ok, null).show(); } public static void showErrorDialog(Context context, int title, String message) { new AlertDialog.Builder(context).setTitle(title) .setIcon(android.R.drawable.ic_dialog_alert) .setMessage(message) .setPositiveButton(R.string.Commons_Ok, null).show(); } /** * Display a standard Ok / Cancel dialog. * * @param context * The current context. * @param icon * The dialog icon. * @param title * The dialog title. * @param message * The dialog message. * @param onYes * The dialog listener for the yes button. */ public static void showOkCancelDialog(Context context, int icon, String title, String message, DialogInterface.OnClickListener onYes) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setIcon(icon); builder.setTitle(title); builder.setMessage(message); builder.setInverseBackgroundForced(true); builder.setPositiveButton( context.getResources().getString(R.string.Commons_Ok), onYes); builder.setNegativeButton( context.getResources().getString(R.string.Commons_Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } /** * Display a standard Ok dialog. * * @param context * The current context. * @param icon * The dialog icon. * @param title * The dialog title. * @param message * The dialog message. */ public static void showOkDialog(Context context, int icon, String title, String message) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(false); builder.setIcon(icon); builder.setTitle(title); builder.setMessage(message); builder.setInverseBackgroundForced(true); builder.setPositiveButton( context.getResources().getString(R.string.Commons_Ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } /** * Display a standard yes / no dialog. * * @param context * The current context. * @param icon * The dialog icon. * @param title * The dialog title. * @param message * The dialog message. * @param onYes * The dialog listener for the yes button. */ public static void showYesNoDialog(Context context, int icon, int title, int message, DialogInterface.OnClickListener onYes) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setCancelable(true); builder.setIcon(icon); builder.setTitle(context.getResources().getString(title)); builder.setMessage(context.getResources().getString(message)); builder.setInverseBackgroundForced(true); builder.setPositiveButton( context.getResources().getString(R.string.Commons_Yes), onYes); builder.setNegativeButton( context.getResources().getString(R.string.Commons_No), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/ApplicationUtils.java
Java
gpl3
19,052
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.utils; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import android.os.Environment; /** * Utilities for I/O reading and writing. */ public class IOUtils { private static final String APPLICATION_FOLDER = "zirco"; private static final String DOWNLOAD_FOLDER = "downloads"; private static final String BOOKMARKS_EXPORT_FOLDER = "bookmarks-exports"; /** * Get the application folder on the SD Card. Create it if not present. * * @return The application folder. */ public static File getApplicationFolder() { File root = Environment.getExternalStorageDirectory(); if (root.canWrite()) { File folder = new File(root, APPLICATION_FOLDER); if (!folder.exists()) { folder.mkdir(); } return folder; } else { return null; } } /** * Get the application folder for bookmarks export. Create it if not * present. * * @return The application folder for bookmarks export. */ public static File getBookmarksExportFolder() { File root = getApplicationFolder(); if (root != null) { File folder = new File(root, BOOKMARKS_EXPORT_FOLDER); if (!folder.exists()) { folder.mkdir(); } return folder; } else { return null; } } /** * Get the application download folder on the SD Card. Create it if not * present. * * @return The application download folder. */ public static File getDownloadFolder() { File root = getApplicationFolder(); if (root != null) { File folder = new File(root, DOWNLOAD_FOLDER); if (!folder.exists()) { folder.mkdir(); } return folder; } else { return null; } } /** * Get the list of xml files in the bookmark export folder. * * @return The list of xml files in the bookmark export folder. */ public static List<String> getExportedBookmarksFileList() { List<String> result = new ArrayList<String>(); File folder = getBookmarksExportFolder(); if (folder != null) { FileFilter filter = new FileFilter() { @Override public boolean accept(File pathname) { if ((pathname.isFile()) && (pathname.getPath().endsWith(".xml"))) { return true; } return false; } }; File[] files = folder.listFiles(filter); for (File file : files) { result.add(file.getName()); } } Collections.sort(result, new Comparator<String>() { @Override public int compare(String arg0, String arg1) { return arg1.compareTo(arg0); } }); return result; } }
zyh3290-proxy
src/org/gaeproxy/zirco/utils/IOUtils.java
Java
gpl3
3,146
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.utils.Constants; import android.app.TabActivity; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Window; import android.view.WindowManager; import android.widget.TabHost; import android.widget.TabHost.OnTabChangeListener; /** * Combined bookmarks and history activity. */ public class BookmarksHistoryActivity extends TabActivity { @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Controller.getInstance().getPreferences() .getBoolean(Constants.PREFERENCES_SHOW_FULL_SCREEN, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_GENERAL_HIDE_TITLE_BARS, true)) { requestWindowFeature(Window.FEATURE_NO_TITLE); } setContentView(R.layout.bookmarks_history_activity); setTitle(R.string.BookmarksListActivity_Title); Resources res = getResources(); TabHost tabHost = getTabHost(); TabHost.TabSpec spec; Intent intent; // Bookmarks intent = new Intent().setClass(this, BookmarksListActivity.class); spec = tabHost .newTabSpec("bookmarks") .setIndicator(res.getString(R.string.Main_MenuShowBookmarks), res.getDrawable(R.drawable.ic_tab_bookmarks)) .setContent(intent); tabHost.addTab(spec); // History intent = new Intent().setClass(this, HistoryListActivity.class); spec = tabHost .newTabSpec("history") .setIndicator(res.getString(R.string.Main_MenuShowHistory), res.getDrawable(R.drawable.ic_tab_history)) .setContent(intent); tabHost.addTab(spec); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( Constants.PREFERENCE_USE_WEAVE, false)) { // Weave bookmarks intent = new Intent().setClass(this, WeaveBookmarksListActivity.class); spec = tabHost .newTabSpec("weave") .setIndicator( res.getString(R.string.WeaveBookmarksListActivity_Title), res.getDrawable(R.drawable.ic_tab_weave)) .setContent(intent); tabHost.addTab(spec); } tabHost.setCurrentTab(0); tabHost.setOnTabChangedListener(new OnTabChangeListener() { @Override public void onTabChanged(String tabId) { if (tabId.equals("bookmarks")) { setTitle(R.string.BookmarksListActivity_Title); } else if (tabId.equals("history")) { setTitle(R.string.HistoryListActivity_Title); } else if (tabId.equals("weave")) { setTitle(R.string.WeaveBookmarksListActivity_Title); } else { setTitle(R.string.ApplicationName); } } }); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/BookmarksHistoryActivity.java
Java
gpl3
3,578
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.emergent.android.weave.client.WeaveAccountInfo; import org.gaeproxy.R; import org.gaeproxy.zirco.model.DbAdapter; import org.gaeproxy.zirco.model.adapters.WeaveBookmarksCursorAdapter; import org.gaeproxy.zirco.model.items.WeaveBookmarkItem; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.providers.WeaveColumns; import org.gaeproxy.zirco.sync.ISyncListener; import org.gaeproxy.zirco.sync.WeaveSyncTask; import org.gaeproxy.zirco.ui.activities.preferences.WeavePreferencesActivity; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class WeaveBookmarksListActivity extends Activity implements ISyncListener { private class Clearer implements Runnable { private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); fillData(); } }; public Clearer() { new Thread(this).start(); } @Override public void run() { BookmarksProviderWrapper.clearWeaveBookmarks(getContentResolver()); mHandler.sendEmptyMessage(0); } } private static final int MENU_SYNC = Menu.FIRST; private static final int MENU_CLEAR = Menu.FIRST + 1; private static final int MENU_OPEN_IN_TAB = Menu.FIRST + 10; private static final int MENU_COPY_URL = Menu.FIRST + 11; private static final int MENU_SHARE = Menu.FIRST + 12; private static final String ROOT_FOLDER = "places"; private LinearLayout mNavigationView; private TextView mNavigationText; private ImageButton mNavigationBack; private ListView mListView; private Button mSetupButton; private Button mSyncButton; private View mEmptyView; private View mEmptyFolderView; private List<WeaveBookmarkItem> mNavigationList; private ProgressDialog mProgressDialog; private DbAdapter mDbAdapter; private Cursor mCursor = null; private WeaveSyncTask mSyncTask; private static final AtomicReference<AsyncTask<WeaveAccountInfo, Integer, Throwable>> mSyncThread = new AtomicReference<AsyncTask<WeaveAccountInfo, Integer, Throwable>>(); private void doClear() { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingBookmarks)); new Clearer(); // Reset last sync date. Editor lastSyncDateEditor = PreferenceManager .getDefaultSharedPreferences(this).edit(); lastSyncDateEditor.putLong(Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE, -1); lastSyncDateEditor.commit(); } private void doNavigationBack() { mNavigationList.remove(mNavigationList.size() - 1); if (mNavigationList.size() == 0) { mNavigationList.add(new WeaveBookmarkItem(getResources().getString( R.string.WeaveBookmarksListActivity_WeaveRootFolder), null, ROOT_FOLDER, true)); } fillData(); } private void doSync() { String authToken = ApplicationUtils.getWeaveAuthToken(this); if (authToken != null) { WeaveAccountInfo info = WeaveAccountInfo .createWeaveAccountInfo(authToken); mSyncTask = new WeaveSyncTask(this, this); mProgressDialog = new ProgressDialog(this); mProgressDialog.setIndeterminate(true); mProgressDialog.setTitle(R.string.WeaveSync_SyncTitle); mProgressDialog .setMessage(getString(R.string.WeaveSync_Connecting)); mProgressDialog.setCancelable(true); mProgressDialog.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { mSyncTask.cancel(true); } }); mProgressDialog.show(); boolean retVal = mSyncThread.compareAndSet(null, mSyncTask); if (retVal) { mSyncTask.execute(info); } } else { ApplicationUtils.showErrorDialog(this, R.string.Errors_WeaveSyncFailedTitle, R.string.Errors_WeaveAuthFailedMessage); } } private void fillData() { String[] from = { WeaveColumns.WEAVE_BOOKMARKS_TITLE, WeaveColumns.WEAVE_BOOKMARKS_URL }; int[] to = { R.id.BookmarkRow_Title, R.id.BookmarkRow_Url }; mCursor = BookmarksProviderWrapper.getWeaveBookmarksByParentId( getContentResolver(), mNavigationList.get(mNavigationList.size() - 1).getWeaveId()); ListAdapter adapter = new WeaveBookmarksCursorAdapter(this, R.layout.weave_bookmark_row, mCursor, from, to); if (adapter.isEmpty() && (mNavigationList.size() <= 1)) { mNavigationView.setVisibility(View.GONE); } else { mNavigationView.setVisibility(View.VISIBLE); } if (mNavigationList.size() > 1) { mNavigationBack.setEnabled(true); mListView.setEmptyView(mEmptyFolderView); } else { mNavigationBack.setEnabled(false); mListView.setEmptyView(mEmptyView); } mListView.setAdapter(adapter); setAnimation(); mNavigationText.setText(getNavigationText()); } private String getNavigationText() { StringBuilder sb = new StringBuilder(); for (WeaveBookmarkItem navigationItem : mNavigationList) { if (sb.length() != 0) { sb.append(" > "); } sb.append(navigationItem.getTitle()); } return sb.toString(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); WeaveBookmarkItem bookmarkItem = BookmarksProviderWrapper .getWeaveBookmarkById(getContentResolver(), info.id); switch (item.getItemId()) { case MENU_OPEN_IN_TAB: Intent i = new Intent(); i.putExtra(Constants.EXTRA_ID_NEW_TAB, true); i.putExtra(Constants.EXTRA_ID_URL, bookmarkItem.getUrl()); if (getParent() != null) { getParent().setResult(RESULT_OK, i); } else { setResult(RESULT_OK, i); } finish(); return true; case MENU_COPY_URL: ApplicationUtils.copyTextToClipboard(this, bookmarkItem.getUrl(), getString(R.string.Commons_UrlCopyToastMessage)); return true; case MENU_SHARE: ApplicationUtils.sharePage(this, bookmarkItem.getTitle(), bookmarkItem.getUrl()); return true; default: return super.onContextItemSelected(item); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.weave_bookmarks_list_activity); mNavigationView = (LinearLayout) findViewById(R.id.WeaveBookmarksNavigationView); mNavigationText = (TextView) findViewById(R.id.WeaveBookmarksNavigationText); mNavigationBack = (ImageButton) findViewById(R.id.WeaveBookmarksNavigationBack); mListView = (ListView) findViewById(R.id.WeaveBookmarksList); mNavigationBack.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doNavigationBack(); } }); mListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View v, int position, long id) { WeaveBookmarkItem selectedItem = BookmarksProviderWrapper .getWeaveBookmarkById(getContentResolver(), id); if (selectedItem != null) { if (selectedItem.isFolder()) { mNavigationList.add(selectedItem); fillData(); } else { String url = selectedItem.getUrl(); if (url != null) { Intent result = new Intent(); result.putExtra(Constants.EXTRA_ID_NEW_TAB, false); result.putExtra(Constants.EXTRA_ID_URL, url); if (getParent() != null) { getParent().setResult(RESULT_OK, result); } else { setResult(RESULT_OK, result); } finish(); } } } } }); mEmptyView = findViewById(R.id.WeaveBookmarksEmptyView); mEmptyFolderView = findViewById(R.id.WeaveBookmarksEmptyFolderView); // mListView.setEmptyView(mEmptyView); mSetupButton = (Button) findViewById(R.id.WeaveBookmarksEmptyViewSetupButton); mSetupButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { startActivity(new Intent(WeaveBookmarksListActivity.this, WeavePreferencesActivity.class)); } }); mSyncButton = (Button) findViewById(R.id.WeaveBookmarksEmptyViewSyncButton); mSyncButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { doSync(); } }); mNavigationList = new ArrayList<WeaveBookmarkItem>(); mNavigationList.add(new WeaveBookmarkItem(getResources().getString( R.string.WeaveBookmarksListActivity_WeaveRootFolder), null, ROOT_FOLDER, true)); mDbAdapter = new DbAdapter(this); mDbAdapter.open(); registerForContextMenu(mListView); fillData(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); long id = ((AdapterContextMenuInfo) menuInfo).id; if (id != -1) { WeaveBookmarkItem item = BookmarksProviderWrapper .getWeaveBookmarkById(getContentResolver(), id); if (!item.isFolder()) { menu.setHeaderTitle(item.getTitle()); menu.add(0, MENU_OPEN_IN_TAB, 0, R.string.BookmarksListActivity_MenuOpenInTab); menu.add(0, MENU_COPY_URL, 0, R.string.BookmarksHistoryActivity_MenuCopyLinkUrl); menu.add(0, MENU_SHARE, 0, R.string.Main_MenuShareLinkUrl); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.add(0, MENU_SYNC, 0, R.string.WeaveBookmarksListActivity_MenuSync); item.setIcon(R.drawable.ic_menu_sync); item = menu.add(0, MENU_CLEAR, 0, R.string.WeaveBookmarksListActivity_MenuClear); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override protected void onDestroy() { if (mCursor != null) { mCursor.close(); } mDbAdapter.close(); super.onDestroy(); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mNavigationList.size() > 1) { doNavigationBack(); return true; } else { return super.onKeyUp(keyCode, event); } default: return super.onKeyUp(keyCode, event); } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_SYNC: doSync(); return true; case MENU_CLEAR: doClear(); return true; default: return super.onMenuItemSelected(featureId, item); } } @Override public void onSyncCancelled() { mSyncThread.compareAndSet(mSyncTask, null); mProgressDialog.dismiss(); fillData(); if (mSyncTask.isFullSync()) { // Reset last sync date is this was a full sync. Editor lastSyncDateEditor = PreferenceManager .getDefaultSharedPreferences(this).edit(); lastSyncDateEditor.putLong( Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE, -1); lastSyncDateEditor.commit(); } } @Override public void onSyncEnd(Throwable result) { mSyncThread.compareAndSet(mSyncTask, null); if (result != null) { String msg = String.format( getResources().getString( R.string.Errors_WeaveSyncFailedMessage), result.getMessage()); Log.e("MainActivity: Sync failed.", msg); ApplicationUtils.showErrorDialog(this, R.string.Errors_WeaveSyncFailedTitle, msg); } else { Editor lastSyncDateEditor = PreferenceManager .getDefaultSharedPreferences(this).edit(); lastSyncDateEditor.putLong( Constants.PREFERENCE_WEAVE_LAST_SYNC_DATE, new Date().getTime()); lastSyncDateEditor.commit(); } mProgressDialog.dismiss(); fillData(); } @Override public void onSyncProgress(int step, int done, int total) { switch (step) { case 0: mProgressDialog .setMessage(getString(R.string.WeaveSync_Connecting)); break; case 1: mProgressDialog .setMessage(getString(R.string.WeaveSync_GettingData)); break; case 2: mProgressDialog.setMessage(String.format( getString(R.string.WeaveSync_ReadingData), done, total)); break; case 3: mProgressDialog .setMessage(getString(R.string.WeaveSync_WrittingData)); break; } } /** * Set the list loading animation. */ private void setAnimation() { AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(75); set.addAnimation(animation); animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setDuration(50); set.addAnimation(animation); LayoutAnimationController controller = new LayoutAnimationController( set, 0.5f); mListView.setLayoutAnimation(controller); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/WeaveBookmarksListActivity.java
Java
gpl3
14,541
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.utils.Constants; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; /** * Add / Edit bookmark activity. */ public class EditBookmarkActivity extends Activity { private EditText mTitleEditText; private EditText mUrlEditText; private Button mOkButton; private Button mCancelButton; private long mRowId = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.edit_bookmark_activity); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_input_add); mTitleEditText = (EditText) findViewById(R.id.EditBookmarkActivity_TitleValue); mUrlEditText = (EditText) findViewById(R.id.EditBookmarkActivity_UrlValue); mOkButton = (Button) findViewById(R.id.EditBookmarkActivity_BtnOk); mCancelButton = (Button) findViewById(R.id.EditBookmarkActivity_BtnCancel); mOkButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setAsBookmark(); setResult(RESULT_OK); finish(); } }); mCancelButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); Bundle extras = getIntent().getExtras(); if (extras != null) { String title = extras.getString(Constants.EXTRA_ID_BOOKMARK_TITLE); if ((title != null) && (title.length() > 0)) { mTitleEditText.setText(title); } String url = extras.getString(Constants.EXTRA_ID_BOOKMARK_URL); if ((url != null) && (url.length() > 0)) { mUrlEditText.setText(url); } else { mUrlEditText.setHint("http://"); } mRowId = extras.getLong(Constants.EXTRA_ID_BOOKMARK_ID); } if (mRowId == -1) { setTitle(R.string.EditBookmarkActivity_TitleAdd); } } /** * Set the current title and url values as a bookmark, e.g. adding a record * if necessary or set only the bookmark flag. */ private void setAsBookmark() { BookmarksProviderWrapper.setAsBookmark(getContentResolver(), mRowId, mTitleEditText.getText().toString(), mUrlEditText.getText() .toString(), true); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/EditBookmarkActivity.java
Java
gpl3
3,019
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.events.EventConstants; import org.gaeproxy.zirco.events.EventController; import org.gaeproxy.zirco.events.IDownloadEventsListener; import org.gaeproxy.zirco.model.adapters.DownloadListAdapter; import org.gaeproxy.zirco.model.items.DownloadItem; import android.app.ListActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; /** * Download list activity. */ public class DownloadsListActivity extends ListActivity implements IDownloadEventsListener { private static final int MENU_CLEAR_DOWNLOADS = Menu.FIRST; private DownloadListAdapter mAdapter; /** * Fill the download list. */ private void fillData() { mAdapter = new DownloadListAdapter(this, Controller.getInstance() .getDownloadList()); setListAdapter(mAdapter); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.downloads_list_activity); setTitle(R.string.DownloadListActivity_Title); EventController.getInstance().addDownloadListener(this); fillData(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item = menu.add(0, MENU_CLEAR_DOWNLOADS, 0, R.string.DownloadListActivity_RemoveCompletedDownloads); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override protected void onDestroy() { EventController.getInstance().removeDownloadListener(this); super.onDestroy(); } @Override public void onDownloadEvent(String event, Object data) { if (event.equals(EventConstants.EVT_DOWNLOAD_ON_START)) { fillData(); } else if (event.equals(EventConstants.EVT_DOWNLOAD_ON_PROGRESS)) { if (data != null) { DownloadItem item = (DownloadItem) data; ProgressBar bar = mAdapter.getBarMap().get(item); if (bar != null) { bar.setMax(100); bar.setProgress(item.getProgress()); } } } else if (event.equals(EventConstants.EVT_DOWNLOAD_ON_FINISHED)) { if (data != null) { DownloadItem item = (DownloadItem) data; TextView title = mAdapter.getTitleMap().get(item); if (title != null) { if (item.isAborted()) { title.setText(String.format( getResources().getString( R.string.DownloadListActivity_Aborted), item.getFileName())); } else { title.setText(String .format(getResources().getString( R.string.DownloadListActivity_Finished), item.getFileName())); } } ProgressBar bar = mAdapter.getBarMap().get(item); if (bar != null) { bar.setProgress(bar.getMax()); } ImageButton button = mAdapter.getButtonMap().get(item); if (button != null) { button.setEnabled(false); } } } } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_CLEAR_DOWNLOADS: Controller.getInstance().clearCompletedDownloads(); fillData(); return true; default: return super.onMenuItemSelected(featureId, item); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/DownloadsListActivity.java
Java
gpl3
3,814
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.model.adapters.HistoryExpandableListAdapter; import org.gaeproxy.zirco.model.items.HistoryItem; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.ui.components.CustomWebView; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import android.app.ExpandableListActivity; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.provider.Browser; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ExpandableListView.ExpandableListContextMenuInfo; /** * history list activity. */ public class HistoryListActivity extends ExpandableListActivity { /** * Runnable to clear history. */ private class HistoryClearer implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); fillData(); } }; /** * Constructor. */ public HistoryClearer() { new Thread(this).start(); } @Override public void run() { BookmarksProviderWrapper.clearHistoryAndOrBookmarks(getContentResolver(), true, false); for (CustomWebView webView : Controller.getInstance().getWebViewList()) { webView.clearHistory(); } handler.sendEmptyMessage(0); } } private static final int MENU_CLEAR_HISTORY = Menu.FIRST; private static final int MENU_OPEN_IN_TAB = Menu.FIRST + 10; private static final int MENU_COPY_URL = Menu.FIRST + 11; private static final int MENU_SHARE = Menu.FIRST + 12; private static final int MENU_DELETE_FROM_HISTORY = Menu.FIRST + 13; private ExpandableListAdapter mAdapter; private ProgressDialog mProgressDialog; /** * Display confirmation and clear history. */ private void clearHistory() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.Commons_ClearHistory, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearHistory(); } }); } /** * Clear history. */ private void doClearHistory() { mProgressDialog = ProgressDialog.show(this, this.getResources().getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingHistory)); new HistoryClearer(); } /** * Load the given url. * * @param url * The url. * @param newTab * If True, will open a new tab. If False, the current tab is * used. */ private void doNavigateToUrl(String url, boolean newTab) { Intent result = new Intent(); result.putExtra(Constants.EXTRA_ID_NEW_TAB, newTab); result.putExtra(Constants.EXTRA_ID_URL, url); if (getParent() != null) { getParent().setResult(RESULT_OK, result); } else { setResult(RESULT_OK, result); } finish(); } /** * Fill the history list. */ private void fillData() { Cursor c = BookmarksProviderWrapper.getStockHistory(getContentResolver()); if (c == null) return; mAdapter = new HistoryExpandableListAdapter(this, c, Browser.HISTORY_PROJECTION_DATE_INDEX, ApplicationUtils.getFaviconSizeForBookmarks(this)); setListAdapter(mAdapter); if (getExpandableListAdapter().getGroupCount() > 0) { getExpandableListView().expandGroup(0); } } @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { HistoryItem item = (HistoryItem) getExpandableListAdapter().getChild(groupPosition, childPosition); doNavigateToUrl(item.getUrl(), false); return super.onChildClick(parent, v, groupPosition, childPosition, id); } @Override public boolean onContextItemSelected(MenuItem menuItem) { ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo) menuItem.getMenuInfo(); int type = ExpandableListView.getPackedPositionType(info.packedPosition); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { int group = ExpandableListView.getPackedPositionGroup(info.packedPosition); int child = ExpandableListView.getPackedPositionChild(info.packedPosition); HistoryItem item = (HistoryItem) getExpandableListAdapter().getChild(group, child); switch (menuItem.getItemId()) { case MENU_OPEN_IN_TAB: doNavigateToUrl(item.getUrl(), true); break; case MENU_COPY_URL: ApplicationUtils.copyTextToClipboard(this, item.getUrl(), getString(R.string.Commons_UrlCopyToastMessage)); break; case MENU_SHARE: ApplicationUtils.sharePage(this, item.getTitle(), item.getUrl()); break; case MENU_DELETE_FROM_HISTORY: BookmarksProviderWrapper.deleteHistoryRecord(getContentResolver(), item.getId()); fillData(); break; default: break; } } return super.onContextItemSelected(menuItem); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.HistoryListActivity_Title); registerForContextMenu(getExpandableListView()); fillData(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); ExpandableListView.ExpandableListContextMenuInfo info = (ExpandableListView.ExpandableListContextMenuInfo) menuInfo; int type = ExpandableListView.getPackedPositionType(info.packedPosition); int group = ExpandableListView.getPackedPositionGroup(info.packedPosition); int child = ExpandableListView.getPackedPositionChild(info.packedPosition); if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) { HistoryItem item = (HistoryItem) getExpandableListAdapter().getChild(group, child); menu.setHeaderTitle(item.getTitle()); menu.add(0, MENU_OPEN_IN_TAB, 0, R.string.HistoryListActivity_MenuOpenInTab); menu.add(0, MENU_COPY_URL, 0, R.string.BookmarksHistoryActivity_MenuCopyLinkUrl); menu.add(0, MENU_SHARE, 0, R.string.Main_MenuShareLinkUrl); menu.add(0, MENU_DELETE_FROM_HISTORY, 0, R.string.HistoryListActivity_MenuDelete); } } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item; item = menu.add(0, MENU_CLEAR_HISTORY, 0, R.string.Commons_ClearHistory); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_CLEAR_HISTORY: clearHistory(); return true; default: return super.onMenuItemSelected(featureId, item); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/HistoryListActivity.java
Java
gpl3
7,636
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; /** * Interface defining a tool bar container. */ public interface IToolbarsContainer { /** * Hide the tool bars of this item. */ void hideToolbars(); }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/IToolbarsContainer.java
Java
gpl3
741
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.ApplicationUtils; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; /** * Changelog dialog activity. */ public class ChangelogActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.changelog_activity); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); TextView changelogText = (TextView) findViewById(R.id.ChangelogContent); changelogText.setText(ApplicationUtils.getChangelogString(this)); Button closeBtn = (Button) this .findViewById(R.id.ChangelogActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/ChangelogActivity.java
Java
gpl3
1,607
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.model.DbAdapter; import org.gaeproxy.zirco.utils.ApplicationUtils; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.text.InputType; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; /** * AdBlocker white list activity. */ public class MobileViewListActivity extends ListActivity { private static final int MENU_ADD = Menu.FIRST; private static final int MENU_CLEAR = Menu.FIRST + 1; private static final int MENU_DELETE = Menu.FIRST + 10; private Cursor mCursor; private DbAdapter mDbAdapter; private SimpleCursorAdapter mCursorAdapter; /** * Build and show a dialog for user input. Add user input to the white list. */ private void addToMobileViewList() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(android.R.drawable.ic_input_add); builder.setTitle(getResources().getString( R.string.MobileViewListActivity_AddMessage)); builder.setInverseBackgroundForced(true); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_TEXT_VARIATION_URI); builder.setView(input); builder.setInverseBackgroundForced(true); builder.setPositiveButton( getResources().getString(R.string.Commons_Ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doAddToMobileViewList(input.getText().toString()); } }); builder.setNegativeButton( getResources().getString(R.string.Commons_Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } /** * Display a confirmation dialog and clear the white list. */ private void clearMobileViewList() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.MobileViewListActivity_ClearMessage, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearMobileViewList(); } }); } /** * Add a value to the white list. * * @param value * The value to add. */ private void doAddToMobileViewList(String value) { mDbAdapter.insertInMobileViewUrlList(value); Controller.getInstance().resetMobileViewUrlList(); fillData(); } /** * Clear the white list. */ private void doClearMobileViewList() { mDbAdapter.clearMobileViewUrlList(); Controller.getInstance().resetMobileViewUrlList(); fillData(); } /** * Fill the list view. */ private void fillData() { mCursor = mDbAdapter.getMobileViewUrlCursor(); startManagingCursor(mCursor); String[] from = new String[] { DbAdapter.MOBILE_VIEW_URL_URL }; int[] to = new int[] { R.id.MobileViewListRow_Title }; mCursorAdapter = new SimpleCursorAdapter(this, R.layout.mobile_view_list_row, mCursor, from, to); setListAdapter(mCursorAdapter); setAnimation(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); switch (item.getItemId()) { case MENU_DELETE: mDbAdapter.deleteFromMobileViewUrlList(info.id); Controller.getInstance().resetMobileViewUrlList(); fillData(); return true; default: return super.onContextItemSelected(item); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.mobile_view_list_activity); setTitle(R.string.MobileViewListActivity_Title); mDbAdapter = new DbAdapter(this); mDbAdapter.open(); registerForContextMenu(getListView()); fillData(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); long id = ((AdapterContextMenuInfo) menuInfo).id; if (id != -1) { menu.setHeaderTitle(mDbAdapter.getMobileViewUrlItemById(id)); } menu.add(0, MENU_DELETE, 0, R.string.Commons_Delete); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item; item = menu.add(0, MENU_ADD, 0, R.string.Commons_Add); item.setIcon(R.drawable.ic_menu_add); item = menu.add(0, MENU_CLEAR, 0, R.string.Commons_Clear); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override protected void onDestroy() { mDbAdapter.close(); mCursor.close(); super.onDestroy(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_ADD: addToMobileViewList(); return true; case MENU_CLEAR: clearMobileViewList(); return true; default: return super.onMenuItemSelected(featureId, item); } } /** * Set the view loading animation. */ private void setAnimation() { AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(100); set.addAnimation(animation); animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setDuration(100); set.addAnimation(animation); LayoutAnimationController controller = new LayoutAnimationController( set, 0.5f); ListView listView = getListView(); listView.setLayoutAnimation(controller); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/MobileViewListActivity.java
Java
gpl3
6,939
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import android.app.Activity; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.TextView; /** * About dialog activity. */ public class AboutActivity extends Activity { /** * Get the current package version. * * @return The current version. */ private String getVersion() { String result = ""; try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); result = String.format("%s (%s)", info.versionName, info.versionCode); } catch (NameNotFoundException e) { Log.w(AboutActivity.class.toString(), "Unable to get application version: " + e.getMessage()); result = "Unable to get application version."; } return result; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.about_activity); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_info); TextView versionText = (TextView) this .findViewById(R.id.AboutActivity_VersionText); versionText.setText(this.getString(R.string.AboutActivity_VersionText) + " " + getVersion()); TextView licenseText = (TextView) this .findViewById(R.id.AboutActivity_LicenseText); licenseText .setText(this.getString(R.string.AboutActivity_LicenseText) + " " + this.getString(R.string.AboutActivity_LicenseTextValue)); TextView urlText = (TextView) this .findViewById(R.id.AboutActivity_UrlText); urlText.setText(this.getString(R.string.AboutActivity_UrlTextValue)); Button closeBtn = (Button) this .findViewById(R.id.AboutActivity_CloseBtn); closeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/AboutActivity.java
Java
gpl3
2,737
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.Constants; import android.content.SharedPreferences.Editor; import android.preference.PreferenceManager; /** * User agent preference chooser activity. */ public class UserAgentPreferenceActivity extends BaseSpinnerCustomPreferenceActivity { @Override protected int getSpinnerPromptId() { return R.string.UserAgentPreferenceActivity_Prompt; } @Override protected int getSpinnerValuesArrayId() { return R.array.UserAgentValues; } @Override protected void onOk() { Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putString(Constants.PREFERENCES_BROWSER_USER_AGENT, mCustomEditText.getText().toString()); editor.commit(); } @Override protected void onSpinnerItemSelected(int position) { switch (position) { case 0: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.USER_AGENT_DEFAULT); break; case 1: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.USER_AGENT_DESKTOP); break; case 2: { mCustomEditText.setEnabled(true); if ((mCustomEditText.getText().toString() .equals(Constants.USER_AGENT_DEFAULT)) || (mCustomEditText.getText().toString() .equals(Constants.USER_AGENT_DESKTOP))) { mCustomEditText.setText(null); } break; } default: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.USER_AGENT_DEFAULT); break; } } @Override protected void setSpinnerValueFromPreferences() { String currentUserAgent = PreferenceManager .getDefaultSharedPreferences(this).getString( Constants.PREFERENCES_BROWSER_USER_AGENT, Constants.USER_AGENT_DEFAULT); if (currentUserAgent.equals(Constants.USER_AGENT_DEFAULT)) { mSpinner.setSelection(0); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.USER_AGENT_DEFAULT); } else if (currentUserAgent.equals(Constants.USER_AGENT_DESKTOP)) { mSpinner.setSelection(1); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.USER_AGENT_DESKTOP); } else { mSpinner.setSelection(2); mCustomEditText.setEnabled(true); mCustomEditText.setText(currentUserAgent); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/UserAgentPreferenceActivity.java
Java
gpl3
2,830
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import java.util.List; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.ui.activities.AboutActivity; import org.gaeproxy.zirco.ui.activities.AdBlockerWhiteListActivity; import org.gaeproxy.zirco.ui.activities.ChangelogActivity; import org.gaeproxy.zirco.ui.activities.MainActivity; import org.gaeproxy.zirco.ui.activities.MobileViewListActivity; import org.gaeproxy.zirco.ui.components.CustomWebView; import org.gaeproxy.zirco.ui.runnables.XmlHistoryBookmarksExporter; import org.gaeproxy.zirco.ui.runnables.XmlHistoryBookmarksImporter; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import org.gaeproxy.zirco.utils.DateUtils; import org.gaeproxy.zirco.utils.IOUtils; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceManager; import android.webkit.CookieManager; /** * Preferences activity. */ public class PreferencesActivity extends PreferenceActivity { /** * Base class for all clear operations launched as Runnable. */ private abstract class AbstractClearer implements Runnable { protected Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); } }; /** * Constructor. Launch itself as a Thread. */ public AbstractClearer() { new Thread(this).start(); } } /** * Cache clearer thread. */ private class CacheClearer implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); } }; /** * Constructor. */ public CacheClearer() { new Thread(this).start(); } @Override public void run() { // Only need to clear the cache from one WebView, as it is // application-based. CustomWebView webView = Controller.getInstance().getWebViewList() .get(0); webView.clearCache(true); handler.sendEmptyMessage(0); } } /** * Cookies clearer thread. */ private class CookiesClearer implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); } }; /** * Constructor. */ public CookiesClearer() { new Thread(this).start(); } @Override public void run() { CookieManager.getInstance().removeAllCookie(); handler.sendEmptyMessage(0); } } /** * Form data clearer thread. */ private class FormDataClearer implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); } }; /** * Constructor. */ public FormDataClearer() { new Thread(this).start(); } @Override public void run() { for (CustomWebView webView : Controller.getInstance() .getWebViewList()) { webView.clearFormData(); } handler.sendEmptyMessage(0); } } private class HistoryBookmarksClearer extends AbstractClearer { private int mChoice; public HistoryBookmarksClearer(int choice) { mChoice = choice; } @Override public void run() { switch (mChoice) { case 0: BookmarksProviderWrapper.clearHistoryAndOrBookmarks( PreferencesActivity.this.getContentResolver(), true, false); break; case 1: BookmarksProviderWrapper.clearHistoryAndOrBookmarks( PreferencesActivity.this.getContentResolver(), false, true); break; case 2: BookmarksProviderWrapper.clearHistoryAndOrBookmarks( PreferencesActivity.this.getContentResolver(), true, true); break; default: break; } mHandler.sendEmptyMessage(0); } } /** * History clearer thread. */ private class HistoryClearer implements Runnable { private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { mProgressDialog.dismiss(); } }; /** * Constructor. */ public HistoryClearer() { new Thread(this).start(); } @Override public void run() { // Clear DB History BookmarksProviderWrapper.clearHistoryAndOrBookmarks( getContentResolver(), true, false); // Clear WebViews history for (CustomWebView webView : Controller.getInstance() .getWebViewList()) { webView.clearHistory(); } handler.sendEmptyMessage(0); } } private ProgressDialog mProgressDialog; private OnSharedPreferenceChangeListener mPreferenceChangeListener; /** * Ask user to restart the app. Do it if click on "Yes". */ private void askForRestart() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.PreferencesActivity_RestartDialogTitle, R.string.PreferencesActivity_RestartDialogMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { MainActivity.INSTANCE.restartApplication(); } }); } /** * Display confirmation and clear the cache. */ private void clearCache() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.Commons_ClearCache, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearCache(); } }); } /** * Display confirmation and clear cookies. */ private void clearCookies() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.Commons_ClearCookies, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearCookies(); } }); } /** * Display confirmation and clear form data. */ private void clearFormData() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.Commons_ClearFormData, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearFormData(); } }); } /** * Display confirmation and clear the history. */ private void clearHistory() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.Commons_ClearHistory, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearHistory(); } }); } /** * Clear the history. */ private void clearHistoryBookmarks() { final String[] choices = new String[] { getString(R.string.Commons_History), getString(R.string.Commons_Bookmarks), getString(R.string.Commons_All) }; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setInverseBackgroundForced(true); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(R.string.Commons_ClearHistoryBookmarks); builder.setSingleChoiceItems(choices, 0, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doClearHistoryBookmarks(which); dialog.dismiss(); } }); builder.setCancelable(true); builder.setNegativeButton(R.string.Commons_Cancel, null); AlertDialog alert = builder.create(); alert.show(); } /** * Clear the cache. */ private void doClearCache() { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingCache)); new CacheClearer(); } /** * Clear cookies. */ private void doClearCookies() { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingCookies)); new CookiesClearer(); } /** * Clear form data. */ private void doClearFormData() { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingFormData)); new FormDataClearer(); } /** * Clear the history. */ private void doClearHistory() { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingHistory)); new HistoryClearer(); } private void doClearHistoryBookmarks(int choice) { mProgressDialog = ProgressDialog.show(this, this.getResources() .getString(R.string.Commons_PleaseWait), this.getResources() .getString(R.string.Commons_ClearingHistoryBookmarks)); new HistoryBookmarksClearer(choice); } /** * Export the bookmarks and history. */ private void doExportHistoryBookmarks() { if (ApplicationUtils.checkCardState(this, true)) { mProgressDialog = ProgressDialog.show( this, this.getResources().getString(R.string.Commons_PleaseWait), this.getResources().getString( R.string.Commons_ExportingHistoryBookmarks)); XmlHistoryBookmarksExporter exporter = new XmlHistoryBookmarksExporter( this, DateUtils.getNowForFileName() + ".xml", BookmarksProviderWrapper.getAllStockRecords(this .getContentResolver()), mProgressDialog); new Thread(exporter).start(); } } /** * Import the given file to bookmarks and history. * * @param fileName * The file to import. */ private void doImportHistoryBookmarks(String fileName) { if (ApplicationUtils.checkCardState(this, true)) { mProgressDialog = ProgressDialog.show( this, this.getResources().getString(R.string.Commons_PleaseWait), this.getResources().getString( R.string.Commons_ImportingHistoryBookmarks)); XmlHistoryBookmarksImporter importer = new XmlHistoryBookmarksImporter( this, fileName, mProgressDialog); new Thread(importer).start(); } } /** * Ask the user to confirm the export. Launch it if confirmed. */ private void exportHistoryBookmarks() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_info, R.string.Commons_HistoryBookmarksExportSDCardConfirmation, R.string.Commons_OperationCanBeLongMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doExportHistoryBookmarks(); } }); } /** * Ask the user the file to import to bookmarks and history, and launch the * import. */ private void importHistoryBookmarks() { List<String> exportedFiles = IOUtils.getExportedBookmarksFileList(); final String[] choices = exportedFiles.toArray(new String[exportedFiles .size()]); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setInverseBackgroundForced(true); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString( R.string.Commons_ImportHistoryBookmarksSource)); builder.setSingleChoiceItems(choices, 0, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doImportHistoryBookmarks(choices[which]); dialog.dismiss(); } }); builder.setCancelable(true); builder.setNegativeButton(R.string.Commons_Cancel, null); AlertDialog alert = builder.create(); alert.show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.preferences_activity); PreferenceCategory browserPreferenceCategory = (PreferenceCategory) findPreference("BrowserPreferenceCategory"); Preference enablePluginsEclair = findPreference(Constants.PREFERENCES_BROWSER_ENABLE_PLUGINS_ECLAIR); Preference enablePlugins = findPreference(Constants.PREFERENCES_BROWSER_ENABLE_PLUGINS); if (Build.VERSION.SDK_INT <= 7) { browserPreferenceCategory.removePreference(enablePlugins); } else { browserPreferenceCategory.removePreference(enablePluginsEclair); } Preference userAgentPref = findPreference(Constants.PREFERENCES_BROWSER_USER_AGENT); userAgentPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openUserAgentActivity(); return true; } }); Preference fullScreenPref = findPreference(Constants.PREFERENCES_SHOW_FULL_SCREEN); fullScreenPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { askForRestart(); return true; } }); Preference hideTitleBarPref = findPreference(Constants.PREFERENCES_GENERAL_HIDE_TITLE_BARS); hideTitleBarPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { askForRestart(); return true; } }); Preference searchUrlPref = findPreference(Constants.PREFERENCES_GENERAL_SEARCH_URL); searchUrlPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openSearchUrlActivity(); return true; } }); Preference homepagePref = findPreference(Constants.PREFERENCES_GENERAL_HOME_PAGE); homepagePref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openHomepageActivity(); return true; } }); Preference weaveServerPref = findPreference(Constants.PREFERENCE_WEAVE_SERVER); weaveServerPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openWeaveServerActivity(); return true; } }); Preference aboutPref = findPreference("About"); aboutPref.setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openAboutActivity(); return true; } }); Preference changelogPref = findPreference("Changelog"); changelogPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openChangelogActivity(); return true; } }); Preference mobileViewPref = findPreference("MobileViewList"); mobileViewPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openMobileViewListActivity(); return true; } }); Preference whiteListPref = findPreference("AdBlockerWhiteList"); whiteListPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openWhiteListActivity(); return true; } }); Preference clearHistoryPref = findPreference("PrivacyClearHistory"); clearHistoryPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clearHistory(); return true; } }); Preference clearformDataPref = findPreference("PrivacyClearFormData"); clearformDataPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clearFormData(); return true; } }); Preference clearCachePref = findPreference("PrivacyClearCache"); clearCachePref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clearCache(); return true; } }); Preference clearCookiesPref = findPreference("PrivacyClearCookies"); clearCookiesPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clearCookies(); return true; } }); Preference exportHistoryBookmarksPref = findPreference("ExportHistoryBookmarks"); exportHistoryBookmarksPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { exportHistoryBookmarks(); return true; } }); Preference importHistoryBookmarksPref = findPreference("ImportHistoryBookmarks"); importHistoryBookmarksPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { importHistoryBookmarks(); return true; } }); Preference clearHistoryBookmarksPref = findPreference("ClearHistoryBookmarks"); clearHistoryBookmarksPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { clearHistoryBookmarks(); return true; } }); mPreferenceChangeListener = new OnSharedPreferenceChangeListener() { @Override public void onSharedPreferenceChanged( SharedPreferences sharedPreferences, String key) { MainActivity.INSTANCE.applyPreferences(); } }; PreferenceManager.getDefaultSharedPreferences(this) .registerOnSharedPreferenceChangeListener( mPreferenceChangeListener); } /** * Display the about dialog. */ private void openAboutActivity() { Intent i = new Intent(this, AboutActivity.class); startActivity(i); } /** * Display the changelog dialog. */ private void openChangelogActivity() { Intent i = new Intent(this, ChangelogActivity.class); startActivity(i); } /** * Display the homepage preference dialog. */ private void openHomepageActivity() { Intent i = new Intent(this, HomepagePreferenceActivity.class); startActivity(i); } /** * Display the mobile view list activity. */ private void openMobileViewListActivity() { Intent i = new Intent(this, MobileViewListActivity.class); startActivity(i); } /** * Display the search url preference dialog. */ private void openSearchUrlActivity() { Intent i = new Intent(this, SearchUrlPreferenceActivity.class); startActivity(i); } /** * Display the user agent preference dialog. */ private void openUserAgentActivity() { Intent i = new Intent(this, UserAgentPreferenceActivity.class); startActivity(i); } private void openWeaveServerActivity() { Intent i = new Intent(this, WeaveServerPreferenceActivity.class); startActivity(i); } /** * Display the ad blocker white list activity. */ private void openWhiteListActivity() { Intent i = new Intent(this, AdBlockerWhiteListActivity.class); startActivity(i); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/PreferencesActivity.java
Java
gpl3
20,304
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.Constants; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; /** * Search url preference chooser activity. */ public class SearchUrlPreferenceActivity extends BaseSpinnerCustomPreferenceActivity { @Override protected int getSpinnerPromptId() { return R.string.SearchUrlPreferenceActivity_Prompt; } @Override protected int getSpinnerValuesArrayId() { return R.array.SearchUrlValues; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onOk() { Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putString(Constants.PREFERENCES_GENERAL_SEARCH_URL, mCustomEditText.getText().toString()); editor.commit(); } @Override protected void onSpinnerItemSelected(int position) { switch (position) { case 0: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_SEARCH_GOOGLE); break; case 1: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_SEARCH_WIKIPEDIA); break; case 2: { mCustomEditText.setEnabled(true); if ((mCustomEditText.getText().toString() .equals(Constants.URL_SEARCH_GOOGLE)) || (mCustomEditText.getText().toString() .equals(Constants.URL_SEARCH_WIKIPEDIA))) { mCustomEditText.setText(null); } break; } default: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_SEARCH_GOOGLE); break; } } @Override protected void setSpinnerValueFromPreferences() { String currentSearchUrl = PreferenceManager .getDefaultSharedPreferences(this).getString( Constants.PREFERENCES_GENERAL_SEARCH_URL, Constants.URL_SEARCH_GOOGLE); if (currentSearchUrl.equals(Constants.URL_SEARCH_GOOGLE)) { mSpinner.setSelection(0); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_SEARCH_GOOGLE); } else if (currentSearchUrl.equals(Constants.URL_SEARCH_WIKIPEDIA)) { mSpinner.setSelection(1); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_SEARCH_WIKIPEDIA); } else { mSpinner.setSelection(2); mCustomEditText.setEnabled(true); mCustomEditText.setText(currentSearchUrl); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/SearchUrlPreferenceActivity.java
Java
gpl3
2,965
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; /** * Base class for a dialog activity for a preference which can have several * predefined values, and a customizable one. */ public abstract class BaseSpinnerCustomPreferenceActivity extends Activity { protected Spinner mSpinner; protected EditText mCustomEditText; /** * Get the resource id for the prompt of the spinner. * * @return The resource id. */ protected abstract int getSpinnerPromptId(); /** * Get the resource id for the array values of the spinner. * * @return The array id. */ protected abstract int getSpinnerValuesArrayId(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window w = getWindow(); w.requestFeature(Window.FEATURE_LEFT_ICON); setContentView(R.layout.base_spinner_custom_preference_activity); w.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_map); mCustomEditText = (EditText) findViewById(R.id.BaseSpinnerCustomPreferenceEditText); mSpinner = (Spinner) findViewById(R.id.BaseSpinnerCustomPreferenceSpinner); mSpinner.setPromptId(getSpinnerPromptId()); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, getSpinnerValuesArrayId(), android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mSpinner.setAdapter(adapter); setSpinnerValueFromPreferences(); mSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { onSpinnerItemSelected(position); } @Override public void onNothingSelected(AdapterView<?> arg0) { } }); Button okBtn = (Button) findViewById(R.id.BaseSpinnerCustomPreferenceOk); okBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { onOk(); finish(); } }); Button cancelBtn = (Button) findViewById(R.id.BaseSpinnerCustomPreferenceCancel); cancelBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); } /** * Behavior when the user press the Ok button. */ protected abstract void onOk(); /** * Behavior when the spinner selected item change. * * @param position * The new selected index. */ protected abstract void onSpinnerItemSelected(int position); /** * Initialize the spinner with the current value in preferences. */ protected abstract void setSpinnerValueFromPreferences(); }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/BaseSpinnerCustomPreferenceActivity.java
Java
gpl3
3,569
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.Constants; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; /** * Home page preference chooser activity. */ public class HomepagePreferenceActivity extends BaseSpinnerCustomPreferenceActivity { @Override protected int getSpinnerPromptId() { return R.string.HomepagePreferenceActivity_Prompt; } @Override protected int getSpinnerValuesArrayId() { return R.array.HomepageValues; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onOk() { Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putString(Constants.PREFERENCES_GENERAL_HOME_PAGE, mCustomEditText.getText().toString()); editor.commit(); } @Override protected void onSpinnerItemSelected(int position) { switch (position) { case 0: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_ABOUT_START); break; case 1: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_ABOUT_BLANK); break; case 2: { mCustomEditText.setEnabled(true); if ((mCustomEditText.getText().toString() .equals(Constants.URL_ABOUT_START)) || (mCustomEditText.getText().toString() .equals(Constants.URL_ABOUT_BLANK))) { mCustomEditText.setText(null); } break; } default: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_ABOUT_START); break; } } @Override protected void setSpinnerValueFromPreferences() { String currentHomepage = PreferenceManager.getDefaultSharedPreferences( this).getString(Constants.PREFERENCES_GENERAL_HOME_PAGE, Constants.URL_ABOUT_START); if (currentHomepage.equals(Constants.URL_ABOUT_START)) { mSpinner.setSelection(0); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_ABOUT_START); } else if (currentHomepage.equals(Constants.URL_ABOUT_BLANK)) { mSpinner.setSelection(1); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.URL_ABOUT_BLANK); } else { mSpinner.setSelection(2); mCustomEditText.setEnabled(true); mCustomEditText.setText(currentHomepage); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/HomepagePreferenceActivity.java
Java
gpl3
2,914
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.Constants; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.preference.PreferenceManager; public class WeaveServerPreferenceActivity extends BaseSpinnerCustomPreferenceActivity { @Override protected int getSpinnerPromptId() { return R.string.WeaveServerPreferenceActivity_Prompt; } @Override protected int getSpinnerValuesArrayId() { return R.array.WeaveServerValues; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override protected void onOk() { Editor editor = PreferenceManager.getDefaultSharedPreferences(this) .edit(); editor.putString(Constants.PREFERENCE_WEAVE_SERVER, mCustomEditText .getText().toString()); editor.commit(); } @Override protected void onSpinnerItemSelected(int position) { switch (position) { case 0: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.WEAVE_DEFAULT_SERVER); break; case 1: { mCustomEditText.setEnabled(true); if (mCustomEditText.getText().toString() .equals(Constants.WEAVE_DEFAULT_SERVER)) { mCustomEditText.setText(null); } break; } default: mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.WEAVE_DEFAULT_SERVER); break; } } @Override protected void setSpinnerValueFromPreferences() { String currentServer = PreferenceManager.getDefaultSharedPreferences( this).getString(Constants.PREFERENCE_WEAVE_SERVER, Constants.WEAVE_DEFAULT_SERVER); if (currentServer.equals(Constants.WEAVE_DEFAULT_SERVER)) { mSpinner.setSelection(0); mCustomEditText.setEnabled(false); mCustomEditText.setText(Constants.WEAVE_DEFAULT_SERVER); } else { mSpinner.setSelection(1); mCustomEditText.setEnabled(true); mCustomEditText.setText(currentServer); } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/WeaveServerPreferenceActivity.java
Java
gpl3
2,593
/* * Zirco Browser for Android * * Copyright (C) 2010 - 2011 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities.preferences; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.Constants; import android.content.Intent; import android.os.Bundle; import android.preference.Preference; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; public class WeavePreferencesActivity extends PreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.layout.weave_preferences_activity); Preference weaveServerPref = findPreference(Constants.PREFERENCE_WEAVE_SERVER); weaveServerPref .setOnPreferenceClickListener(new OnPreferenceClickListener() { @Override public boolean onPreferenceClick(Preference preference) { openWeaveServerActivity(); return true; } }); } private void openWeaveServerActivity() { Intent i = new Intent(this, WeaveServerPreferenceActivity.class); startActivity(i); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/preferences/WeavePreferencesActivity.java
Java
gpl3
1,614
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.model.adapters.BookmarksCursorAdapter; import org.gaeproxy.zirco.model.items.BookmarkItem; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.provider.Browser; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; /** * Bookmarks list activity. */ public class BookmarksListActivity extends Activity { private static final int MENU_ADD_BOOKMARK = Menu.FIRST; private static final int MENU_SORT_MODE = Menu.FIRST + 1; private static final int MENU_OPEN_IN_TAB = Menu.FIRST + 10; private static final int MENU_COPY_URL = Menu.FIRST + 11; private static final int MENU_SHARE = Menu.FIRST + 12; private static final int MENU_EDIT_BOOKMARK = Menu.FIRST + 13; private static final int MENU_DELETE_BOOKMARK = Menu.FIRST + 14; private static final int ACTIVITY_ADD_BOOKMARK = 0; private static final int ACTIVITY_EDIT_BOOKMARK = 1; private Cursor mCursor; private BookmarksCursorAdapter mCursorAdapter; private ListView mList; /** * Show a dialog for choosing the sort mode. Perform the change if required. */ private void changeSortMode() { int currentSort = PreferenceManager.getDefaultSharedPreferences(this).getInt( Constants.PREFERENCES_BOOKMARKS_SORT_MODE, 0); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setInverseBackgroundForced(true); builder.setIcon(android.R.drawable.ic_dialog_info); builder.setTitle(getResources().getString(R.string.BookmarksListActivity_MenuSortMode)); builder.setSingleChoiceItems( new String[] { getResources().getString(R.string.BookmarksListActivity_MostUsedSortMode), getResources().getString(R.string.BookmarksListActivity_AlphaSortMode), getResources().getString(R.string.BookmarksListActivity_RecentSortMode) }, currentSort, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { doChangeSortMode(which); dialog.dismiss(); } }); builder.setCancelable(true); builder.setNegativeButton(R.string.Commons_Cancel, null); AlertDialog alert = builder.create(); alert.show(); } /** * Change list sort mode. Update list. * * @param sortMode * The new sort mode. */ private void doChangeSortMode(int sortMode) { Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(Constants.PREFERENCES_BOOKMARKS_SORT_MODE, sortMode); editor.commit(); fillData(); } /** * Fill the bookmark to the list UI. */ private void fillData() { mCursor = BookmarksProviderWrapper.getStockBookmarks( getContentResolver(), PreferenceManager.getDefaultSharedPreferences(this).getInt( Constants.PREFERENCES_BOOKMARKS_SORT_MODE, 0)); startManagingCursor(mCursor); String[] from = new String[] { Browser.BookmarkColumns.TITLE, Browser.BookmarkColumns.URL }; int[] to = new int[] { R.id.BookmarkRow_Title, R.id.BookmarkRow_Url }; mCursorAdapter = new BookmarksCursorAdapter(this, R.layout.bookmark_row, mCursor, from, to, ApplicationUtils.getFaviconSizeForBookmarks(this)); mList.setAdapter(mCursorAdapter); setAnimation(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); switch (requestCode) { case ACTIVITY_EDIT_BOOKMARK: if (resultCode == RESULT_OK) { fillData(); } break; case ACTIVITY_ADD_BOOKMARK: if (resultCode == RESULT_OK) { fillData(); } break; default: break; } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); Intent i; BookmarkItem bookmarkItem = BookmarksProviderWrapper.getStockBookmarkById( getContentResolver(), info.id); switch (item.getItemId()) { case MENU_OPEN_IN_TAB: i = new Intent(); i.putExtra(Constants.EXTRA_ID_NEW_TAB, true); if (bookmarkItem != null) { i.putExtra(Constants.EXTRA_ID_URL, bookmarkItem.getUrl()); } else { i.putExtra( Constants.EXTRA_ID_URL, PreferenceManager.getDefaultSharedPreferences(BookmarksListActivity.this) .getString(Constants.PREFERENCES_GENERAL_HOME_PAGE, Constants.URL_ABOUT_START)); } if (getParent() != null) { getParent().setResult(RESULT_OK, i); } else { setResult(RESULT_OK, i); } finish(); return true; case MENU_EDIT_BOOKMARK: if (bookmarkItem != null) { i = new Intent(this, EditBookmarkActivity.class); i.putExtra(Constants.EXTRA_ID_BOOKMARK_ID, info.id); i.putExtra(Constants.EXTRA_ID_BOOKMARK_TITLE, bookmarkItem.getTitle()); i.putExtra(Constants.EXTRA_ID_BOOKMARK_URL, bookmarkItem.getUrl()); startActivityForResult(i, ACTIVITY_EDIT_BOOKMARK); } return true; case MENU_COPY_URL: if (bookmarkItem != null) { ApplicationUtils.copyTextToClipboard(this, bookmarkItem.getUrl(), getString(R.string.Commons_UrlCopyToastMessage)); } return true; case MENU_SHARE: if (bookmarkItem != null) { ApplicationUtils.sharePage(this, bookmarkItem.getTitle(), bookmarkItem.getUrl()); } return true; case MENU_DELETE_BOOKMARK: // mDbAdapter.deleteBookmark(info.id); BookmarksProviderWrapper.deleteStockBookmark(getContentResolver(), info.id); fillData(); return true; default: return super.onContextItemSelected(item); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bookmarks_list_activity); setTitle(R.string.BookmarksListActivity_Title); View emptyView = findViewById(R.id.BookmarksListActivity_EmptyTextView); mList = (ListView) findViewById(R.id.BookmarksListActivity_List); mList.setEmptyView(emptyView); mList.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> l, View v, int position, long id) { Intent result = new Intent(); result.putExtra(Constants.EXTRA_ID_NEW_TAB, false); BookmarkItem item = BookmarksProviderWrapper.getStockBookmarkById( getContentResolver(), id); if (item != null) { result.putExtra(Constants.EXTRA_ID_URL, item.getUrl()); } else { result.putExtra( Constants.EXTRA_ID_URL, PreferenceManager.getDefaultSharedPreferences( BookmarksListActivity.this).getString( Constants.PREFERENCES_GENERAL_HOME_PAGE, Constants.URL_ABOUT_START)); } if (getParent() != null) { getParent().setResult(RESULT_OK, result); } else { setResult(RESULT_OK, result); } finish(); } }); registerForContextMenu(mList); fillData(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); long id = ((AdapterContextMenuInfo) menuInfo).id; if (id != -1) { BookmarkItem item = BookmarksProviderWrapper.getStockBookmarkById(getContentResolver(), id); if (item != null) { menu.setHeaderTitle(item.getTitle()); } } menu.add(0, MENU_OPEN_IN_TAB, 0, R.string.BookmarksListActivity_MenuOpenInTab); menu.add(0, MENU_COPY_URL, 0, R.string.BookmarksHistoryActivity_MenuCopyLinkUrl); menu.add(0, MENU_SHARE, 0, R.string.Main_MenuShareLinkUrl); menu.add(0, MENU_EDIT_BOOKMARK, 0, R.string.BookmarksListActivity_MenuEditBookmark); menu.add(0, MENU_DELETE_BOOKMARK, 0, R.string.BookmarksListActivity_MenuDeleteBookmark); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item; item = menu.add(0, MENU_ADD_BOOKMARK, 0, R.string.BookmarksListActivity_MenuAddBookmark); item.setIcon(R.drawable.ic_menu_add_bookmark); item = menu.add(0, MENU_SORT_MODE, 0, R.string.BookmarksListActivity_MenuSortMode); item.setIcon(R.drawable.ic_menu_sort); return true; } @Override protected void onDestroy() { if (mCursor != null) mCursor.close(); super.onDestroy(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_SORT_MODE: changeSortMode(); return true; case MENU_ADD_BOOKMARK: openAddBookmarkDialog(); return true; default: return super.onMenuItemSelected(featureId, item); } } /** * Display the add bookmark dialog. */ private void openAddBookmarkDialog() { Intent i = new Intent(this, EditBookmarkActivity.class); i.putExtra(Constants.EXTRA_ID_BOOKMARK_ID, (long) -1); i.putExtra(Constants.EXTRA_ID_BOOKMARK_TITLE, ""); i.putExtra(Constants.EXTRA_ID_BOOKMARK_URL, ""); startActivityForResult(i, ACTIVITY_ADD_BOOKMARK); } /** * Set the list loading animation. */ private void setAnimation() { AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(100); set.addAnimation(animation); animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setDuration(100); set.addAnimation(animation); LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f); mList.setLayoutAnimation(controller); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/BookmarksListActivity.java
Java
gpl3
10,933
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.model.DbAdapter; import org.gaeproxy.zirco.utils.ApplicationUtils; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.database.Cursor; import android.os.Bundle; import android.text.InputType; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.animation.AlphaAnimation; import android.view.animation.Animation; import android.view.animation.AnimationSet; import android.view.animation.LayoutAnimationController; import android.view.animation.TranslateAnimation; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; /** * AdBlocker white list activity. */ public class AdBlockerWhiteListActivity extends ListActivity { private static final int MENU_ADD = Menu.FIRST; private static final int MENU_CLEAR = Menu.FIRST + 1; private static final int MENU_DELETE = Menu.FIRST + 10; private Cursor mCursor; private DbAdapter mDbAdapter; private SimpleCursorAdapter mCursorAdapter; /** * Build and show a dialog for user input. Add user input to the white list. */ private void addToWhiteList() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setCancelable(true); builder.setIcon(android.R.drawable.ic_input_add); builder.setTitle(getResources().getString( R.string.AdBlockerWhiteListActivity_AddMessage)); builder.setInverseBackgroundForced(true); // Set an EditText view to get user input final EditText input = new EditText(this); input.setInputType(InputType.TYPE_TEXT_VARIATION_URI); builder.setView(input); builder.setInverseBackgroundForced(true); builder.setPositiveButton( getResources().getString(R.string.Commons_Ok), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doAddToWhiteList(input.getText().toString()); } }); builder.setNegativeButton( getResources().getString(R.string.Commons_Cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); AlertDialog alert = builder.create(); alert.show(); } /** * Display a confirmation dialog and clear the white list. */ private void clearWhiteList() { ApplicationUtils.showYesNoDialog(this, android.R.drawable.ic_dialog_alert, R.string.AdBlockerWhiteListActivity_ClearMessage, R.string.Commons_NoUndoMessage, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); doClearWhiteList(); } }); } /** * Add a value to the white list. * * @param value * The value to add. */ private void doAddToWhiteList(String value) { mDbAdapter.insertInWhiteList(value); Controller.getInstance().resetAdBlockWhiteList(); fillData(); } /** * Clear the white list. */ private void doClearWhiteList() { mDbAdapter.clearWhiteList(); Controller.getInstance().resetAdBlockWhiteList(); fillData(); } /** * Fill the list view. */ private void fillData() { mCursor = mDbAdapter.getWhiteListCursor(); startManagingCursor(mCursor); String[] from = new String[] { DbAdapter.ADBLOCK_URL }; int[] to = new int[] { R.id.AdBlockerWhiteListRow_Title }; mCursorAdapter = new SimpleCursorAdapter(this, R.layout.adblocker_whitelist_row, mCursor, from, to); setListAdapter(mCursorAdapter); setAnimation(); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); switch (item.getItemId()) { case MENU_DELETE: mDbAdapter.deleteFromWhiteList(info.id); Controller.getInstance().resetAdBlockWhiteList(); fillData(); return true; default: return super.onContextItemSelected(item); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.adblocker_whitelist_activity); setTitle(R.string.AdBlockerWhiteListActivity_Title); mDbAdapter = new DbAdapter(this); mDbAdapter.open(); registerForContextMenu(getListView()); fillData(); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); long id = ((AdapterContextMenuInfo) menuInfo).id; if (id != -1) { menu.setHeaderTitle(mDbAdapter.getWhiteListItemById(id)); } menu.add(0, MENU_DELETE, 0, R.string.Commons_Delete); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item; item = menu.add(0, MENU_ADD, 0, R.string.Commons_Add); item.setIcon(R.drawable.ic_menu_add); item = menu.add(0, MENU_CLEAR, 0, R.string.Commons_Clear); item.setIcon(R.drawable.ic_menu_delete); return true; } @Override protected void onDestroy() { mDbAdapter.close(); mCursor.close(); super.onDestroy(); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_ADD: addToWhiteList(); return true; case MENU_CLEAR: clearWhiteList(); return true; default: return super.onMenuItemSelected(featureId, item); } } /** * Set the view loading animation. */ private void setAnimation() { AnimationSet set = new AnimationSet(true); Animation animation = new AlphaAnimation(0.0f, 1.0f); animation.setDuration(100); set.addAnimation(animation); animation = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); animation.setDuration(100); set.addAnimation(animation); LayoutAnimationController controller = new LayoutAnimationController( set, 0.5f); ListView listView = getListView(); listView.setLayoutAnimation(controller); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/AdBlockerWhiteListActivity.java
Java
gpl3
6,882
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.activities; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.gaeproxy.ProxySettings; import org.gaeproxy.R; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.events.EventConstants; import org.gaeproxy.zirco.events.EventController; import org.gaeproxy.zirco.events.IDownloadEventsListener; import org.gaeproxy.zirco.model.adapters.UrlSuggestionCursorAdapter; import org.gaeproxy.zirco.model.items.DownloadItem; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.ui.activities.preferences.PreferencesActivity; import org.gaeproxy.zirco.ui.components.CustomWebView; import org.gaeproxy.zirco.ui.components.CustomWebViewClient; import org.gaeproxy.zirco.ui.runnables.FaviconUpdaterRunnable; import org.gaeproxy.zirco.ui.runnables.HideToolbarsRunnable; import org.gaeproxy.zirco.ui.runnables.HistoryUpdater; import org.gaeproxy.zirco.utils.AnimationManager; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import org.gaeproxy.zirco.utils.UrlUtils; import org.greendroid.QuickAction; import org.greendroid.QuickActionGrid; import org.greendroid.QuickActionWidget; import org.greendroid.QuickActionWidget.OnQuickActionClickListener; import android.app.Activity; import android.app.AlarmManager; import android.app.AlertDialog; import android.app.PendingIntent; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.text.Editable; import android.text.TextWatcher; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.GestureDetector; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.webkit.DownloadListener; import android.webkit.JsPromptResult; import android.webkit.JsResult; import android.webkit.ValueCallback; import android.webkit.WebChromeClient; import android.webkit.WebIconDatabase; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import android.widget.AutoCompleteTextView; import android.widget.EditText; import android.widget.FilterQueryProvider; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.SimpleCursorAdapter.CursorToStringConverter; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewFlipper; /** * The application main activity. */ public class MainActivity extends Activity implements IToolbarsContainer, OnTouchListener, IDownloadEventsListener { /** * Gesture listener implementation. */ private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onDoubleTap(MotionEvent e) { mCurrentWebView.zoomIn(); return super.onDoubleTap(e); } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { if (isSwitchTabsByFlingEnabled()) { if (e2.getEventTime() - e1.getEventTime() <= FLIP_TIME_THRESHOLD) { if (e2.getX() > (e1.getX() + FLIP_PIXEL_THRESHOLD)) { showPreviousTab(false); return false; } // going forwards: pushing stuff to the left if (e2.getX() < (e1.getX() - FLIP_PIXEL_THRESHOLD)) { showNextTab(false); return false; } } } return super.onFling(e1, e2, velocityX, velocityY); } } private enum SwitchTabsMethod { BUTTONS, FLING, BOTH } public static MainActivity INSTANCE = null; private static final int FLIP_PIXEL_THRESHOLD = 200; private static final int FLIP_TIME_THRESHOLD = 400; private static final int MENU_ADD_BOOKMARK = Menu.FIRST; private static final int MENU_SHOW_BOOKMARKS = Menu.FIRST + 1; private static final int MENU_SHOW_DOWNLOADS = Menu.FIRST + 2; private static final int MENU_PREFERENCES = Menu.FIRST + 3; private static final int MENU_EXIT = Menu.FIRST + 4; private static final int CONTEXT_MENU_OPEN = Menu.FIRST + 10; private static final int CONTEXT_MENU_OPEN_IN_NEW_TAB = Menu.FIRST + 11; private static final int CONTEXT_MENU_DOWNLOAD = Menu.FIRST + 12; private static final int CONTEXT_MENU_COPY = Menu.FIRST + 13; private static final int CONTEXT_MENU_SEND_MAIL = Menu.FIRST + 14; private static final int CONTEXT_MENU_SHARE = Menu.FIRST + 15; private static final int OPEN_BOOKMARKS_HISTORY_ACTIVITY = 0; private static final int OPEN_DOWNLOADS_ACTIVITY = 1; private static final int OPEN_FILE_CHOOSER_ACTIVITY = 2; protected LayoutInflater mInflater = null; private LinearLayout mTopBar; private LinearLayout mBottomBar; private LinearLayout mFindBar; private ImageButton mFindPreviousButton; private ImageButton mFindNextButton; private ImageButton mFindCloseButton; private EditText mFindText; private ImageView mPreviousTabView; private ImageView mNextTabView; private ImageButton mToolsButton; private AutoCompleteTextView mUrlEditText; private ImageButton mGoButton; private ProgressBar mProgressBar; private ImageView mBubbleRightView; private ImageView mBubbleLeftView; private CustomWebView mCurrentWebView; private List<CustomWebView> mWebViews; private ImageButton mPreviousButton; private ImageButton mNextButton; private ImageButton mNewTabButton; private ImageButton mRemoveTabButton; private ImageButton mQuickButton; private Drawable mCircularProgress; private boolean mUrlBarVisible; private boolean mToolsActionGridVisible = false; private boolean mFindDialogVisible = false; private TextWatcher mUrlTextWatcher; private HideToolbarsRunnable mHideToolbarsRunnable; private ViewFlipper mViewFlipper; private GestureDetector mGestureDetector; private SwitchTabsMethod mSwitchTabsMethod = SwitchTabsMethod.BOTH; private QuickActionGrid mToolsActionGrid; private ValueCallback<Uri> mUploadMessage; /** * Add a new tab. * * @param navigateToHome * If True, will load the user home page. */ private void addTab(boolean navigateToHome) { addTab(navigateToHome, -1); } /** * Add a new tab. * * @param navigateToHome * If True, will load the user home page. * @param parentIndex * The index of the new tab. */ private void addTab(boolean navigateToHome, int parentIndex) { if (mFindDialogVisible) { closeFindDialog(); } RelativeLayout view = (RelativeLayout) mInflater.inflate(R.layout.webview, mViewFlipper, false); mCurrentWebView = (CustomWebView) view.findViewById(R.id.webview); initializeCurrentWebView(); synchronized (mViewFlipper) { if (parentIndex != -1) { mWebViews.add(parentIndex + 1, mCurrentWebView); mViewFlipper.addView(view, parentIndex + 1); } else { mWebViews.add(mCurrentWebView); mViewFlipper.addView(view); } mViewFlipper.setDisplayedChild(mViewFlipper.indexOfChild(view)); } updateUI(); updatePreviousNextTabViewsVisibility(); mUrlEditText.clearFocus(); if (navigateToHome) { navigateToHome(); } } /** * Apply preferences to the current UI objects. */ public void applyPreferences() { // To update to Bubble position. setToolbarsVisibility(false); updateSwitchTabsMethod(); for (CustomWebView view : mWebViews) { view.initializeOptions(); } } /** * Create main UI. */ private void buildComponents() { mToolsActionGrid = new QuickActionGrid(this); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_home, R.string.QuickAction_Home)); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_share, R.string.QuickAction_Share)); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_find, R.string.QuickAction_Find)); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_select, R.string.QuickAction_SelectText)); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_mobile_view, R.string.QuickAction_MobileView)); mToolsActionGrid.addQuickAction(new QuickAction(this, R.drawable.ic_btn_tools, R.string.QuickAction_Menu)); mToolsActionGrid.setOnQuickActionClickListener(new OnQuickActionClickListener() { @Override public void onQuickActionClicked(QuickActionWidget widget, int position) { switch (position) { case 0: navigateToHome(); break; case 1: ApplicationUtils.sharePage(MainActivity.this, mCurrentWebView.getTitle(), mCurrentWebView.getUrl()); break; case 2: // Somewhat dirty hack: when the find dialog was // shown from a QuickAction, // the soft keyboard did not show... Hack is to wait // a little before showing // the file dialog through a thread. startShowFindDialogRunnable(); break; case 3: swithToSelectAndCopyTextMode(); break; case 4: String currentUrl = mUrlEditText.getText().toString(); // Do not reload mobile view if already on it. if (!currentUrl.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT)) { String url = String.format(Constants.URL_GOOGLE_MOBILE_VIEW, mUrlEditText .getText().toString()); navigateToUrl(url); } break; case 5: openOptionsMenu(); break; } } }); mToolsActionGrid.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { mToolsActionGridVisible = false; startToolbarsHideRunnable(); } }); mGestureDetector = new GestureDetector(this, new GestureListener()); mUrlBarVisible = true; mWebViews = new ArrayList<CustomWebView>(); Controller.getInstance().setWebViewList(mWebViews); mBubbleRightView = (ImageView) findViewById(R.id.BubbleRightView); mBubbleRightView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setToolbarsVisibility(true); } }); mBubbleRightView.setVisibility(View.GONE); mBubbleLeftView = (ImageView) findViewById(R.id.BubbleLeftView); mBubbleLeftView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { setToolbarsVisibility(true); } }); mBubbleLeftView.setVisibility(View.GONE); mViewFlipper = (ViewFlipper) findViewById(R.id.ViewFlipper); mTopBar = (LinearLayout) findViewById(R.id.BarLayout); mTopBar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Dummy event to steel it from the WebView, in case of clicking // between the buttons. } }); mBottomBar = (LinearLayout) findViewById(R.id.BottomBarLayout); mBottomBar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Dummy event to steel it from the WebView, in case of clicking // between the buttons. } }); mFindBar = (LinearLayout) findViewById(R.id.findControls); mFindBar.setVisibility(View.GONE); mPreviousTabView = (ImageView) findViewById(R.id.PreviousTabView); mPreviousTabView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showPreviousTab(true); } }); mPreviousTabView.setVisibility(View.GONE); mNextTabView = (ImageView) findViewById(R.id.NextTabView); mNextTabView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showNextTab(true); } }); mNextTabView.setVisibility(View.GONE); String[] from = new String[] { UrlSuggestionCursorAdapter.URL_SUGGESTION_TITLE, UrlSuggestionCursorAdapter.URL_SUGGESTION_URL }; int[] to = new int[] { R.id.AutocompleteTitle, R.id.AutocompleteUrl }; UrlSuggestionCursorAdapter adapter = new UrlSuggestionCursorAdapter(this, R.layout.url_autocomplete_line, null, from, to); adapter.setCursorToStringConverter(new CursorToStringConverter() { @Override public CharSequence convertToString(Cursor cursor) { String aColumnString = cursor.getString(cursor .getColumnIndex(UrlSuggestionCursorAdapter.URL_SUGGESTION_URL)); return aColumnString; } }); adapter.setFilterQueryProvider(new FilterQueryProvider() { @Override public Cursor runQuery(CharSequence constraint) { if ((constraint != null) && (constraint.length() > 0)) { return BookmarksProviderWrapper.getUrlSuggestions(getContentResolver(), constraint.toString(), PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .getBoolean(Constants.PREFERENCE_USE_WEAVE, false)); } else { return BookmarksProviderWrapper.getUrlSuggestions(getContentResolver(), null, PreferenceManager.getDefaultSharedPreferences(MainActivity.this) .getBoolean(Constants.PREFERENCE_USE_WEAVE, false)); } } }); mUrlEditText = (AutoCompleteTextView) findViewById(R.id.UrlText); mUrlEditText.setThreshold(1); mUrlEditText.setAdapter(adapter); mUrlEditText.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER) { navigateToUrl(); return true; } return false; } }); mUrlTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable arg0) { updateGoButton(); } @Override public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } @Override public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { } }; mUrlEditText.addTextChangedListener(mUrlTextWatcher); mUrlEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { // Select all when focus gained. if (hasFocus) { mUrlEditText.setSelection(0, mUrlEditText.getText().length()); } } }); mUrlEditText.setCompoundDrawablePadding(5); mGoButton = (ImageButton) findViewById(R.id.GoBtn); mGoButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (mCurrentWebView.isLoading()) { mCurrentWebView.stopLoading(); } else if (!mCurrentWebView.isSameUrl(mUrlEditText.getText().toString())) { navigateToUrl(); } else { mCurrentWebView.reload(); } } }); mToolsButton = (ImageButton) findViewById(R.id.ToolsBtn); mToolsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mToolsActionGridVisible = true; mToolsActionGrid.show(v); } }); mProgressBar = (ProgressBar) findViewById(R.id.WebViewProgress); mProgressBar.setMax(100); mPreviousButton = (ImageButton) findViewById(R.id.PreviousBtn); mNextButton = (ImageButton) findViewById(R.id.NextBtn); mPreviousButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { navigatePrevious(); } }); mNextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { navigateNext(); } }); mNewTabButton = (ImageButton) findViewById(R.id.NewTabBtn); mNewTabButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { addTab(true); } }); mRemoveTabButton = (ImageButton) findViewById(R.id.RemoveTabBtn); mRemoveTabButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { removeCurrentTab(); } }); mQuickButton = (ImageButton) findViewById(R.id.QuickBtn); mQuickButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onQuickButton(); } }); mFindPreviousButton = (ImageButton) findViewById(R.id.find_previous); mFindPreviousButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCurrentWebView.findNext(false); hideKeyboardFromFindDialog(); } }); mFindNextButton = (ImageButton) findViewById(R.id.find_next); mFindNextButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mCurrentWebView.findNext(true); hideKeyboardFromFindDialog(); } }); mFindCloseButton = (ImageButton) findViewById(R.id.find_close); mFindCloseButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeFindDialog(); } }); mFindText = (EditText) findViewById(R.id.find_value); mFindText.addTextChangedListener(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) { doFind(); } }); } /** * Check if the url is in the AdBlock white list. * * @param url * The url to check * @return true if the url is in the white list */ private boolean checkInAdBlockWhiteList(String url) { if (url != null) { boolean inList = false; Iterator<String> iter = Controller.getInstance().getAdBlockWhiteList(this).iterator(); while ((iter.hasNext()) && (!inList)) { if (url.contains(iter.next())) { inList = true; } } return inList; } else { return false; } } /** * Set the application title to default. */ private void clearTitle() { this.setTitle(getResources().getString(R.string.ApplicationName)); } private void closeFindDialog() { hideKeyboardFromFindDialog(); mCurrentWebView.doNotifyFindDialogDismissed(); setFindBarVisibility(false); } /** * Initiate a download. Check the SD card and start the download runnable. * * @param url * The url to download. * @param userAgent * The user agent. * @param contentDisposition * The content disposition. * @param mimetype * The mime type. * @param contentLength * The content length. */ private void doDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { if (ApplicationUtils.checkCardState(this, true)) { DownloadItem item = new DownloadItem(this, url); Controller.getInstance().addToDownload(item); item.startDownload(); Toast.makeText(this, getString(R.string.Main_DownloadStartedMsg), Toast.LENGTH_SHORT) .show(); } } private void doFind() { CharSequence find = mFindText.getText(); if (find.length() == 0) { mFindPreviousButton.setEnabled(false); mFindNextButton.setEnabled(false); mCurrentWebView.clearMatches(); } else { int found = mCurrentWebView.findAll(find.toString()); if (found < 2) { mFindPreviousButton.setEnabled(false); mFindNextButton.setEnabled(false); } else { mFindPreviousButton.setEnabled(true); mFindNextButton.setEnabled(true); } } } /** * Get a Drawable of the current favicon, with its size normalized relative * to current screen density. * * @return The normalized favicon. */ private BitmapDrawable getNormalizedFavicon() { BitmapDrawable favIcon = new BitmapDrawable(getResources(), mCurrentWebView.getFavicon()); if (mCurrentWebView.getFavicon() != null) { int imageButtonSize = ApplicationUtils.getImageButtonSize(this); int favIconSize = ApplicationUtils.getFaviconSize(this); Bitmap bm = Bitmap.createBitmap(imageButtonSize, imageButtonSize, Bitmap.Config.ARGB_4444); Canvas canvas = new Canvas(bm); favIcon.setBounds((imageButtonSize / 2) - (favIconSize / 2), (imageButtonSize / 2) - (favIconSize / 2), (imageButtonSize / 2) + (favIconSize / 2), (imageButtonSize / 2) + (favIconSize / 2)); favIcon.draw(canvas); favIcon = new BitmapDrawable(getResources(), bm); } return favIcon; } /** * Hide the keyboard. * * @param delayedHideToolbars * If True, will start a runnable to delay tool bars hiding. If * False, tool bars are hidden immediatly. */ private void hideKeyboard(boolean delayedHideToolbars) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mUrlEditText.getWindowToken(), 0); if (mUrlBarVisible) { if (delayedHideToolbars) { startToolbarsHideRunnable(); } else { setToolbarsVisibility(false); } } } private void hideKeyboardFromFindDialog() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mFindText.getWindowToken(), 0); } /** * Hide the tool bars. */ @Override public void hideToolbars() { if (mUrlBarVisible) { if ((!mUrlEditText.hasFocus()) && (!mToolsActionGridVisible)) { if (!mCurrentWebView.isLoading()) { setToolbarsVisibility(false); } } } mHideToolbarsRunnable = null; } /** * Initialize a newly created WebView. */ private void initializeCurrentWebView() { mCurrentWebView.setWebViewClient(new CustomWebViewClient(this)); mCurrentWebView.setOnTouchListener(this); mCurrentWebView.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { HitTestResult result = ((WebView) v).getHitTestResult(); int resultType = result.getType(); if ((resultType == HitTestResult.ANCHOR_TYPE) || (resultType == HitTestResult.IMAGE_ANCHOR_TYPE) || (resultType == HitTestResult.SRC_ANCHOR_TYPE) || (resultType == HitTestResult.SRC_IMAGE_ANCHOR_TYPE)) { Intent i = new Intent(); i.putExtra(Constants.EXTRA_ID_URL, result.getExtra()); MenuItem item = menu.add(0, CONTEXT_MENU_OPEN, 0, R.string.Main_MenuOpen); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_OPEN_IN_NEW_TAB, 0, R.string.Main_MenuOpenNewTab); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_COPY, 0, R.string.Main_MenuCopyLinkUrl); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_DOWNLOAD, 0, R.string.Main_MenuDownload); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_SHARE, 0, R.string.Main_MenuShareLinkUrl); item.setIntent(i); menu.setHeaderTitle(result.getExtra()); } else if (resultType == HitTestResult.IMAGE_TYPE) { Intent i = new Intent(); i.putExtra(Constants.EXTRA_ID_URL, result.getExtra()); MenuItem item = menu.add(0, CONTEXT_MENU_OPEN, 0, R.string.Main_MenuViewImage); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_COPY, 0, R.string.Main_MenuCopyImageUrl); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_DOWNLOAD, 0, R.string.Main_MenuDownloadImage); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_SHARE, 0, R.string.Main_MenuShareImageUrl); item.setIntent(i); menu.setHeaderTitle(result.getExtra()); } else if (resultType == HitTestResult.EMAIL_TYPE) { Intent sendMail = new Intent(Intent.ACTION_VIEW, Uri .parse(WebView.SCHEME_MAILTO + result.getExtra())); MenuItem item = menu.add(0, CONTEXT_MENU_SEND_MAIL, 0, R.string.Main_MenuSendEmail); item.setIntent(sendMail); Intent i = new Intent(); i.putExtra(Constants.EXTRA_ID_URL, result.getExtra()); item = menu.add(0, CONTEXT_MENU_COPY, 0, R.string.Main_MenuCopyEmailUrl); item.setIntent(i); item = menu.add(0, CONTEXT_MENU_SHARE, 0, R.string.Main_MenuShareEmailUrl); item.setIntent(i); menu.setHeaderTitle(result.getExtra()); } } }); mCurrentWebView.setDownloadListener(new DownloadListener() { @Override public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) { doDownloadStart(url, userAgent, contentDisposition, mimetype, contentLength); } }); final Activity activity = this; mCurrentWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onCreateWindow(WebView view, final boolean dialog, final boolean userGesture, final Message resultMsg) { WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; addTab(false, mViewFlipper.getDisplayedChild()); transport.setWebView(mCurrentWebView); resultMsg.sendToTarget(); return false; } @Override public boolean onJsAlert(WebView view, String url, String message, final JsResult result) { new AlertDialog.Builder(activity).setTitle(R.string.Commons_JavaScriptDialog) .setMessage(message) .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }).setCancelable(false).create().show(); return true; } @Override public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) { new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.Commons_JavaScriptDialog) .setMessage(message) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.confirm(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { result.cancel(); } }).create().show(); return true; } @Override public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, final JsPromptResult result) { final LayoutInflater factory = LayoutInflater.from(MainActivity.this); final View v = factory.inflate(R.layout.javascript_prompt_dialog, null); ((TextView) v.findViewById(R.id.JavaScriptPromptMessage)).setText(message); ((EditText) v.findViewById(R.id.JavaScriptPromptInput)).setText(defaultValue); new AlertDialog.Builder(MainActivity.this) .setTitle(R.string.Commons_JavaScriptDialog) .setView(v) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { String value = ((EditText) v .findViewById(R.id.JavaScriptPromptInput)) .getText().toString(); result.confirm(value); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int whichButton) { result.cancel(); } }).setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { result.cancel(); } }).show(); return true; } @Override public void onProgressChanged(WebView view, int newProgress) { ((CustomWebView) view).setProgress(newProgress); mProgressBar.setProgress(mCurrentWebView.getProgress()); } @Override public void onReceivedIcon(WebView view, Bitmap icon) { new Thread(new FaviconUpdaterRunnable(MainActivity.this, view.getUrl(), view .getOriginalUrl(), icon)).start(); updateFavIcon(); super.onReceivedIcon(view, icon); } @Override public void onReceivedTitle(WebView view, String title) { setTitle(String .format(getResources().getString(R.string.ApplicationNameUrl), title)); startHistoryUpdaterRunnable(title, mCurrentWebView.getUrl(), mCurrentWebView.getOriginalUrl()); super.onReceivedTitle(view, title); } @SuppressWarnings("unused") // This is an undocumented method, it _is_ used, whatever Eclipse // may think :) // Used to show a file chooser dialog. public void openFileChooser(ValueCallback<Uri> uploadMsg) { mUploadMessage = uploadMsg; Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); MainActivity.this.startActivityForResult( Intent.createChooser(i, MainActivity.this.getString(R.string.Main_FileChooserPrompt)), OPEN_FILE_CHOOSER_ACTIVITY); } }); } /** * Initialize the Web icons database. */ private void initializeWebIconDatabase() { final WebIconDatabase db = WebIconDatabase.getInstance(); db.open(getDir("icons", 0).getPath()); } private boolean isSwitchTabsByButtonsEnabled() { return (mSwitchTabsMethod == SwitchTabsMethod.BUTTONS) || (mSwitchTabsMethod == SwitchTabsMethod.BOTH); } private boolean isSwitchTabsByFlingEnabled() { return (mSwitchTabsMethod == SwitchTabsMethod.FLING) || (mSwitchTabsMethod == SwitchTabsMethod.BOTH); } /** * Navigate to the next page in history. */ private void navigateNext() { // Needed to hide toolbars properly. mUrlEditText.clearFocus(); hideKeyboard(true); mCurrentWebView.goForward(); } /** * Navigate to the previous page in history. */ private void navigatePrevious() { // Needed to hide toolbars properly. mUrlEditText.clearFocus(); hideKeyboard(true); mCurrentWebView.goBack(); } /** * Navigate to the user home page. */ private void navigateToHome() { navigateToUrl(Controller.getInstance().getPreferences() .getString(Constants.PREFERENCES_GENERAL_HOME_PAGE, Constants.URL_ABOUT_START)); } /** * Navigate to the url given in the url edit text. */ private void navigateToUrl() { navigateToUrl(mUrlEditText.getText().toString()); } /** * Navigate to the given url. * * @param url * The url. */ private void navigateToUrl(String url) { // Needed to hide toolbars properly. mUrlEditText.clearFocus(); if ((url != null) && (url.length() > 0)) { if (UrlUtils.isUrl(url)) { url = UrlUtils.checkUrl(url); } else { url = UrlUtils.getSearchUrl(this, url); } hideKeyboard(true); if (url.equals(Constants.URL_ABOUT_START)) { mCurrentWebView.loadDataWithBaseURL("file:///android_asset/startpage/", ApplicationUtils.getStartPage(this), "text/html", "UTF-8", Constants.URL_ABOUT_START); } else { // If the url is not from GWT mobile view, and is in the mobile // view url list, then load it with GWT. if ((!url.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT)) && (UrlUtils.checkInMobileViewUrlList(this, url))) { url = String.format(Constants.URL_GOOGLE_MOBILE_VIEW, url); } mCurrentWebView.loadUrl(url); } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent intent) { super.onActivityResult(requestCode, resultCode, intent); if (requestCode == OPEN_BOOKMARKS_HISTORY_ACTIVITY) { if (intent != null) { Bundle b = intent.getExtras(); if (b != null) { if (b.getBoolean(Constants.EXTRA_ID_NEW_TAB)) { addTab(false); } navigateToUrl(b.getString(Constants.EXTRA_ID_URL)); } } } else if (requestCode == OPEN_FILE_CHOOSER_ACTIVITY) { if (mUploadMessage == null) { return; } Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData(); mUploadMessage.onReceiveValue(result); mUploadMessage = null; } } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } @Override public boolean onContextItemSelected(MenuItem item) { if ((item != null) && (item.getIntent() != null)) { Bundle b = item.getIntent().getExtras(); switch (item.getItemId()) { case CONTEXT_MENU_OPEN: if (b != null) { navigateToUrl(b.getString(Constants.EXTRA_ID_URL)); } return true; case CONTEXT_MENU_OPEN_IN_NEW_TAB: if (b != null) { addTab(false, mViewFlipper.getDisplayedChild()); navigateToUrl(b.getString(Constants.EXTRA_ID_URL)); } return true; case CONTEXT_MENU_DOWNLOAD: if (b != null) { doDownloadStart(b.getString(Constants.EXTRA_ID_URL), null, null, null, 0); } return true; case CONTEXT_MENU_COPY: if (b != null) { ApplicationUtils.copyTextToClipboard(this, b.getString(Constants.EXTRA_ID_URL), getString(R.string.Commons_UrlCopyToastMessage)); } return true; case CONTEXT_MENU_SHARE: if (b != null) { ApplicationUtils.sharePage(this, "", b.getString(Constants.EXTRA_ID_URL)); } return true; default: return super.onContextItemSelected(item); } } return super.onContextItemSelected(item); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); INSTANCE = this; Constants.initializeConstantsFromResources(this); Controller.getInstance() .setPreferences(PreferenceManager.getDefaultSharedPreferences(this)); if (Controller.getInstance().getPreferences() .getBoolean(Constants.PREFERENCES_SHOW_FULL_SCREEN, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } if (Controller.getInstance().getPreferences() .getBoolean(Constants.PREFERENCES_GENERAL_HIDE_TITLE_BARS, true)) { requestWindowFeature(Window.FEATURE_NO_TITLE); } setProgressBarVisibility(true); setContentView(R.layout.ziro_main); mCircularProgress = getResources().getDrawable(R.drawable.spinner); EventController.getInstance().addDownloadListener(this); mHideToolbarsRunnable = null; mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); buildComponents(); mViewFlipper.removeAllViews(); updateSwitchTabsMethod(); Intent i = getIntent(); if (i.getData() != null) { // App first launch from another app. addTab(false); navigateToUrl(i.getDataString()); } else { // Normal start. int currentVersionCode = ApplicationUtils.getApplicationVersionCode(this); int savedVersionCode = PreferenceManager.getDefaultSharedPreferences(this).getInt( Constants.PREFERENCES_LAST_VERSION_CODE, -1); // If currentVersionCode and savedVersionCode are different, the // application has been updated. if (currentVersionCode != savedVersionCode) { // Save current version code. Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt(Constants.PREFERENCES_LAST_VERSION_CODE, currentVersionCode); editor.commit(); // Display changelog dialog. Intent changelogIntent = new Intent(this, ChangelogActivity.class); startActivity(changelogIntent); } addTab(true); } initializeWebIconDatabase(); startToolbarsHideRunnable(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuItem item; item = menu.add(0, MENU_ADD_BOOKMARK, 0, R.string.Main_MenuAddBookmark); item.setIcon(R.drawable.ic_menu_add_bookmark); item = menu.add(0, MENU_SHOW_BOOKMARKS, 0, R.string.Main_MenuShowBookmarks); item.setIcon(R.drawable.ic_menu_bookmarks); item = menu.add(0, MENU_SHOW_DOWNLOADS, 0, R.string.Main_MenuShowDownloads); item.setIcon(R.drawable.ic_menu_downloads); item = menu.add(0, MENU_PREFERENCES, 0, R.string.Main_MenuPreferences); item.setIcon(R.drawable.ic_menu_preferences); item = menu.add(0, MENU_EXIT, 0, R.string.Main_MenuExit); item.setIcon(R.drawable.ic_menu_exit); return true; } @Override protected void onDestroy() { WebIconDatabase.getInstance().close(); if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean( Constants.PREFERENCES_PRIVACY_CLEAR_CACHE_ON_EXIT, false)) { mCurrentWebView.clearCache(true); } EventController.getInstance().removeDownloadListener(this); super.onDestroy(); } @Override public void onDownloadEvent(String event, Object data) { if (event.equals(EventConstants.EVT_DOWNLOAD_ON_FINISHED)) { DownloadItem item = (DownloadItem) data; if (item.getErrorMessage() == null) { Toast.makeText(this, getString(R.string.Main_DownloadFinishedMsg), Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, getString(R.string.Main_DownloadErrorMsg, item.getErrorMessage()), Toast.LENGTH_SHORT).show(); } } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { String volumeKeysBehaviour = PreferenceManager.getDefaultSharedPreferences(this).getString( Constants.PREFERENCES_UI_VOLUME_KEYS_BEHAVIOUR, "DEFAULT"); if (!volumeKeysBehaviour.equals("DEFAULT")) { switch (keyCode) { case KeyEvent.KEYCODE_VOLUME_DOWN: if (volumeKeysBehaviour.equals("SWITCH_TABS")) { showPreviousTab(false); } else if (volumeKeysBehaviour.equals("HISTORY")) { mCurrentWebView.goForward(); } else { mCurrentWebView.zoomIn(); } return true; case KeyEvent.KEYCODE_VOLUME_UP: if (volumeKeysBehaviour.equals("SWITCH_TABS")) { showNextTab(false); } else if (volumeKeysBehaviour.equals("HISTORY")) { mCurrentWebView.goBack(); } else { mCurrentWebView.zoomOut(); } return true; default: return super.onKeyDown(keyCode, event); } } else { return super.onKeyDown(keyCode, event); } } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: this.moveTaskToBack(true); return true; default: return super.onKeyLongPress(keyCode, event); } } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { switch (keyCode) { case KeyEvent.KEYCODE_BACK: if (mFindDialogVisible) { closeFindDialog(); } else { if (mCurrentWebView.canGoBack()) { mCurrentWebView.goBack(); } else { this.moveTaskToBack(true); } } return true; case KeyEvent.KEYCODE_SEARCH: if (!mFindDialogVisible) { showFindDialog(); } return true; default: return super.onKeyUp(keyCode, event); } } public void onMailTo(String url) { Intent sendMail = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(sendMail); } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case MENU_ADD_BOOKMARK: openAddBookmarkDialog(); return true; case MENU_SHOW_BOOKMARKS: openBookmarksHistoryActivity(); return true; case MENU_SHOW_DOWNLOADS: openDownloadsList(); return true; case MENU_PREFERENCES: openPreferences(); return true; case MENU_EXIT: this.finish(); return true; default: return super.onMenuItemSelected(featureId, item); } } /** * Handle url request from external apps. * * @param intent * The intent. */ @Override protected void onNewIntent(Intent intent) { if (intent.getData() != null) { addTab(false); navigateToUrl(intent.getDataString()); } setIntent(intent); super.onNewIntent(intent); } public void onPageFinished(String url) { updateUI(); if (url.contains("mobile.twitter.com")) { mCurrentWebView.loadUrl("http://dabr.co.uk/"); return; } if ((Controller.getInstance().getPreferences().getBoolean( Constants.PREFERENCES_ADBLOCKER_ENABLE, true)) && (!checkInAdBlockWhiteList(mCurrentWebView.getUrl()))) { mCurrentWebView.loadAdSweep(); } WebIconDatabase.getInstance().retainIconForPageUrl(mCurrentWebView.getUrl()); if (mUrlBarVisible) { startToolbarsHideRunnable(); } } public void onPageStarted(String url) { if (mFindDialogVisible) { closeFindDialog(); } mUrlEditText.removeTextChangedListener(mUrlTextWatcher); mUrlEditText.setText(url); mUrlEditText.addTextChangedListener(mUrlTextWatcher); mPreviousButton.setEnabled(false); mNextButton.setEnabled(false); updateGoButton(); setToolbarsVisibility(true); } @Override protected void onPause() { mCurrentWebView.doOnPause(); super.onPause(); } /** * Perform the user-defined action when clicking on the quick button. */ private void onQuickButton() { openBookmarksHistoryActivity(); } @Override protected void onResume() { mCurrentWebView.doOnResume(); super.onResume(); } @Override public boolean onTouch(View v, MotionEvent event) { hideKeyboard(false); return mGestureDetector.onTouchEvent(event); } public void onUrlLoading(String url) { setToolbarsVisibility(true); } public void onVndUrl(String url) { try { Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(i); } catch (Exception e) { // Notify user that the vnd url cannot be viewed. new AlertDialog.Builder(this).setTitle(R.string.Main_VndErrorTitle) .setMessage(String.format(getString(R.string.Main_VndErrorMessage), url)) .setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setCancelable(true).create().show(); } } /** * Open the "Add bookmark" dialog. */ private void openAddBookmarkDialog() { Intent i = new Intent(this, EditBookmarkActivity.class); i.putExtra(Constants.EXTRA_ID_BOOKMARK_ID, (long) -1); i.putExtra(Constants.EXTRA_ID_BOOKMARK_TITLE, mCurrentWebView.getTitle()); i.putExtra(Constants.EXTRA_ID_BOOKMARK_URL, mCurrentWebView.getUrl()); startActivity(i); } /** * Open the bookmark list. */ private void openBookmarksHistoryActivity() { Intent i = new Intent(this, BookmarksHistoryActivity.class); startActivityForResult(i, OPEN_BOOKMARKS_HISTORY_ACTIVITY); } /** * Open the download list. */ private void openDownloadsList() { Intent i = new Intent(this, DownloadsListActivity.class); startActivityForResult(i, OPEN_DOWNLOADS_ACTIVITY); } /** * Open preferences. */ private void openPreferences() { Intent preferencesActivity = new Intent(this, PreferencesActivity.class); startActivity(preferencesActivity); } /** * Remove the current tab. */ private void removeCurrentTab() { if (mFindDialogVisible) { closeFindDialog(); } int removeIndex = mViewFlipper.getDisplayedChild(); mCurrentWebView.doOnPause(); synchronized (mViewFlipper) { mViewFlipper.removeViewAt(removeIndex); mViewFlipper.setDisplayedChild(removeIndex - 1); mWebViews.remove(removeIndex); } mCurrentWebView = mWebViews.get(mViewFlipper.getDisplayedChild()); updateUI(); updatePreviousNextTabViewsVisibility(); mUrlEditText.clearFocus(); } /** * Restart the application. */ public void restartApplication() { PendingIntent intent = PendingIntent.getActivity(this.getBaseContext(), 0, new Intent( getIntent()), getIntent().getFlags()); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, intent); System.exit(2); } private void setFindBarVisibility(boolean visible) { if (visible) { mFindBar.startAnimation(AnimationManager.getInstance().getTopBarShowAnimation()); mFindBar.setVisibility(View.VISIBLE); mFindDialogVisible = true; } else { mFindBar.startAnimation(AnimationManager.getInstance().getTopBarHideAnimation()); mFindBar.setVisibility(View.GONE); mFindDialogVisible = false; } } /** * Change the tool bars visibility. * * @param visible * If True, the tool bars will be shown. */ private void setToolbarsVisibility(boolean visible) { boolean switchTabByButtons = isSwitchTabsByButtonsEnabled(); boolean showPreviousTabView = mViewFlipper.getDisplayedChild() > 0; boolean showNextTabView = mViewFlipper.getDisplayedChild() < mViewFlipper.getChildCount() - 1; if (visible) { if (!mUrlBarVisible) { mTopBar.startAnimation(AnimationManager.getInstance().getTopBarShowAnimation()); mBottomBar.startAnimation(AnimationManager.getInstance() .getBottomBarShowAnimation()); if (switchTabByButtons) { if (showPreviousTabView) { mPreviousTabView.startAnimation(AnimationManager.getInstance() .getPreviousTabViewShowAnimation()); } if (showNextTabView) { mNextTabView.startAnimation(AnimationManager.getInstance() .getNextTabViewShowAnimation()); } } mTopBar.setVisibility(View.VISIBLE); mBottomBar.setVisibility(View.VISIBLE); if (switchTabByButtons) { if (showPreviousTabView) { mPreviousTabView.setVisibility(View.VISIBLE); } if (showNextTabView) { mNextTabView.setVisibility(View.VISIBLE); } } mBubbleRightView.setVisibility(View.GONE); mBubbleLeftView.setVisibility(View.GONE); } startToolbarsHideRunnable(); mUrlBarVisible = true; } else { if (mUrlBarVisible) { mTopBar.startAnimation(AnimationManager.getInstance().getTopBarHideAnimation()); mBottomBar.startAnimation(AnimationManager.getInstance() .getBottomBarHideAnimation()); if (switchTabByButtons) { if (showPreviousTabView) { mPreviousTabView.startAnimation(AnimationManager.getInstance() .getPreviousTabViewHideAnimation()); } if (showNextTabView) { mNextTabView.startAnimation(AnimationManager.getInstance() .getNextTabViewHideAnimation()); } } mTopBar.setVisibility(View.GONE); mBottomBar.setVisibility(View.GONE); if (switchTabByButtons) { if (showPreviousTabView) { mPreviousTabView.setVisibility(View.GONE); } if (showNextTabView) { mNextTabView.setVisibility(View.GONE); } } String bubblePosition = Controller.getInstance().getPreferences() .getString(Constants.PREFERENCES_GENERAL_BUBBLE_POSITION, "right"); if (bubblePosition.equals("right")) { mBubbleRightView.setVisibility(View.VISIBLE); mBubbleLeftView.setVisibility(View.GONE); } else if (bubblePosition.equals("left")) { mBubbleRightView.setVisibility(View.GONE); mBubbleLeftView.setVisibility(View.VISIBLE); } else if (bubblePosition.equals("both")) { mBubbleRightView.setVisibility(View.VISIBLE); mBubbleLeftView.setVisibility(View.VISIBLE); } else { mBubbleRightView.setVisibility(View.VISIBLE); mBubbleLeftView.setVisibility(View.GONE); } } mUrlBarVisible = false; } } private void showFindDialog() { setFindBarVisibility(true); mCurrentWebView.doSetFindIsUp(true); CharSequence text = mFindText.getText(); if (text.length() > 0) { mFindText.setSelection(0, text.length()); doFind(); } else { mFindPreviousButton.setEnabled(false); mFindNextButton.setEnabled(false); } mFindText.requestFocus(); showKeyboardForFindDialog(); } private void showKeyboardForFindDialog() { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.showSoftInput(mFindText, InputMethodManager.SHOW_IMPLICIT); } /** * Show the next tab, if any. */ private void showNextTab(boolean resetToolbarsRunnable) { if (mViewFlipper.getChildCount() > 1) { if (mFindDialogVisible) { closeFindDialog(); } mCurrentWebView.doOnPause(); mViewFlipper.setInAnimation(AnimationManager.getInstance().getInFromRightAnimation()); mViewFlipper.setOutAnimation(AnimationManager.getInstance().getOutToLeftAnimation()); mViewFlipper.showNext(); mCurrentWebView = mWebViews.get(mViewFlipper.getDisplayedChild()); mCurrentWebView.doOnResume(); if (resetToolbarsRunnable) { startToolbarsHideRunnable(); } showToastOnTabSwitch(); updatePreviousNextTabViewsVisibility(); updateUI(); } } /** * Show the previous tab, if any. */ private void showPreviousTab(boolean resetToolbarsRunnable) { if (mViewFlipper.getChildCount() > 1) { if (mFindDialogVisible) { closeFindDialog(); } mCurrentWebView.doOnPause(); mViewFlipper.setInAnimation(AnimationManager.getInstance().getInFromLeftAnimation()); mViewFlipper.setOutAnimation(AnimationManager.getInstance().getOutToRightAnimation()); mViewFlipper.showPrevious(); mCurrentWebView = mWebViews.get(mViewFlipper.getDisplayedChild()); mCurrentWebView.doOnResume(); if (resetToolbarsRunnable) { startToolbarsHideRunnable(); } showToastOnTabSwitch(); updatePreviousNextTabViewsVisibility(); updateUI(); } } /** * Show a toast alert on tab switch. */ private void showToastOnTabSwitch() { if (Controller.getInstance().getPreferences() .getBoolean(Constants.PREFERENCES_SHOW_TOAST_ON_TAB_SWITCH, true)) { String text; if (mCurrentWebView.getTitle() != null) { text = String.format(getString(R.string.Main_ToastTabSwitchFullMessage), mViewFlipper.getDisplayedChild() + 1, mCurrentWebView.getTitle()); } else { text = String.format(getString(R.string.Main_ToastTabSwitchMessage), mViewFlipper.getDisplayedChild() + 1); } Toast.makeText(this, text, Toast.LENGTH_SHORT).show(); } } /** * Start a runnable to update history. * * @param title * The page title. * @param url * The page url. */ private void startHistoryUpdaterRunnable(String title, String url, String originalUrl) { if ((url != null) && (url.length() > 0)) { new Thread(new HistoryUpdater(this, title, url, originalUrl)).start(); } } /** * Thread to delay the show of the find dialog. This seems to be necessary * when shown from a QuickAction. If not, the keyboard does not show. 50ms * seems to be enough on a Nexus One and on the (rather) slow emulator. * Dirty hack :( */ private void startShowFindDialogRunnable() { new Thread(new Runnable() { private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { showFindDialog(); } }; @Override public void run() { try { Thread.sleep(50); mHandler.sendEmptyMessage(0); } catch (InterruptedException e) { mHandler.sendEmptyMessage(0); } } }).start(); } /** * Start a runnable to hide the tool bars after a user-defined delay. */ private void startToolbarsHideRunnable() { if (mHideToolbarsRunnable != null) { mHideToolbarsRunnable.setDisabled(); } int delay = Integer.parseInt(Controller.getInstance().getPreferences() .getString(Constants.PREFERENCES_GENERAL_BARS_DURATION, "3000")); if (delay <= 0) { delay = 3000; } mHideToolbarsRunnable = new HideToolbarsRunnable(this, delay); new Thread(mHideToolbarsRunnable).start(); } /** * Select Text in the webview and automatically sends the selected text to * the clipboard. */ public void swithToSelectAndCopyTextMode() { try { KeyEvent shiftPressEvent = new KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_SHIFT_LEFT, 0, 0); shiftPressEvent.dispatch(mCurrentWebView); } catch (Exception e) { throw new AssertionError(e); } } /** * Update the fav icon display. */ private void updateFavIcon() { BitmapDrawable favicon = getNormalizedFavicon(); if (mCurrentWebView.getFavicon() != null) { mToolsButton.setImageDrawable(favicon); } else { mToolsButton.setImageResource(R.drawable.fav_icn_default_toolbar); } } /** * Update the "Go" button image. */ private void updateGoButton() { if (mCurrentWebView.isLoading()) { mGoButton.setImageResource(R.drawable.ic_btn_stop); mUrlEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, mCircularProgress, null); ((AnimationDrawable) mCircularProgress).start(); } else { if (!mCurrentWebView.isSameUrl(mUrlEditText.getText().toString())) { mGoButton.setImageResource(R.drawable.ic_btn_go); } else { mGoButton.setImageResource(R.drawable.ic_btn_reload); } mUrlEditText.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null); ((AnimationDrawable) mCircularProgress).stop(); } } private void updatePreviousNextTabViewsVisibility() { if ((mUrlBarVisible) && (isSwitchTabsByButtonsEnabled())) { if (mViewFlipper.getDisplayedChild() > 0) { mPreviousTabView.setVisibility(View.VISIBLE); } else { mPreviousTabView.setVisibility(View.GONE); } if (mViewFlipper.getDisplayedChild() < mViewFlipper.getChildCount() - 1) { mNextTabView.setVisibility(View.VISIBLE); } else { mNextTabView.setVisibility(View.GONE); } } else { mPreviousTabView.setVisibility(View.GONE); mNextTabView.setVisibility(View.GONE); } } private void updateSwitchTabsMethod() { String method = PreferenceManager.getDefaultSharedPreferences(this).getString( Constants.PREFERENCES_GENERAL_SWITCH_TABS_METHOD, "buttons"); if (method.equals("buttons")) { mSwitchTabsMethod = SwitchTabsMethod.BUTTONS; } else if (method.equals("fling")) { mSwitchTabsMethod = SwitchTabsMethod.FLING; } else if (method.equals("both")) { mSwitchTabsMethod = SwitchTabsMethod.BOTH; } else { mSwitchTabsMethod = SwitchTabsMethod.BUTTONS; } } /** * Update the application title. */ private void updateTitle() { String value = mCurrentWebView.getTitle(); if ((value != null) && (value.length() > 0)) { this.setTitle(String.format(getResources().getString(R.string.ApplicationNameUrl), value)); } else { clearTitle(); } } /** * Update the UI: Url edit text, previous/next button state,... */ private void updateUI() { mUrlEditText.removeTextChangedListener(mUrlTextWatcher); mUrlEditText.setText(mCurrentWebView.getUrl()); mUrlEditText.addTextChangedListener(mUrlTextWatcher); mPreviousButton.setEnabled(mCurrentWebView.canGoBack()); mNextButton.setEnabled(mCurrentWebView.canGoForward()); mRemoveTabButton.setEnabled(mViewFlipper.getChildCount() > 1); mProgressBar.setProgress(mCurrentWebView.getProgress()); updateGoButton(); updateTitle(); updateFavIcon(); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/activities/MainActivity.java
Java
gpl3
55,328
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.components; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.ui.activities.MainActivity; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import org.gaeproxy.zirco.utils.UrlUtils; import android.graphics.Bitmap; import android.net.http.SslError; import android.util.Log; import android.webkit.SslErrorHandler; import android.webkit.WebView; import android.webkit.WebView.HitTestResult; import android.webkit.WebViewClient; /** * Convenient extension of WebViewClient. */ public class CustomWebViewClient extends WebViewClient { private MainActivity mMainActivity; public CustomWebViewClient(MainActivity mainActivity) { super(); mMainActivity = mainActivity; } @Override public void onLoadResource(WebView view, String url) { // Some dirty stuff for handling m.youtube.com. May break in the future // ? if (url.startsWith("http://s.youtube.com/s?ns=yt&ps=blazer&playback=1&el=detailpage&app=youtube_mobile")) { try { int startIndex = url.indexOf("&docid=") + 7; int endIndex = url.indexOf("&", startIndex); String videoId = url.substring(startIndex, endIndex); mMainActivity.onVndUrl("vnd.youtube:" + videoId); } catch (Exception e) { Log.e("onLoadResource", "Unable to parse YouTube url: " + url); } } super.onLoadResource(view, url); } @Override public void onPageFinished(WebView view, String url) { ((CustomWebView) view).notifyPageFinished(); mMainActivity.onPageFinished(url); super.onPageFinished(view, url); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { // Some magic here: when performing WebView.loadDataWithBaseURL, the url // is "file:///android_asset/startpage, // whereas when the doing a "previous" or "next", the url is // "about:start", and we need to perform the // loadDataWithBaseURL here, otherwise it won't load. if (url.equals(Constants.URL_ABOUT_START)) { view.loadDataWithBaseURL("file:///android_asset/startpage/", ApplicationUtils.getStartPage(view.getContext()), "text/html", "UTF-8", "about:start"); } ((CustomWebView) view).notifyPageStarted(); mMainActivity.onPageStarted(url); super.onPageStarted(view, url, favicon); } @Override public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) { handler.proceed(); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("vnd.")) { mMainActivity.onVndUrl(url); return true; } else if (url.startsWith(Constants.URL_ACTION_SEARCH)) { String searchTerm = url.replace(Constants.URL_ACTION_SEARCH, ""); String searchUrl = Controller .getInstance() .getPreferences() .getString(Constants.PREFERENCES_GENERAL_SEARCH_URL, Constants.URL_SEARCH_GOOGLE); String newUrl = String.format(searchUrl, searchTerm); if (view != null) view.loadUrl(newUrl); return true; } else if (view != null && view.getHitTestResult() != null && view.getHitTestResult().getType() == HitTestResult.EMAIL_TYPE) { mMainActivity.onMailTo(url); return true; } else { // If the url is not from GWT mobile view, and is in the mobile view // url list, then load it with GWT. if ((!url.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT)) && (UrlUtils.checkInMobileViewUrlList(view.getContext(), url))) { String newUrl = String.format(Constants.URL_GOOGLE_MOBILE_VIEW, url); if (view != null) view.loadUrl(newUrl); return true; } else { ((CustomWebView) view).resetLoadedUrl(); mMainActivity.onUrlLoading(url); return false; } } } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/components/CustomWebViewClient.java
Java
gpl3
4,267
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.components; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.gaeproxy.ProxySettings; import org.gaeproxy.zirco.controllers.Controller; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.Constants; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceManager; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.view.View; import android.webkit.CookieManager; import android.webkit.WebSettings; import android.webkit.WebSettings.PluginState; import android.webkit.WebSettings.ZoomDensity; import android.webkit.WebView; /** * A convenient extension of WebView. */ public class CustomWebView extends WebView { private Context mContext; private int mProgress = 100; private boolean mIsLoading = false; private String mLoadedUrl; private static boolean mBoMethodsLoaded = false; private static Method mOnPauseMethod = null; private static Method mOnResumeMethod = null; private static Method mSetFindIsUp = null; private static Method mNotifyFindDialogDismissed = null; /** * Constructor. * * @param context * The current context. */ public CustomWebView(Context context) { super(context); mContext = context; initializeOptions(); loadMethods(); } /** * Constructor. * * @param context * The current context. * @param attrs * The attribute set. */ public CustomWebView(Context context, AttributeSet attrs) { super(context, attrs); mContext = context; initializeOptions(); loadMethods(); } public void doNotifyFindDialogDismissed() { if (mNotifyFindDialogDismissed != null) { try { mNotifyFindDialogDismissed.invoke(this); } catch (IllegalArgumentException e) { Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + e.getMessage()); } catch (IllegalAccessException e) { Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + e.getMessage()); } catch (InvocationTargetException e) { Log.e("CustomWebView", "doNotifyFindDialogDismissed(): " + e.getMessage()); } } } /** * Perform an 'onPause' on this WebView through reflexion. */ public void doOnPause() { if (mOnPauseMethod != null) { try { mOnPauseMethod.invoke(this); } catch (IllegalArgumentException e) { Log.e("CustomWebView", "doOnPause(): " + e.getMessage()); } catch (IllegalAccessException e) { Log.e("CustomWebView", "doOnPause(): " + e.getMessage()); } catch (InvocationTargetException e) { Log.e("CustomWebView", "doOnPause(): " + e.getMessage()); } } } /** * Perform an 'onResume' on this WebView through reflexion. */ public void doOnResume() { if (mOnResumeMethod != null) { try { mOnResumeMethod.invoke(this); } catch (IllegalArgumentException e) { Log.e("CustomWebView", "doOnResume(): " + e.getMessage()); } catch (IllegalAccessException e) { Log.e("CustomWebView", "doOnResume(): " + e.getMessage()); } catch (InvocationTargetException e) { Log.e("CustomWebView", "doOnResume(): " + e.getMessage()); } } } public void doSetFindIsUp(boolean value) { if (mSetFindIsUp != null) { try { mSetFindIsUp.invoke(this, value); } catch (IllegalArgumentException e) { Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage()); } catch (IllegalAccessException e) { Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage()); } catch (InvocationTargetException e) { Log.e("CustomWebView", "doSetFindIsUp(): " + e.getMessage()); } } } /** * Get the loaded url, e.g. the one asked by the user, without redirections. * * @return The loaded url. */ public String getLoadedUrl() { return mLoadedUrl; } /** * Get the current loading progress of the view. * * @return The current loading progress of the view. */ @Override public int getProgress() { return mProgress; } private void initializeProxy() { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(mContext); int port = 1984; try { port = Integer.valueOf(settings.getString("port", "1984")); } catch (NumberFormatException ignore) { } ProxySettings.setProxy(mContext, "127.0.0.1", port); } /** * Initialize the WebView with the options set by the user through * preferences. */ public void initializeOptions() { initializeProxy(); WebSettings settings = getSettings(); // User settings settings.setJavaScriptEnabled(Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_ENABLE_JAVASCRIPT, true)); settings.setLoadsImagesAutomatically(Controller.getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_ENABLE_IMAGES, true)); settings.setUseWideViewPort(Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_USE_WIDE_VIEWPORT, true)); settings.setLoadWithOverviewMode(Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_LOAD_WITH_OVERVIEW, false)); settings.setSaveFormData(Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_ENABLE_FORM_DATA, true)); settings.setSavePassword(Controller .getInstance() .getPreferences() .getBoolean(Constants.PREFERENCES_BROWSER_ENABLE_PASSWORDS, true)); settings.setDefaultZoom(ZoomDensity.valueOf(Controller .getInstance() .getPreferences() .getString(Constants.PREFERENCES_DEFAULT_ZOOM_LEVEL, ZoomDensity.MEDIUM.toString()))); settings.setUserAgentString(Controller .getInstance() .getPreferences() .getString(Constants.PREFERENCES_BROWSER_USER_AGENT, Constants.USER_AGENT_DEFAULT)); CookieManager.getInstance().setAcceptCookie( Controller .getInstance() .getPreferences() .getBoolean( Constants.PREFERENCES_BROWSER_ENABLE_COOKIES, true)); if (Build.VERSION.SDK_INT <= 7) { settings.setPluginsEnabled(Controller .getInstance() .getPreferences() .getBoolean( Constants.PREFERENCES_BROWSER_ENABLE_PLUGINS_ECLAIR, true)); } else { settings.setPluginState(PluginState.valueOf(Controller .getInstance() .getPreferences() .getString(Constants.PREFERENCES_BROWSER_ENABLE_PLUGINS, PluginState.ON_DEMAND.toString()))); } settings.setSupportZoom(true); // Technical settings settings.setSupportMultipleWindows(true); setLongClickable(true); setScrollbarFadingEnabled(true); setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY); setDrawingCacheEnabled(true); settings.setAppCacheEnabled(true); settings.setDatabaseEnabled(true); settings.setDomStorageEnabled(true); } /** * Check if the view is currently loading. * * @return True if the view is currently loading. */ public boolean isLoading() { return mIsLoading; } public boolean isSameUrl(String url) { if (url != null) { return url.equalsIgnoreCase(this.getUrl()); } return false; } /** * Inject the AdSweep javascript. */ public void loadAdSweep() { super.loadUrl(ApplicationUtils.getAdSweepString(mContext)); } /** * Load static reflected methods. */ private void loadMethods() { if (!mBoMethodsLoaded) { try { mOnPauseMethod = WebView.class.getMethod("onPause"); mOnResumeMethod = WebView.class.getMethod("onResume"); } catch (SecurityException e) { Log.e("CustomWebView", "loadMethods(): " + e.getMessage()); mOnPauseMethod = null; mOnResumeMethod = null; } catch (NoSuchMethodException e) { Log.e("CustomWebView", "loadMethods(): " + e.getMessage()); mOnPauseMethod = null; mOnResumeMethod = null; } try { mSetFindIsUp = WebView.class.getMethod("setFindIsUp", Boolean.TYPE); mNotifyFindDialogDismissed = WebView.class .getMethod("notifyFindDialogDismissed"); } catch (SecurityException e) { Log.e("CustomWebView", "loadMethods(): " + e.getMessage()); mSetFindIsUp = null; mNotifyFindDialogDismissed = null; } catch (NoSuchMethodException e) { Log.e("CustomWebView", "loadMethods(): " + e.getMessage()); mSetFindIsUp = null; mNotifyFindDialogDismissed = null; } mBoMethodsLoaded = true; } } @Override public void loadUrl(String url) { mLoadedUrl = url; super.loadUrl(url); } /** * Triggered when the page has finished loading. */ public void notifyPageFinished() { mProgress = 100; mIsLoading = false; } /** * Triggered when a new page loading is requested. */ public void notifyPageStarted() { mIsLoading = true; } @Override public boolean onTouchEvent(MotionEvent ev) { final int action = ev.getAction(); // Enable / disable zoom support in case of multiple pointer, e.g. // enable zoom when we have two down pointers, disable with one pointer // or when pointer up. // We do this to prevent the display of zoom controls, which are not // useful and override over the right bubble. if ((action == MotionEvent.ACTION_DOWN) || (action == MotionEvent.ACTION_POINTER_DOWN) || (action == MotionEvent.ACTION_POINTER_1_DOWN) || (action == MotionEvent.ACTION_POINTER_2_DOWN) || (action == MotionEvent.ACTION_POINTER_3_DOWN)) { if (ev.getPointerCount() > 1) { this.getSettings().setBuiltInZoomControls(true); this.getSettings().setSupportZoom(true); } else { this.getSettings().setBuiltInZoomControls(false); this.getSettings().setSupportZoom(false); } } else if ((action == MotionEvent.ACTION_UP) || (action == MotionEvent.ACTION_POINTER_UP) || (action == MotionEvent.ACTION_POINTER_1_UP) || (action == MotionEvent.ACTION_POINTER_2_UP) || (action == MotionEvent.ACTION_POINTER_3_UP)) { this.getSettings().setBuiltInZoomControls(false); this.getSettings().setSupportZoom(false); } return super.onTouchEvent(ev); } /** * Reset the loaded url. */ public void resetLoadedUrl() { mLoadedUrl = null; } /** * Set the current loading progress of this view. * * @param progress * The current loading progress. */ public void setProgress(int progress) { mProgress = progress; } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/components/CustomWebView.java
Java
gpl3
10,981
package org.gaeproxy.zirco.ui.runnables; import java.io.File; import java.io.IOException; import java.net.URLDecoder; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.gaeproxy.R; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.DateUtils; import org.gaeproxy.zirco.utils.IOUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import android.app.ProgressDialog; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.Log; /** * Runnable to import history and bookmarks from an XML file. */ public class XmlHistoryBookmarksImporter implements Runnable { private Context mContext; private String mFileName; private ProgressDialog mProgressDialog; private String mErrorMessage = null; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (mProgressDialog != null) { mProgressDialog.dismiss(); } if (mErrorMessage != null) { ApplicationUtils .showOkDialog( mContext, android.R.drawable.ic_dialog_alert, mContext.getResources() .getString( R.string.Commons_HistoryBookmarksImportSDCardFailedTitle), String.format( mContext.getResources() .getString( R.string.Commons_HistoryBookmarksFailedMessage), mErrorMessage)); } } }; /** * Constructor. * * @param context * The current context. * @param fileName * The file to import. * @param progressDialog * The progress dialog shown during import. */ public XmlHistoryBookmarksImporter(Context context, String fileName, ProgressDialog progressDialog) { mContext = context; mFileName = fileName; mProgressDialog = progressDialog; } /** * Get the content of a node, why Android does not include * Node.getTextContent() ? * * @param node * The node. * @return The node content. */ private String getNodeContent(Node node) { StringBuffer buffer = new StringBuffer(); NodeList childList = node.getChildNodes(); for (int i = 0; i < childList.getLength(); i++) { Node child = childList.item(i); if (child.getNodeType() != Node.TEXT_NODE) { continue; // skip non-text nodes } buffer.append(child.getNodeValue()); } return buffer.toString(); } @Override public void run() { File file = new File(IOUtils.getBookmarksExportFolder(), mFileName); if ((file != null) && (file.exists()) && (file.canRead())) { try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); DocumentBuilder builder; builder = factory.newDocumentBuilder(); Document document = builder.parse(file); Element root = document.getDocumentElement(); if ((root != null) && (root.getNodeName().equals("itemlist"))) { NodeList itemsList = root.getElementsByTagName("item"); Node item; NodeList record; Node dataItem; for (int i = 0; i < itemsList.getLength(); i++) { item = itemsList.item(i); if (item != null) { record = item.getChildNodes(); String title = null; String url = null; int visits = 0; long date = -1; long created = -1; int bookmark = 0; for (int j = 0; j < record.getLength(); j++) { dataItem = record.item(j); if ((dataItem != null) && (dataItem.getNodeName() != null)) { if (dataItem.getNodeName().equals("title")) { title = URLDecoder .decode(getNodeContent(dataItem)); } else if (dataItem.getNodeName().equals( "url")) { url = URLDecoder .decode(getNodeContent(dataItem)); } else if (dataItem.getNodeName().equals( "visits")) { try { visits = Integer .parseInt(getNodeContent(dataItem)); } catch (Exception e) { visits = 0; } } else if (dataItem.getNodeName().equals( "date")) { try { date = Long .parseLong(getNodeContent(dataItem)); } catch (Exception e) { date = -1; } } else if (dataItem.getNodeName().equals( "created")) { try { created = Long .parseLong(getNodeContent(dataItem)); } catch (Exception e) { created = -1; } } else if (dataItem.getNodeName().equals( "bookmark")) { try { bookmark = Integer .parseInt(getNodeContent(dataItem)); } catch (Exception e) { bookmark = 0; } } } } BookmarksProviderWrapper.insertRawRecord( mContext.getContentResolver(), title, url, visits, date, created, bookmark); } } } else if ((root != null) && (root.getNodeName().equals("bookmarkslist"))) { // Old export format (before 0.4.0). NodeList bookmarksList = root .getElementsByTagName("bookmark"); Node bookmark; NodeList bookmarkItems; String title; String url; String creationDate; int count; long date = -1; long created = -1; Node item; for (int i = 0; i < bookmarksList.getLength(); i++) { bookmark = bookmarksList.item(i); if (bookmark != null) { title = null; url = null; creationDate = null; count = 0; bookmarkItems = bookmark.getChildNodes(); for (int j = 0; j < bookmarkItems.getLength(); j++) { item = bookmarkItems.item(j); if ((item != null) && (item.getNodeName() != null)) { if (item.getNodeName().equals("title")) { title = getNodeContent(item); } else if (item.getNodeName().equals("url")) { url = URLDecoder .decode(getNodeContent(item)); } else if (item.getNodeName().equals( "creationdate")) { creationDate = getNodeContent(item); date = DateUtils.convertFromDatabase( mContext, creationDate) .getTime(); created = date; } else if (item.getNodeName().equals( "count")) { try { count = Integer .parseInt(getNodeContent(item)); } catch (Exception e) { count = 0; } } } } BookmarksProviderWrapper.insertRawRecord( mContext.getContentResolver(), title, url, count, date, created, 1); } } } } catch (ParserConfigurationException e) { Log.w("Bookmark import failed", e.getMessage()); mErrorMessage = e.toString(); } catch (SAXException e) { Log.w("Bookmark import failed", e.getMessage()); mErrorMessage = e.toString(); } catch (IOException e) { Log.w("Bookmark import failed", e.getMessage()); mErrorMessage = e.toString(); } } mHandler.sendEmptyMessage(0); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/XmlHistoryBookmarksImporter.java
Java
gpl3
7,596
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.runnables; import org.gaeproxy.zirco.ui.activities.IToolbarsContainer; import android.os.Handler; import android.os.Message; import android.util.Log; /** * A runnable to hide tool bars after the given delay. */ public class HideToolbarsRunnable implements Runnable { private static final String TAG = "HideToolbarsRunnable"; private IToolbarsContainer mParent; private boolean mDisabled; private int mDelay; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if ((mParent != null) && (!mDisabled)) { mParent.hideToolbars(); } } }; /** * Constructor. * * @param parent * The parent tool bar container. * @param delay * The delay before hiding, in milliseconds. */ public HideToolbarsRunnable(IToolbarsContainer parent, int delay) { mParent = parent; mDisabled = false; mDelay = delay; } @Override public void run() { try { Thread.sleep(mDelay); mHandler.sendEmptyMessage(0); } catch (InterruptedException e) { Log.w(TAG, "Exception in thread: " + e.getMessage()); mHandler.sendEmptyMessage(0); } } /** * Disable this runnable. */ public void setDisabled() { mDisabled = true; } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/HideToolbarsRunnable.java
Java
gpl3
1,802
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.runnables; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import org.gaeproxy.zirco.utils.Constants; import android.content.Context; import android.preference.PreferenceManager; /** * Runnable to update and truncate the history in background. */ public class HistoryUpdater implements Runnable { private Context mContext; private String mTitle; private String mUrl; private String mOriginalUrl; /** * Constructor. * * @param context * The current context. * @param title * The title. * @param url * The url. */ public HistoryUpdater(Context context, String title, String url, String originalUrl) { mContext = context; mTitle = title; mUrl = url; mOriginalUrl = originalUrl; if (mUrl.startsWith(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT)) { mUrl = mUrl.substring(Constants.URL_GOOGLE_MOBILE_VIEW_NO_FORMAT .length()); } } @Override public void run() { BookmarksProviderWrapper.updateHistory(mContext.getContentResolver(), mTitle, mUrl, mOriginalUrl); BookmarksProviderWrapper.truncateHistory( mContext.getContentResolver(), PreferenceManager.getDefaultSharedPreferences(mContext) .getString(Constants.PREFERENCES_BROWSER_HISTORY_SIZE, "90")); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/HistoryUpdater.java
Java
gpl3
1,852
package org.gaeproxy.zirco.ui.runnables; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.URLEncoder; import org.gaeproxy.R; import org.gaeproxy.zirco.utils.ApplicationUtils; import org.gaeproxy.zirco.utils.IOUtils; import android.app.ProgressDialog; import android.content.Context; import android.database.Cursor; import android.os.Handler; import android.os.Message; import android.provider.Browser; import android.util.Log; /** * Runnable to export history and bookmarks to an XML file. */ public class XmlHistoryBookmarksExporter implements Runnable { private Context mContext; private ProgressDialog mProgressDialog; private String mFileName; private Cursor mCursor; private File mFile; private String mErrorMessage = null; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (mProgressDialog != null) { mProgressDialog.dismiss(); } if (mContext != null) { if (mErrorMessage == null) { ApplicationUtils .showOkDialog( mContext, android.R.drawable.ic_dialog_info, mContext.getResources() .getString( R.string.Commons_HistoryBookmarksExportSDCardDoneTitle), String.format( mContext.getResources() .getString( R.string.Commons_HistoryBookmarksExportSDCardDoneMessage), mFile.getAbsolutePath())); } else { ApplicationUtils .showOkDialog( mContext, android.R.drawable.ic_dialog_alert, mContext.getResources() .getString( R.string.Commons_HistoryBookmarksExportSDCardFailedTitle), String.format( mContext.getResources() .getString( R.string.Commons_HistoryBookmarksFailedMessage), mErrorMessage)); } } } }; /** * Constructor. * * @param context * The current context. * @param fileName * The output file. * @param cursor * The cursor to history and bookmarks. * @param progressDialog * The progress dialog shown during export. */ public XmlHistoryBookmarksExporter(Context context, String fileName, Cursor cursor, ProgressDialog progressDialog) { mContext = context; mFileName = fileName; mCursor = cursor; mProgressDialog = progressDialog; } @Override public void run() { try { mFile = new File(IOUtils.getBookmarksExportFolder(), mFileName); FileWriter writer = new FileWriter(mFile); writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); writer.write("<itemlist>\n"); if (mCursor.moveToFirst()) { int titleIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.TITLE); int urlIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.URL); int visitsIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.VISITS); int dateIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.DATE); int createdIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.CREATED); int bookmarkIndex = mCursor .getColumnIndex(Browser.BookmarkColumns.BOOKMARK); while (!mCursor.isAfterLast()) { writer.write("<item>\n"); String title = mCursor.getString(titleIndex); writer.write(String.format("<title>%s</title>\n", title != null ? URLEncoder.encode(title) : "")); String url = mCursor.getString(urlIndex); writer.write(String.format("<url>%s</url>\n", url != null ? URLEncoder.encode(url) : "")); writer.write(String.format("<created>%s</created>\n", mCursor.getLong(createdIndex))); writer.write(String.format("<visits>%s</visits>\n", mCursor.getInt(visitsIndex))); writer.write(String.format("<date>%s</date>\n", mCursor.getLong(dateIndex))); writer.write(String.format("<bookmark>%s</bookmark>\n", mCursor.getInt(bookmarkIndex))); writer.write("</item>\n"); mCursor.moveToNext(); } } writer.write("</itemlist>\n"); writer.flush(); writer.close(); } catch (IOException e1) { Log.w("Bookmark export failed", e1.toString()); mErrorMessage = e1.toString(); } mHandler.sendEmptyMessage(0); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/XmlHistoryBookmarksExporter.java
Java
gpl3
4,276
/* * Zirco Browser for Android * * Copyright (C) 2010 J. Devauchelle and contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package org.gaeproxy.zirco.ui.runnables; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import org.gaeproxy.zirco.model.items.DownloadItem; import org.gaeproxy.zirco.utils.IOUtils; import android.os.Handler; import android.os.Message; /** * Background downloader. */ public class DownloadRunnable implements Runnable { private static final int BUFFER_SIZE = 4096; private DownloadItem mParent; private boolean mAborted; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { mParent.onFinished(); } }; /** * Contructor. * * @param parent * The item to download. */ public DownloadRunnable(DownloadItem parent) { mParent = parent; mAborted = false; } /** * Abort this download. */ public void abort() { mAborted = true; } /** * Get a file object representation of the file name, in th right folder of * the SD card. * * @return A file object. */ private File getFile() { File downloadFolder = IOUtils.getDownloadFolder(); if (downloadFolder != null) { return new File(downloadFolder, getFileNameFromUrl()); } else { mParent.setErrorMessage("Unable to get download folder from SD Card."); return null; } } /** * Compute the file name given the url. * * @return The file name. */ private String getFileNameFromUrl() { return mParent.getUrl() .substring(mParent.getUrl().lastIndexOf("/") + 1); } @Override public void run() { File downloadFile = getFile(); if (downloadFile != null) { if (downloadFile.exists()) { downloadFile.delete(); } BufferedInputStream bis = null; BufferedOutputStream bos = null; try { mParent.onStart(); URL url = new URL(mParent.getUrl()); URLConnection conn = url.openConnection(); InputStream is = conn.getInputStream(); int size = conn.getContentLength(); double oldCompleted = 0; double completed = 0; bis = new BufferedInputStream(is); bos = new BufferedOutputStream(new FileOutputStream( downloadFile)); boolean downLoading = true; byte[] buffer = new byte[BUFFER_SIZE]; int downloaded = 0; int read; int stepRead = 0; while ((downLoading) && (!mAborted)) { if ((size - downloaded < BUFFER_SIZE) && (size - downloaded > 0)) { buffer = new byte[size - downloaded]; } read = bis.read(buffer); if (read > 0) { bos.write(buffer, 0, read); downloaded += read; completed = ((downloaded * 100f) / size); stepRead++; } else { downLoading = false; } // Notify each 5% or more. if (oldCompleted + 5 < completed) { mParent.onProgress((int) completed); oldCompleted = completed; } } } catch (MalformedURLException mue) { mParent.setErrorMessage(mue.getMessage()); } catch (IOException ioe) { mParent.setErrorMessage(ioe.getMessage()); } finally { if (bis != null) { try { bis.close(); } catch (IOException ioe) { mParent.setErrorMessage(ioe.getMessage()); } } if (bos != null) { try { bos.close(); } catch (IOException ioe) { mParent.setErrorMessage(ioe.getMessage()); } } } if (mAborted) { if (downloadFile.exists()) { downloadFile.delete(); } } } mHandler.sendEmptyMessage(0); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/DownloadRunnable.java
Java
gpl3
4,154
package org.gaeproxy.zirco.ui.runnables; import org.gaeproxy.zirco.providers.BookmarksProviderWrapper; import android.app.Activity; import android.graphics.Bitmap; /** * Runnable to update database favicon. */ public class FaviconUpdaterRunnable implements Runnable { private Activity mActivity; private String mUrl; private String mOriginalUrl; private Bitmap mFavIcon; /** * Constructor. * * @param activity * The parent activity. * @param url * The page url. * @param originalUrl * The page original url. * @param favicon * The favicon. */ public FaviconUpdaterRunnable(Activity activity, String url, String originalUrl, Bitmap favicon) { mActivity = activity; mUrl = url; mOriginalUrl = originalUrl; mFavIcon = favicon; } @Override public void run() { BookmarksProviderWrapper.updateFavicon(mActivity, mUrl, mOriginalUrl, mFavIcon); } }
zyh3290-proxy
src/org/gaeproxy/zirco/ui/runnables/FaviconUpdaterRunnable.java
Java
gpl3
944
package org.gaeproxy; import java.io.IOException; import java.net.Socket; import android.util.Log; public class InnerSocketBuilder { private String proxyHost = "127.0.0.1"; private int proxyPort = 1053; private Socket innerSocket = null; private boolean isConnected = false; private final String TAG = "CMWRAP->InnerSocketBuilder"; /** * 建立经由代理服务器至目标服务器的连接 * * @param proxyHost * 代理服务器地址 * @param proxyPort * 代理服务器端口 * @param target * 目标服务器 */ public InnerSocketBuilder(String proxyHost, int proxyPort, String target) { this.proxyHost = proxyHost; this.proxyPort = proxyPort; connect(); } private void connect() { // starTime = System.currentTimeMillis(); Log.v(TAG, "建立通道"); try { innerSocket = new Socket(proxyHost, proxyPort); innerSocket.setKeepAlive(true); innerSocket.setSoTimeout(60 * 1000); isConnected = true; } catch (IOException e) { Log.e(TAG, "建立隧道失败:" + e.getLocalizedMessage()); } } public Socket getSocket() { return innerSocket; } public boolean isConnected() { return this.isConnected; } }
zyh3290-proxy
src/org/gaeproxy/InnerSocketBuilder.java
Java
gpl3
1,221
package org.gaeproxy.db; import java.sql.SQLException; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.util.Log; import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; import com.j256.ormlite.dao.Dao; import com.j256.ormlite.support.ConnectionSource; import com.j256.ormlite.table.TableUtils; /** * Database helper class used to manage the creation and upgrading of your * database. This class also usually provides the DAOs used by the other * classes. */ public class DatabaseHelper extends OrmLiteSqliteOpenHelper { // name of the database file for your application -- change to something // appropriate for your app private static final String DATABASE_NAME = "dnscache.db"; // any time you make changes to your database objects, you may have to // increase the database version private static final int DATABASE_VERSION = 3; // the DAO object we use to access the SimpleData table private Dao<DNSResponse, String> dnsCacheDao = null; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * Close the database connections and clear any cached DAOs. */ @Override public void close() { super.close(); dnsCacheDao = null; } /** * Returns the Database Access Object (DAO) for our SimpleData class. It * will create it or just give the cached value. */ public Dao<DNSResponse, String> getDNSCacheDao() throws SQLException { if (dnsCacheDao == null) { dnsCacheDao = getDao(DNSResponse.class); } return dnsCacheDao; } /** * This is called when the database is first created. Usually you should * call createTable statements here to create the tables that will store * your data. */ @Override public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource) { try { Log.i(DatabaseHelper.class.getName(), "onCreate"); TableUtils.createTable(connectionSource, DNSResponse.class); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't create database", e); throw new RuntimeException(e); } } /** * This is called when your application is upgraded and it has a higher * version number. This allows you to adjust the various data to match the * new version number. */ @Override public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) { switch (oldVersion) { default: try { Log.i(DatabaseHelper.class.getName(), "onUpgrade"); TableUtils.dropTable(connectionSource, DNSResponse.class, true); // after we drop the old databases, we create the new ones onCreate(db, connectionSource); } catch (SQLException e) { Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e); throw new RuntimeException(e); } } } }
zyh3290-proxy
src/org/gaeproxy/db/DatabaseHelper.java
Java
gpl3
2,830
/* gaeproxy - GAppProxy / WallProxy client App for Android * Copyright (C) 2011 <max.c.lv@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ___====-_ _-====___ * _--^^^#####// \\#####^^^--_ * _-^##########// ( ) \\##########^-_ * -############// |\^^/| \\############- * _/############// (@::@) \\############\_ * /#############(( \\// ))#############\ * -###############\\ (oo) //###############- * -#################\\ / VV \ //#################- * -###################\\/ \//###################- * _#/|##########/\######( /\ )######/\##########|\#_ * |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \| * ` |/ V V ` V \#\| | | |/#/ V ' V V \| ' * ` ` ` ` / | | | | \ ' ' ' ' * ( | | | | ) * __\ | | | | /__ * (vvv(VVV)(VVV)vvv) * * HERE BE DRAGONS * */ package org.gaeproxy; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; import android.preference.PreferenceManager; import android.telephony.TelephonyManager; import android.util.Log; public class GAEProxyReceiver extends BroadcastReceiver { private String proxy; private String proxyType; private int port; private boolean isAutoConnect = false; private boolean isInstalled = false; private String sitekey; private boolean isGlobalProxy; private boolean isHTTPSProxy; private boolean isGFWList = false; private static final String TAG = "GAEProxy"; @Override public void onReceive(Context context, Intent intent) { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context); String versionName; try { versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName; } catch (NameNotFoundException e) { versionName = "NONE"; } isAutoConnect = settings.getBoolean("isAutoConnect", false); isInstalled = settings.getBoolean(versionName, false); boolean isMarketEnable = settings.getBoolean("isMarketEnable", false); if (isMarketEnable) { TelephonyManager tm = (TelephonyManager) context .getSystemService(Context.TELEPHONY_SERVICE); String countryCode = tm.getSimCountryIso(); try { Log.d(TAG, "Location: " + countryCode); if (countryCode.toLowerCase().equals("cn")) { String command = "setprop gsm.sim.operator.numeric 31026\n" + "setprop gsm.operator.numeric 31026\n" + "setprop gsm.sim.operator.iso-country us\n" + "setprop gsm.operator.iso-country us\n" + "chmod 777 /data/data/com.android.vending/shared_prefs\n" + "chmod 666 /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n" + "setpref com.android.vending vending_preferences boolean metadata_paid_apps_enabled true\n" + "chmod 660 /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n" + "chmod 771 /data/data/com.android.vending/shared_prefs\n" + "setown com.android.vending /data/data/com.android.vending/shared_prefs/vending_preferences.xml\n" + "kill $(ps | grep vending | tr -s ' ' | cut -d ' ' -f2)\n" + "rm -rf /data/data/com.android.vending/cache/*\n"; Utils.runRootCommand(command); } } catch (Exception e) { // Nothing } } if (isAutoConnect && isInstalled) { proxy = settings.getString("proxy", ""); proxyType = settings.getString("proxyType", "GAppProxy"); String portText = settings.getString("port", ""); if (portText != null && portText.length() > 0) { try { port = Integer.valueOf(portText); } catch (NumberFormatException e) { port = 1984; } if (port <= 1024) port = 1984; } else { port = 1984; } sitekey = settings.getString("sitekey", ""); isGlobalProxy = settings.getBoolean("isGlobalProxy", false); isHTTPSProxy = settings.getBoolean("isHTTPSProxy", false); isGFWList = settings.getBoolean("isGFWList", false); Intent it = new Intent(context, GAEProxyService.class); Bundle bundle = new Bundle(); bundle.putString("proxy", proxy); bundle.putString("proxyType", proxyType); bundle.putInt("port", port); bundle.putString("sitekey", sitekey); bundle.putBoolean("isGlobalProxy", isGlobalProxy); bundle.putBoolean("isHTTPSProxy", isHTTPSProxy); bundle.putBoolean("isGFWList", isGFWList); it.putExtras(bundle); context.startService(it); } } }
zyh3290-proxy
src/org/gaeproxy/GAEProxyReceiver.java
Java
gpl3
5,463
/* Copyright (c) 2009, Nathan Freitas, Orbot / The Guardian Project - http://openideals.com/guardian */ /* See LICENSE for licensing information */ package org.gaeproxy; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import java.util.Vector; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.PixelFormat; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.view.WindowManager; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.ArrayAdapter; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.ImageView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.TextView; public class AppManager extends Activity implements OnCheckedChangeListener, OnClickListener { private static class ListEntry { private CheckBox box; private TextView text; private ImageView icon; } public static ProxyedApp[] getProxyedApps(Context context) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); String tordAppString = prefs.getString(PREFS_KEY_PROXYED, ""); String[] tordApps; StringTokenizer st = new StringTokenizer(tordAppString, "|"); tordApps = new String[st.countTokens()]; int tordIdx = 0; while (st.hasMoreTokens()) { tordApps[tordIdx++] = st.nextToken(); } Arrays.sort(tordApps); // else load the apps up PackageManager pMgr = context.getPackageManager(); List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0); Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator(); Vector<ProxyedApp> vectorApps = new Vector<ProxyedApp>(); ApplicationInfo aInfo = null; while (itAppInfo.hasNext()) { aInfo = itAppInfo.next(); // ignore system apps if (aInfo.uid < 10000) continue; ProxyedApp app = new ProxyedApp(); app.setUid(aInfo.uid); app.setUsername(pMgr.getNameForUid(app.getUid())); // check if this application is allowed if (aInfo.packageName != null && aInfo.packageName.equals("org.proxydroid")) { app.setProxyed(true); } else if (Arrays.binarySearch(tordApps, app.getUsername()) >= 0) { app.setProxyed(true); } else { app.setProxyed(false); } vectorApps.add(app); } ProxyedApp[] apps = new ProxyedApp[vectorApps.size()]; vectorApps.toArray(apps); return apps; } private ProxyedApp[] apps = null; private ListView listApps; private AppManager mAppManager; private TextView overlay; private ProgressDialog pd = null; private ListAdapter adapter; private ImageLoader dm; private static final int MSG_LOAD_START = 1; private static final int MSG_LOAD_FINISH = 2; public final static String PREFS_KEY_PROXYED = "Proxyed"; private boolean appsLoaded = false; final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_LOAD_START: pd = ProgressDialog.show(AppManager.this, "", getString(R.string.loading), true, true); break; case MSG_LOAD_FINISH: listApps.setAdapter(adapter); listApps.setOnScrollListener(new OnScrollListener() { boolean visible; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (visible) { String name = apps[firstVisibleItem].getName(); if (name != null && name.length() > 1) overlay.setText(apps[firstVisibleItem] .getName().substring(0, 1)); else overlay.setText("*"); overlay.setVisibility(View.VISIBLE); } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { visible = true; if (scrollState == ListView.OnScrollListener.SCROLL_STATE_IDLE) { overlay.setVisibility(View.INVISIBLE); } } }); if (pd != null) { pd.dismiss(); pd = null; } break; } super.handleMessage(msg); } }; public void getApps(Context context) { SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(context); String tordAppString = prefs.getString(PREFS_KEY_PROXYED, ""); String[] tordApps; StringTokenizer st = new StringTokenizer(tordAppString, "|"); tordApps = new String[st.countTokens()]; int tordIdx = 0; while (st.hasMoreTokens()) { tordApps[tordIdx++] = st.nextToken(); } Arrays.sort(tordApps); Vector<ProxyedApp> vectorApps = new Vector<ProxyedApp>(); // else load the apps up PackageManager pMgr = context.getPackageManager(); List<ApplicationInfo> lAppInfo = pMgr.getInstalledApplications(0); Iterator<ApplicationInfo> itAppInfo = lAppInfo.iterator(); ApplicationInfo aInfo = null; while (itAppInfo.hasNext()) { aInfo = itAppInfo.next(); // ignore system apps if (aInfo.uid < 10000) continue; if (aInfo.processName == null) continue; if (pMgr.getApplicationLabel(aInfo) == null || pMgr.getApplicationLabel(aInfo).toString().equals("")) continue; if (pMgr.getApplicationIcon(aInfo) == null) continue; ProxyedApp tApp = new ProxyedApp(); tApp.setEnabled(aInfo.enabled); tApp.setUid(aInfo.uid); tApp.setUsername(pMgr.getNameForUid(tApp.getUid())); tApp.setProcname(aInfo.processName); tApp.setName(pMgr.getApplicationLabel(aInfo).toString()); // check if this application is allowed if (Arrays.binarySearch(tordApps, tApp.getUsername()) >= 0) { tApp.setProxyed(true); } else { tApp.setProxyed(false); } vectorApps.add(tApp); } apps = new ProxyedApp[vectorApps.size()]; vectorApps.toArray(apps); } private void loadApps() { getApps(this); Arrays.sort(apps, new Comparator<ProxyedApp>() { @Override public int compare(ProxyedApp o1, ProxyedApp o2) { if (o1 == null || o2 == null || o1.getName() == null || o2.getName() == null) return 1; if (o1.isProxyed() == o2.isProxyed()) return o1.getName().compareTo(o2.getName()); if (o1.isProxyed()) return -1; return 1; } }); final LayoutInflater inflater = getLayoutInflater(); adapter = new ArrayAdapter<ProxyedApp>(this, R.layout.layout_apps_item, R.id.itemtext, apps) { @Override public View getView(int position, View convertView, ViewGroup parent) { ListEntry entry; if (convertView == null) { // Inflate a new view convertView = inflater.inflate(R.layout.layout_apps_item, parent, false); entry = new ListEntry(); entry.icon = (ImageView) convertView .findViewById(R.id.itemicon); entry.box = (CheckBox) convertView .findViewById(R.id.itemcheck); entry.text = (TextView) convertView .findViewById(R.id.itemtext); entry.text.setOnClickListener(mAppManager); entry.text.setOnClickListener(mAppManager); convertView.setTag(entry); entry.box.setOnCheckedChangeListener(mAppManager); } else { // Convert an existing view entry = (ListEntry) convertView.getTag(); } final ProxyedApp app = apps[position]; entry.icon.setTag(app.getUid()); dm.DisplayImage(app.getUid(), (Activity) convertView.getContext(), entry.icon); entry.text.setText(app.getName()); final CheckBox box = entry.box; box.setTag(app); box.setChecked(app.isProxyed()); entry.text.setTag(box); return convertView; } }; appsLoaded = true; } /** * Called an application is check/unchecked */ @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { final ProxyedApp app = (ProxyedApp) buttonView.getTag(); if (app != null) { app.setProxyed(isChecked); } saveAppSettings(this); } @Override public void onClick(View v) { CheckBox cbox = (CheckBox) v.getTag(); final ProxyedApp app = (ProxyedApp) cbox.getTag(); if (app != null) { app.setProxyed(!app.isProxyed()); cbox.setChecked(app.isProxyed()); } saveAppSettings(this); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.setContentView(R.layout.layout_apps); this.dm = ImageLoaderFactory.getImageLoader(this); this.overlay = (TextView) View.inflate(this, R.layout.overlay, null); getWindowManager() .addView( overlay, new WindowManager.LayoutParams( LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT)); mAppManager = this; } @Override protected void onResume() { super.onResume(); new Thread() { @Override public void run() { handler.sendEmptyMessage(MSG_LOAD_START); listApps = (ListView) findViewById(R.id.applistview); if (!appsLoaded) loadApps(); handler.sendEmptyMessage(MSG_LOAD_FINISH); } }.start(); } /* * (non-Javadoc) * * @see android.app.Activity#onStop() */ @Override protected void onStop() { super.onStop(); // Log.d(getClass().getName(),"Exiting Preferences"); } public void saveAppSettings(Context context) { if (apps == null) return; SharedPreferences prefs = PreferenceManager .getDefaultSharedPreferences(this); // final SharedPreferences prefs = // context.getSharedPreferences(PREFS_KEY, 0); StringBuilder tordApps = new StringBuilder(); for (int i = 0; i < apps.length; i++) { if (apps[i].isProxyed()) { tordApps.append(apps[i].getUsername()); tordApps.append("|"); } } Editor edit = prefs.edit(); edit.putString(PREFS_KEY_PROXYED, tordApps.toString()); edit.commit(); } }
zyh3290-proxy
src/org/gaeproxy/AppManager.java
Java
gpl3
10,855
package org.gaeproxy; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.http.HttpHost; import android.content.Context; import android.os.Build; import android.util.Log; /** * Utility class for setting WebKit proxy used by Android WebView * */ public class ProxySettings { private static final String TAG = "GAEProxy.ProxySettings"; static final int PROXY_CHANGED = 193; private static Object getDeclaredField(Object obj, String name) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = obj.getClass().getDeclaredField(name); f.setAccessible(true); Object out = f.get(obj); // System.out.println(obj.getClass().getName() + "." + name + " = "+ // out); return out; } public static Object getRequestQueue(Context ctx) throws Exception { Object ret = null; Class networkClass = Class.forName("android.webkit.Network"); if (networkClass != null) { Object networkObj = invokeMethod(networkClass, "getInstance", new Object[] { ctx }, Context.class); if (networkObj != null) { ret = getDeclaredField(networkObj, "mRequestQueue"); } } return ret; } private static Object invokeMethod(Object object, String methodName, Object[] params, Class... types) throws Exception { Object out = null; Class c = object instanceof Class ? (Class) object : object.getClass(); if (types != null) { Method method = c.getMethod(methodName, types); out = method.invoke(object, params); } else { Method method = c.getMethod(methodName); out = method.invoke(object); } // System.out.println(object.getClass().getName() + "." + methodName + // "() = "+ out); return out; } public static void resetProxy(Context ctx) throws Exception { Object requestQueueObject = getRequestQueue(ctx); if (requestQueueObject != null) { setDeclaredField(requestQueueObject, "mProxyHost", null); } } private static void setDeclaredField(Object obj, String name, Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException { Field f = obj.getClass().getDeclaredField(name); f.setAccessible(true); f.set(obj, value); } /** * Override WebKit Proxy settings * * @param ctx * Android ApplicationContext * @param host * @param port * @return true if Proxy was successfully set */ public static boolean setProxy(Context ctx, String host, int port) { boolean ret = false; setSystemProperties(host, port); try { if (Build.VERSION.SDK_INT < 14) { Object requestQueueObject = getRequestQueue(ctx); if (requestQueueObject != null) { // Create Proxy config object and set it into request Q HttpHost httpHost = new HttpHost(host, port, "http"); setDeclaredField(requestQueueObject, "mProxyHost", httpHost); ret = true; } } else { ret = setICSProxy(host, port); } } catch (Exception e) { Log.e(TAG, "error setting up webkit proxying", e); } return ret; } private static boolean setICSProxy(String host, int port) throws ClassNotFoundException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException { Class webViewCoreClass = Class.forName("android.webkit.WebViewCore"); Class proxyPropertiesClass = Class.forName("android.net.ProxyProperties"); if (webViewCoreClass != null && proxyPropertiesClass != null) { Method m = webViewCoreClass.getDeclaredMethod("sendStaticMessage", Integer.TYPE, Object.class); Constructor c = proxyPropertiesClass.getConstructor(String.class, Integer.TYPE, String.class); m.setAccessible(true); c.setAccessible(true); Object properties = c.newInstance(host, port, null); m.invoke(null, PROXY_CHANGED, properties); return true; } return false; } private static void setSystemProperties(String host, int port) { System.setProperty("http.proxyHost", host); System.setProperty("http.proxyPort", port + ""); System.setProperty("https.proxyHost", host); System.setProperty("https.proxyPort", port + ""); } }
zyh3290-proxy
src/org/gaeproxy/ProxySettings.java
Java
gpl3
4,389
// dbartists - Douban artists client for Android // Copyright (C) 2011 Max Lv <max.c.lv@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // // // ___====-_ _-====___ // _--^^^#####// \\#####^^^--_ // _-^##########// ( ) \\##########^-_ // -############// |\^^/| \\############- // _/############// (@::@) \\############\_ // /#############(( \\// ))#############\ // -###############\\ (oo) //###############- // -#################\\ / VV \ //#################- // -###################\\/ \//###################- // _#/|##########/\######( /\ )######/\##########|\#_ // |/ |#/\#/\#/\/ \#/\##\ | | /##/\#/ \/\#/\#/\#| \| // ` |/ V V ` V \#\| | | |/#/ V ' V V \| ' // ` ` ` ` / | | | | \ ' ' ' ' // ( | | | | ) // __\ | | | | /__ // (vvv(VVV)(VVV)vvv) // // HERE BE DRAGONS package org.gaeproxy; import android.content.Context; public class ImageLoaderFactory { private static ImageLoader il = null; public static ImageLoader getImageLoader(Context context) { if (il == null) { il = new ImageLoader(context); } return il; } }
zyh3290-proxy
src/org/gaeproxy/ImageLoaderFactory.java
Java
gpl3
1,939
package org.gaeproxy; public class ProxyedApp { private boolean enabled; private int uid; private String username; private String procname; private String name; private boolean proxyed = false; /** * @return the name */ public String getName() { return name; } /** * @return the procname */ public String getProcname() { return procname; } /** * @return the uid */ public int getUid() { return uid; } /** * @return the username */ public String getUsername() { return username; } /** * @return the enabled */ public boolean isEnabled() { return enabled; } /** * @return the proxyed */ public boolean isProxyed() { return proxyed; } /** * @param enabled * the enabled to set */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } /** * @param procname * the procname to set */ public void setProcname(String procname) { this.procname = procname; } /** * @param proxyed * the proxyed to set */ public void setProxyed(boolean proxyed) { this.proxyed = proxyed; } /** * @param uid * the uid to set */ public void setUid(int uid) { this.uid = uid; } /** * @param username * the username to set */ public void setUsername(String username) { this.username = username; } }
zyh3290-proxy
src/org/gaeproxy/ProxyedApp.java
Java
gpl3
1,582
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gaeproxy; import java.io.Serializable; import java.util.Arrays; import java.util.List; /** * <p> * <b>Domain name</b> validation routines. * </p> * * <p> * This validator provides methods for validating Internet domain names and * top-level domains. * </p> * * <p> * Domain names are evaluated according to the standards <a * href="http://www.ietf.org/rfc/rfc1034.txt">RFC1034</a>, section 3, and <a * href="http://www.ietf.org/rfc/rfc1123.txt">RFC1123</a>, section 2.1. No * accomodation is provided for the specialized needs of other applications; if * the domain name has been URL-encoded, for example, validation will fail even * though the equivalent plaintext version of the same name would have passed. * </p> * * <p> * Validation is also provided for top-level domains (TLDs) as defined and * maintained by the Internet Assigned Numbers Authority (IANA): * </p> * * <ul> * <li>{@link #isValidInfrastructureTld} - validates infrastructure TLDs ( * <code>.arpa</code>, etc.)</li> * <li>{@link #isValidGenericTld} - validates generic TLDs ( * <code>.com, .org</code>, etc.)</li> * <li>{@link #isValidCountryCodeTld} - validates country code TLDs ( * <code>.us, .uk, .cn</code>, etc.)</li> * </ul> * * <p> * (<b>NOTE</b>: This class does not provide IP address lookup for domain names * or methods to ensure that a given domain name matches a specific IP; see * {@link java.net.InetAddress} for that functionality.) * </p> * * @version $Revision$ $Date$ * @since Validator 1.4 */ public class DomainValidator implements Serializable { // Regular expression strings for hostnames (derived from RFC2396 and RFC // 1123) private static final String DOMAIN_LABEL_REGEX = "\\p{Alnum}(?>[\\p{Alnum}-]*\\p{Alnum})*"; private static final String TOP_LABEL_REGEX = "\\p{Alpha}{2,}"; private static final String DOMAIN_NAME_REGEX = "^(?:" + DOMAIN_LABEL_REGEX + "\\.)+" + "(" + TOP_LABEL_REGEX + ")$"; /** * Singleton instance of this validator. */ private static final DomainValidator DOMAIN_VALIDATOR = new DomainValidator(); private static final String[] INFRASTRUCTURE_TLDS = new String[] { "arpa", // internet // infrastructure "root" // diagnostic marker for non-truncated root zone }; private static final String[] GENERIC_TLDS = new String[] { "aero", // air // transport // industry "asia", // Pan-Asia/Asia Pacific "biz", // businesses "cat", // Catalan linguistic/cultural community "com", // commercial enterprises "coop", // cooperative associations "info", // informational sites "jobs", // Human Resource managers "mobi", // mobile products and services "museum", // museums, surprisingly enough "name", // individuals' sites "net", // internet support infrastructure/business "org", // noncommercial organizations "pro", // credentialed professionals and entities "tel", // contact data for businesses and individuals "travel", // entities in the travel industry "gov", // United States Government "edu", // accredited postsecondary US education entities "mil", // United States Military "int" // organizations established by international treaty }; private static final String[] COUNTRY_CODE_TLDS = new String[] { "ac", // Ascension // Island "ad", // Andorra "ae", // United Arab Emirates "af", // Afghanistan "ag", // Antigua and Barbuda "ai", // Anguilla "al", // Albania "am", // Armenia "an", // Netherlands Antilles "ao", // Angola "aq", // Antarctica "ar", // Argentina "as", // American Samoa "at", // Austria "au", // Australia (includes Ashmore and Cartier Islands and Coral // Sea Islands) "aw", // Aruba "ax", // 脙鈥and "az", // Azerbaijan "ba", // Bosnia and Herzegovina "bb", // Barbados "bd", // Bangladesh "be", // Belgium "bf", // Burkina Faso "bg", // Bulgaria "bh", // Bahrain "bi", // Burundi "bj", // Benin "bm", // Bermuda "bn", // Brunei Darussalam "bo", // Bolivia "br", // Brazil "bs", // Bahamas "bt", // Bhutan "bv", // Bouvet Island "bw", // Botswana "by", // Belarus "bz", // Belize "ca", // Canada "cc", // Cocos (Keeling) Islands "cd", // Democratic Republic of the Congo (formerly Zaire) "cf", // Central African Republic "cg", // Republic of the Congo "ch", // Switzerland "ci", // C脙麓te d'Ivoire "ck", // Cook Islands "cl", // Chile "cm", // Cameroon "cn", // China, mainland "co", // Colombia "cr", // Costa Rica "cu", // Cuba "cv", // Cape Verde "cx", // Christmas Island "cy", // Cyprus "cz", // Czech Republic "de", // Germany "dj", // Djibouti "dk", // Denmark "dm", // Dominica "do", // Dominican Republic "dz", // Algeria "ec", // Ecuador "ee", // Estonia "eg", // Egypt "er", // Eritrea "es", // Spain "et", // Ethiopia "eu", // European Union "fi", // Finland "fj", // Fiji "fk", // Falkland Islands "fm", // Federated States of Micronesia "fo", // Faroe Islands "fr", // France "ga", // Gabon "gb", // Great Britain (United Kingdom) "gd", // Grenada "ge", // Georgia "gf", // French Guiana "gg", // Guernsey "gh", // Ghana "gi", // Gibraltar "gl", // Greenland "gm", // The Gambia "gn", // Guinea "gp", // Guadeloupe "gq", // Equatorial Guinea "gr", // Greece "gs", // South Georgia and the South Sandwich Islands "gt", // Guatemala "gu", // Guam "gw", // Guinea-Bissau "gy", // Guyana "hk", // Hong Kong "hm", // Heard Island and McDonald Islands "hn", // Honduras "hr", // Croatia (Hrvatska) "ht", // Haiti "hu", // Hungary "id", // Indonesia "ie", // Ireland (脙鈥癷re) "il", // Israel "im", // Isle of Man "in", // India "io", // British Indian Ocean Territory "iq", // Iraq "ir", // Iran "is", // Iceland "it", // Italy "je", // Jersey "jm", // Jamaica "jo", // Jordan "jp", // Japan "ke", // Kenya "kg", // Kyrgyzstan "kh", // Cambodia (Khmer) "ki", // Kiribati "km", // Comoros "kn", // Saint Kitts and Nevis "kp", // North Korea "kr", // South Korea "kw", // Kuwait "ky", // Cayman Islands "kz", // Kazakhstan "la", // Laos (currently being marketed as the official domain for // Los Angeles) "lb", // Lebanon "lc", // Saint Lucia "li", // Liechtenstein "lk", // Sri Lanka "lr", // Liberia "ls", // Lesotho "lt", // Lithuania "lu", // Luxembourg "lv", // Latvia "ly", // Libya "ma", // Morocco "mc", // Monaco "md", // Moldova "me", // Montenegro "mg", // Madagascar "mh", // Marshall Islands "mk", // Republic of Macedonia "ml", // Mali "mm", // Myanmar "mn", // Mongolia "mo", // Macau "mp", // Northern Mariana Islands "mq", // Martinique "mr", // Mauritania "ms", // Montserrat "mt", // Malta "mu", // Mauritius "mv", // Maldives "mw", // Malawi "mx", // Mexico "my", // Malaysia "mz", // Mozambique "na", // Namibia "nc", // New Caledonia "ne", // Niger "nf", // Norfolk Island "ng", // Nigeria "ni", // Nicaragua "nl", // Netherlands "no", // Norway "np", // Nepal "nr", // Nauru "nu", // Niue "nz", // New Zealand "om", // Oman "pa", // Panama "pe", // Peru "pf", // French Polynesia With Clipperton Island "pg", // Papua New Guinea "ph", // Philippines "pk", // Pakistan "pl", // Poland "pm", // Saint-Pierre and Miquelon "pn", // Pitcairn Islands "pr", // Puerto Rico "ps", // Palestinian territories (PA-controlled West Bank and Gaza // Strip) "pt", // Portugal "pw", // Palau "py", // Paraguay "qa", // Qatar "re", // R脙漏union "ro", // Romania "rs", // Serbia "ru", // Russia "rw", // Rwanda "sa", // Saudi Arabia "sb", // Solomon Islands "sc", // Seychelles "sd", // Sudan "se", // Sweden "sg", // Singapore "sh", // Saint Helena "si", // Slovenia "sj", // Svalbard and Jan Mayen Islands Not in use (Norwegian // dependencies; see .no) "sk", // Slovakia "sl", // Sierra Leone "sm", // San Marino "sn", // Senegal "so", // Somalia "sr", // Suriname "st", // S脙拢o Tom脙漏 and Pr脙颅ncipe "su", // Soviet Union (deprecated) "sv", // El Salvador "sy", // Syria "sz", // Swaziland "tc", // Turks and Caicos Islands "td", // Chad "tf", // French Southern and Antarctic Lands "tg", // Togo "th", // Thailand "tj", // Tajikistan "tk", // Tokelau "tl", // East Timor (deprecated old code) "tm", // Turkmenistan "tn", // Tunisia "to", // Tonga "tp", // East Timor "tr", // Turkey "tt", // Trinidad and Tobago "tv", // Tuvalu "tw", // Taiwan, Republic of China "tz", // Tanzania "ua", // Ukraine "ug", // Uganda "uk", // United Kingdom "um", // United States Minor Outlying Islands "us", // United States of America "uy", // Uruguay "uz", // Uzbekistan "va", // Vatican City State "vc", // Saint Vincent and the Grenadines "ve", // Venezuela "vg", // British Virgin Islands "vi", // U.S. Virgin Islands "vn", // Vietnam "vu", // Vanuatu "wf", // Wallis and Futuna "ws", // Samoa (formerly Western Samoa) "ye", // Yemen "yt", // Mayotte "yu", // Serbia and Montenegro (originally Yugoslavia) "za", // South Africa "zm", // Zambia "zw", // Zimbabwe }; private static final List INFRASTRUCTURE_TLD_LIST = Arrays .asList(INFRASTRUCTURE_TLDS); private static final List GENERIC_TLD_LIST = Arrays.asList(GENERIC_TLDS); private static final List COUNTRY_CODE_TLD_LIST = Arrays .asList(COUNTRY_CODE_TLDS); /** * Returns the singleton instance of this validator. * * @return the singleton instance of this validator */ public static DomainValidator getInstance() { return DOMAIN_VALIDATOR; } /** * RegexValidator for matching domains. */ private final RegexValidator domainRegex = new RegexValidator( DOMAIN_NAME_REGEX); /** Private constructor. */ private DomainValidator() { } // --------------------------------------------- // ----- TLDs defined by IANA // ----- Authoritative and comprehensive list at: // ----- http://data.iana.org/TLD/tlds-alpha-by-domain.txt private String chompLeadingDot(String str) { if (str.startsWith(".")) { return str.substring(1); } else { return str; } } /** * Returns true if the specified <code>String</code> parses as a valid * domain name with a recognized top-level domain. The parsing is * case-sensitive. * * @param domain * the parameter to check for domain name syntax * @return true if the parameter is a valid domain name */ public boolean isValid(String domain) { String[] groups = domainRegex.match(domain); if (groups != null && groups.length > 0) { return isValidTld(groups[0]); } else { return false; } } /** * Returns true if the specified <code>String</code> matches any * IANA-defined country code top-level domain. Leading dots are ignored if * present. The search is case-sensitive. * * @param ccTld * the parameter to check for country code TLD status * @return true if the parameter is a country code TLD */ public boolean isValidCountryCodeTld(String ccTld) { return COUNTRY_CODE_TLD_LIST.contains(chompLeadingDot(ccTld .toLowerCase())); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined generic top-level domain. Leading dots are ignored if * present. The search is case-sensitive. * * @param gTld * the parameter to check for generic TLD status * @return true if the parameter is a generic TLD */ public boolean isValidGenericTld(String gTld) { return GENERIC_TLD_LIST.contains(chompLeadingDot(gTld.toLowerCase())); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined infrastructure top-level domain. Leading dots are ignored if * present. The search is case-sensitive. * * @param iTld * the parameter to check for infrastructure TLD status * @return true if the parameter is an infrastructure TLD */ public boolean isValidInfrastructureTld(String iTld) { return INFRASTRUCTURE_TLD_LIST.contains(chompLeadingDot(iTld .toLowerCase())); } /** * Returns true if the specified <code>String</code> matches any * IANA-defined top-level domain. Leading dots are ignored if present. The * search is case-sensitive. * * @param tld * the parameter to check for TLD status * @return true if the parameter is a TLD */ public boolean isValidTld(String tld) { return isValidInfrastructureTld(tld) || isValidGenericTld(tld) || isValidCountryCodeTld(tld); } }
zyh3290-proxy
src/org/gaeproxy/DomainValidator.java
Java
gpl3
14,271