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
|
|---|---|---|---|---|---|
#! /usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Name: general_test.py
# Purpose: General testing program for unioc-ng
# Author: Fabien Marteau <fabien.marteau@armadeus.com>
# Created: 22/11/2008
#-----------------------------------------------------------------------------
# Copyright (2008) Armadeus Systems
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#-----------------------------------------------------------------------------
# Revision list :
#
# Date By Changes
#
#-----------------------------------------------------------------------------
__doc__ = ""
__author__ = "Fabien Marteau <fabien.marteau@armadeus.com>"
import sys
import os
from error import Error
from bootstrap import BootStrap
def consoleDump(tid):
while 1:
sys.stdout.write(tid.read(1))
def waitForPositiveResponse(charok,error_message):
response = raw_input().strip()
if response != charok:
raise Error(error_message,0)
if __name__ == "__main__":
print "********************************************"
print "* This is the testing program for unioc-ng.*"
print "* Version 0.1 *"
print "* To ensure a good card functionning *"
print "* follow the instruction. *"
print "********************************************"
print " Powering ..."
print "* Program atmega bootstrap with JTAG"
raw_input()
print "* Configure fpga with GPIO ip"
raw_input()
print "* Branch shunts"
raw_input()
|
102chute
|
trunk/code/test_unioc_ng/host/.svn/text-base/general_test.py.svn-base
|
Python
|
gpl2
| 2,267
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------------------------------------------------
# Name: bootstrap.py
# Purpose: bootstrap class used to communicate with atmega
# Author: Fabien Marteau <fabien.marteau@armadeus.com>
# Created: 22/11/2008
#-----------------------------------------------------------------------------
# Copyright (2008) Armadeus Systems
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#-----------------------------------------------------------------------------
# Revision list :
#
# Date By Changes
#
#-----------------------------------------------------------------------------
__doc__ = ""
__author__ = "Fabien Marteau <fabien.marteau@armadeus.com>"
import sys
import time
import os
try:
import serial
except ImportError:
print "[ERROR]Pyserial is needed : "+\
"http://pyserial.wiki.sourceforge.net/pySerial"
#exit()
class BootStrap():
def __init__(self):
print "TODO: init BootStrap"
def put(self,address,value):
""" Write a value on atmega register
address : int (16bits)
value : int (8bits)
"""
print "TODO: put %02X at %04X"%(value,address)
def get(self,address):
""" Read a value from atmega register
address : int (16bits)
return int
"""
print "TODO : read value at address %04X"%address
|
102chute
|
trunk/code/test_unioc_ng/host/.svn/text-base/bootstrap.py.svn-base
|
Python
|
gpl2
| 2,086
|
# Makefile for VHDL synthesis and simulation
# version 1.0
# Fabien Marteau
# project name
PROJECT=robotter_top
# vhdl files
FILES = src/atmega_wrapper.vhd src/Top.vhd src/Wb_led.vhd src/intercon.vhd src/Wb_pwm.vhd
# pin configuration
UCF_FILE =
# Synthesis constraints file
XCF_FILE =
# testbench
SIMTOP = top_tb
SIMFILES = testbench/Top_tb.vhd testbench/atmega_pkg.vhd
# Simu break condition
GHDL_SIM_OPT = --assert-level=error
#GHDL_SIM_OPT = --stop-time=500ns
# FPGA options
PART = xc3s200-4-tq144
############################
# Personnals options
############################
CAT=../Xtools/catcolor
BRIEF=../Xtools/brief.py
############################
# Xilinx options
############################
BIN = bin
WORK = work
SYNTH = xst
NGDBUILD = ngdbuild
MAP = map
PAR = par
TRACE = trce
BITGEN = bitgen
ifdef $(XCF_FILE)
XCF = -uc $(XCF_FILE)\n
endif
##############################
# GHDL options
##############################
SIMDIR = simu
SYNTHFILES = bin/bus_led_ise/netgen/synthesis
GHDL_CMD = ghdl
GHDL_FLAGS = --ieee=synopsys --warn-no-vital-generic
#GHDL_FLAGS = --ieee=synopsys -P~/Xilinx92i/coregen/ip/xilinx/primary/com/xilinx/ip/unisim --warn-no-vital-generic
VIEW_CMD = /usr/bin/gtkwave
OBJS_FILES = $(patsubst %.vhd, %.o, $(notdir $(FILES)) )
OBJS_SIMFILES = $(patsubst %.vhd, %.o, $(notdir $(SIMFILES)) )
#################################
# Synthesis with xst
#################################
messages : bit
$(BRIEF) $(BIN)/$(PROJECT)
bit : $(BIN)/$(PROJECT).ncd trace
-$(BITGEN) -intstyle xflow -w \
-g DebugBitstream:No \
-g Binary:yes \
-g CRC:Enable \
-g ConfigRate:6 \
-g CclkPin:PullUp \
-g M0Pin:PullUp \
-g M1Pin:PullUp \
-g M2Pin:PullUp \
-g ProgPin:PullUp \
-g DonePin:PullUp \
-g TckPin:PullUp \
-g TdiPin:PullUp \
-g TdoPin:PullUp \
-g TmsPin:PullUp \
-g UnusedPin:PullDown \
-g UserID:0xFFFFFFFF \
-g DCMShutdown:Disable \
-g DCIUpdateMode:AsRequired \
-g StartUpClk:CClk \
-g DONE_cycle:4 \
-g GTS_cycle:5 \
-g GWE_cycle:6 \
-g LCK_cycle:NoWait \
-g Match_cycle:Auto \
-g Security:None \
-g DonePipe:No \
-g DriveDone:No \
$(BIN)/$(PROJECT).ncd > $(BIN)/$(PROJECT).bitlog
$(CAT) $(BIN)/$(PROJECT).bitlog
-cp $(BIN)/$(PROJECT).bit /tftpboot/
-cp $(BIN)/$(PROJECT).bin /tftpboot/
trace: $(BIN)/$(PROJECT).ncd $(BIN)/$(PROJECT).pcf
-$(TRACE) -intstyle xflow -e 3 -l 3 -s 4 -xml $(BIN)/$(PROJECT) $(BIN)/$(PROJECT).ncd -o $(BIN)/$(PROJECT).twr $(BIN)/$(PROJECT).pcf
$(CAT) $(BIN)/$(PROJECT).tracelog
$(BIN)/$(PROJECT).ncd : par
par : $(BIN)/$(PROJECT)_map.ncd $(BIN)/$(PROJECT).pcf
- sh -c 'pid=$$$$; $(PAR) -w -intstyle xflow -ol std -t 1 $(BIN)/$(PROJECT)_map.ncd $(BIN)/$(PROJECT).ncd $(BIN)/$(PROJECT).pcf | (sed "/^PAR done/q";kill $$pid)' > $(BIN)/$(PROJECT).parlog
$(CAT) $(BIN)/$(PROJECT).parlog
- killall -9 par
$(BIN)/$(PROJECT).pcf $(BIN)/$(PROJECT)_map.ncd : map
map : $(BIN)/$(PROJECT).ngd
- sh -c 'pid=$$$$ ; $(MAP) -intstyle xflow -p $(PART) -cm area -pr b -k 4 -c 100 -o $(BIN)/$(PROJECT)_map.ncd $(BIN)/$(PROJECT).ngd $(BIN)/$(PROJECT).pcf | (sed "/^See MAP report file/q" ; kill $$pid ) ' > $(BIN)/$(PROJECT).maplog
$(CAT) $(BIN)/$(PROJECT).maplog
- killall -9 map
$(BIN)/$(PROJECT).ngd : ngdbuild
ngdbuild : $(BIN)/$(PROJECT).ngr $(BIN)/$(PROJECT).ngc $(BIN)/$(PROJECT).lso
-$(NGDBUILD) -intstyle xflow -dd _ngo -nt timestamp -p $(PART) $(BIN)/$(PROJECT).ngc $(BIN)/$(PROJECT).ngd -uc $(UCF_FILE) > $(BIN)/$(PROJECT).ngdlog
$(CAT) $(BIN)/$(PROJECT).ngdlog
$(BIN)/$(PROJECT).ngc $(BIN)/$(PROJECT).ngr $(BIN)/$(PROJECT).lso : synthesis
synthesis : $(BIN)/$(PROJECT).prj $(BIN)/$(PROJECT).xst
$(SYNTH) -ifn $(BIN)/$(PROJECT).xst -ofn $(BIN)/$(PROJECT).log \
| sed "s/^ERROR/[01\;31mERROR[00m/"\
| sed "s/^WARNING/[01\;33mWARNING[00m/"\
| sed "s/^INFO/[01\;32mINFO[0m/"
$(BIN)/$(PROJECT).xst $(BIN)/$(PROJECT).prj :
@mkdir -p $(BIN)
@touch $(BIN)/$(PROJECT);
@for f in $(FILES); do \
echo vhdl $(WORK) \"$$f\" >> $(BIN)/$(PROJECT).prj;\
done
@echo work > $(BIN)/$(PROJECT).lso
@mkdir -p ./bin/xst/projnav.tmp
@echo " \
set -tmpdir "./bin/xst/projnav.tmp" \n\
set -xsthdpdir "./bin/xst" \n\
run \n\
-ifn $(BIN)/$(PROJECT).prj \n\
-ifmt mixed \n\
-ofn $(BIN)/$(PROJECT) \n\
-ofmt NGC \n\
-p $(PART) \n\
-top $(PROJECT) \n\
-opt_mode Speed \n\
-opt_level 1 \n\
$(XCF)\
-iuc NO \n\
-lso $(BIN)/$(PROJECT).lso \n\
-keep_hierarchy NO \n\
-rtlview Yes \n\
-glob_opt AllClockNets \n\
-read_cores YES \n\
-write_timing_constraints NO \n\
-cross_clock_analysis NO \n\
-hierarchy_separator / \n\
-bus_delimiter <> \n\
-case maintain \n\
-slice_utilization_ratio 100 \n\
-bram_utilization_ratio 100 \n\
-verilog2001 YES \n\
-fsm_extract YES -fsm_encoding Auto \n\
-safe_implementation No \n\
-fsm_style lut \n\
-ram_extract Yes \n\
-ram_style Auto \n\
-rom_extract Yes \n\
-mux_style Auto \n\
-decoder_extract YES \n\
-priority_extract YES \n\
-shreg_extract YES \n\
-shift_extract YES \n\
-xor_collapse YES \n\
-rom_style Auto \n\
-auto_bram_packing NO \n\
-mux_extract YES \n\
-resource_sharing YES \n\
-async_to_sync NO \n\
-mult_style auto \n\
-iobuf YES \n\
-max_fanout 500 \n\
-bufg 8 \n\
-register_duplication YES \n\
-register_balancing No \n\
-slice_packing YES \n\
-optimize_primitives NO \n\
-use_clock_enable Yes \n\
-use_sync_set Yes \n\
-use_sync_reset Yes \n\
-iob auto \n\
-equivalent_register_removal YES \n\
-slice_utilization_ratio_maxmargin 5\n\
" >> $(BIN)/$(PROJECT).xst
clean : ghdl-clean
-rm -rf $(BIN)
-rm -rf _ngo
-rm xilinx_device_details.xml
########################
# Simulation with GHDL
########################
ghdl : ghdl-compil ghdl-run ghdl-view
ghdl-compil :
mkdir -p simu
$(GHDL_CMD) -i $(GHDL_FLAGS) --workdir=simu --work=work $(FILES) $(SIMFILES)
$(GHDL_CMD) -m $(GHDL_FLAGS) --workdir=simu --work=work $(SIMTOP)
@mv $(SIMTOP) simu/$(SIMTOP)
#TODO: make it working !
ghdl-simsynth :
$(GHDL_CMD) -i $(GHDL_FLAGS) --workdir=simu --work=work $(SYNTHFILES) $(SIMFILES)
$(GHDL_CMD) -m $(GHDL_FLAGS) --workdir=simu --work=work $(SIMTOP)
@mv $(SIMTOP) simu/$(SIMTOP)
ghdl-run :
@$(SIMDIR)/$(SIMTOP) $(GHDL_SIM_OPT) --vcdgz=$(SIMDIR)/$(SIMTOP).vcdgz
ghdl-view:
gunzip --stdout $(SIMDIR)/$(SIMTOP).vcdgz | $(VIEW_CMD) --vcd
ghdl-clean :
$(GHDL_CMD) --clean --workdir=simu
-rm -rf simu
|
102chute
|
trunk/code/vhdl_v2/Makefile
|
Makefile
|
gpl2
| 6,373
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 23/04/2008
-- File : atmega_wrapper_tb.vhd
--
-- Abstract : Test the wrapper between atmega and wishbone
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
use work.atmega_pkg.ALL;
---------------------------------------------------------------------------
Entity atmega_wrapper_tb is
---------------------------------------------------------------------------
end entity;
---------------------------------------------------------------------------
Architecture atmega_wrapper_tb_1 of atmega_wrapper_tb is
---------------------------------------------------------------------------
CONSTANT HALF_PERIODE : time := 10 ns; -- Half clock period of 50MHz
CONSTANT ATMEGA_HALF_PERIODE : time := 31 ns; -- Half clock period of 50MHz
component atmega_wrapper
port (
-- Atmega128 port
Address_H : in std_logic_vector( 7 downto 0);
DA : inout std_logic_vector( 7 downto 0);
ALE : in std_logic ;
RD : in std_logic ;
WR : in std_logic ;
DIR_buffer : out std_logic ;
-- Wishbone port
wbm_address : out std_logic_vector( 15 downto 0);
wbm_readdata : in std_logic_vector( 7 downto 0);
wbm_writedata : out std_logic_vector( 7 downto 0);
wbm_strobe : out std_logic ;
wbm_write : out std_logic ;
wbm_ack : in std_logic ;
wbm_cycle : out std_logic ;
-- clock 50MHz and reset
clk : in std_logic ;
reset_n : in std_logic
);
end component;
-- Atmega128 port
signal Address_H : std_logic_vector( 7 downto 0);
signal DA : std_logic_vector( 7 downto 0);
signal ALE : std_logic ;
signal RD : std_logic ;
signal WR : std_logic ;
signal DIR_buffer : std_logic ;
-- Wishbone port
signal wbm_address : std_logic_vector( 15 downto 0);
signal wbm_readdata : std_logic_vector( 7 downto 0);
signal wbm_writedata : std_logic_vector( 7 downto 0);
signal wbm_strobe : std_logic ;
signal wbm_write : std_logic ;
signal wbm_ack : std_logic ;
signal wbm_cycle : std_logic ;
-- clock 50MHz areset
signal clk : std_logic ;
signal reset_n : std_logic ;
signal atclk : std_logic ;
signal address : std_logic_vector( 15 downto 0);
begin
reset_n <= '0', '1' AFTER 4*HALF_PERIODE;
-- Clock
Clockp : process
begin
clk <= '1';
wait for HALF_PERIODE;
clk <= '0';
wait for HALF_PERIODE;
end process Clockp;
AtmegaClk : process
begin
atclk <= '1';
wait for ATMEGA_HALF_PERIODE;
atclk <= '0';
wait for ATMEGA_HALF_PERIODE;
end process AtmegaClk;
stimulis : process
variable value : std_logic_vector( 7 downto 0);
begin
Address_H <= (others => '0');
DA <= (others => 'Z');
ALE <= '0';
RD <= '1';
WR <= '1';
wait for 50 ns;
-- Write test
atmega_write(x"0002",x"08",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
-- Read test
atmega_read(x"0002",value,
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
wait for 100 ns;
assert false report "End of test" severity error;
end process stimulis;
connect_atmega_wrapper : atmega_wrapper
port map (
-- Atmega128 port
Address_H => Address_H ,
DA => DA,
ALE => ALE,
RD => RD,
WR => WR,
DIR_buffer => DIR_buffer,
-- Wishbone port
wbm_address => wbm_address,
wbm_readdata => wbm_readdata,
wbm_writedata => wbm_writedata,
wbm_strobe => wbm_strobe,
wbm_write => wbm_write,
wbm_ack => wbm_ack,
wbm_cycle => wbm_cycle,
-- clock 50MHz and reset
clk => clk,
reset_n => reset_n
);
end architecture atmega_wrapper_tb_1;
|
102chute
|
trunk/code/vhdl_v2/testbench/atmega_wrapper_tb.vhd
|
VHDL
|
gpl2
| 3,998
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 24/04/2008
-- File : Top_tb.vhd
--
-- Abstract :
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
use work.atmega_pkg.ALL;
---------------------------------------------------------------------------
Entity Top_tb is
---------------------------------------------------------------------------
end entity;
---------------------------------------------------------------------------
Architecture Top_tb_1 of Top_tb is
---------------------------------------------------------------------------
CONSTANT HALF_PERIODE : time := 10 ns; -- Half clock period of 50MHz
CONSTANT ATMEGA_HALF_PERIODE : time := 31.1 ns; -- Half clock period of 50MHz
component Top
port (
-- Atmega128 port
Address_H : in std_logic_vector( 7 downto 0);
DA : inout std_logic_vector( 7 downto 0);
ALE : in std_logic ;
RD : in std_logic ;
WR : in std_logic ;
DIR_buffer : out std_logic ;
-- Clock and reset
clk : in std_logic ;
reset_n : in std_logic ;
-- Output
LED : out std_logic ;
pwm : out std_logic ;
pwm_dir : out std_logic
);
end component;
signal Address_H : std_logic_vector( 7 downto 0);
signal DA : std_logic_vector( 7 downto 0);
signal ALE : std_logic ;
signal RD : std_logic ;
signal WR : std_logic ;
signal DIR_buffer : std_logic ;
signal clk : std_logic ;
signal reset_n : std_logic ;
signal LED : std_logic ;
signal atclk : std_logic ;
signal address : std_logic_vector( 15 downto 0);
begin
reset_n <= '0', '1' AFTER 4*HALF_PERIODE;
-- Clock
Clockp : process
begin
clk <= '1';
wait for HALF_PERIODE;
clk <= '0';
wait for HALF_PERIODE;
end process Clockp;
AtmegaClk : process
begin
atclk <= '1';
wait for ATMEGA_HALF_PERIODE;
atclk <= '0';
wait for ATMEGA_HALF_PERIODE;
end process AtmegaClk;
stimulis : process
variable value : std_logic_vector( 7 downto 0);
begin
Address_H <= (others => '0');
DA <= (others => 'Z');
ALE <= '0';
RD <= '1';
WR <= '1';
wait for 50 ns;
-- Write test
atmega_write(x"1300",x"01",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
-- Read test
atmega_read(x"1300",value,
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
assert value = x"01" report "Wrong led value read" severity error;
wait for 10 ns;
-- Write test
atmega_write(x"1300",x"00",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
-- Read test
atmega_read(x"1300",value,
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
assert value = x"00" report "Wrong led value read" severity error;
-- Write test
atmega_write(x"1302",x"fe",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
atmega_write(x"1303",x"83",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
wait for 100 us;
-- Read test
atmega_read(x"1302",value,
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
assert value = x"fe" report "Wrong pwm LSB value read" severity error;
wait for 100 us;
-- Read test
atmega_read(x"1303",value,
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
assert value = x"83" report "Wrong pwm MSB value read" severity error;
wait for 200 us;
-- Write test
atmega_write(x"1302",x"3f",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
atmega_write(x"1303",x"00",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
wait for 200 us;
-- Write test
atmega_write(x"1302",x"3f",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
atmega_write(x"1303",x"80",
atclk,Address_H,DA,ALE,RD,WR,DIR_buffer);
wait for 2000 us;
assert false report "End of test" severity error;
end process stimulis;
connect_Top : Top
port map (
-- Atmega128 port
Address_H => Address_H ,
DA => DA,
ALE => ALE,
RD => RD,
WR => WR,
DIR_buffer => DIR_buffer,
-- Clock and reset
clk => clk,
reset_n => reset_n,
-- Output
LED => LED
);
end architecture Top_tb_1;
|
102chute
|
trunk/code/vhdl_v2/testbench/Top_tb.vhd
|
VHDL
|
gpl2
| 4,231
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 23/04/2008
-- File : atmega_pkg.vhd
--
-- Abstract : Simulate atmega128 read and write
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
package atmega_pkg is
procedure atmega_write(
Address : in std_logic_vector( 15 downto 0);
value : in std_logic_vector( 7 downto 0);
signal clk : in std_logic ;
signal Address_H : out std_logic_vector( 7 downto 0);
signal DA : inout std_logic_vector( 7 downto 0);
signal ALE : out std_logic ;
signal RD : out std_logic ;
signal WR : out std_logic ;
signal DIR_buffer : in std_logic
);
procedure atmega_read(
Address : in std_logic_vector( 15 downto 0);
value : out std_logic_vector( 7 downto 0);
signal clk : in std_logic ;
signal Address_H : out std_logic_vector( 7 downto 0);
signal DA : inout std_logic_vector( 7 downto 0);
signal ALE : out std_logic ;
signal RD : out std_logic ;
signal WR : out std_logic ;
signal DIR_buffer : in std_logic
);
end package atmega_pkg;
package body atmega_pkg is
CONSTANT TCLCL : time :=62 ns; -- 16 MHz
--Write value
procedure atmega_write(
Address : in std_logic_vector( 15 downto 0);
value : in std_logic_vector( 7 downto 0);
signal clk : in std_logic ;
signal Address_H : out std_logic_vector( 7 downto 0);
signal DA : inout std_logic_vector( 7 downto 0);
signal ALE : out std_logic ;
signal RD : out std_logic ;
signal WR : out std_logic ;
signal DIR_buffer : in std_logic
) is
begin
WR <= '1';
RD <= '1';
wait until falling_edge(clk);
ALE <= '1';
wait until rising_edge(clk);
Address_H <= Address(15 downto 8);
DA <= Address(7 downto 0);
wait until falling_edge(clk);
ALE <= '0';
wait for 5 ns;
DA <= (others => 'Z');
wait until rising_edge(clk);
DA <= value;
-- 0.5TCLCL - 20 ns
wait for 0.5*TCLCL - 20 ns;
WR <= '0';
wait until rising_edge(clk);
WR <= '1';
wait until falling_edge(clk);
DA <= (others => 'Z');
Address_H <= (others => 'Z');
end procedure atmega_write;
--Read value
procedure atmega_read(
Address : in std_logic_vector( 15 downto 0);
value : out std_logic_vector( 7 downto 0);
signal clk : in std_logic ;
signal Address_H : out std_logic_vector( 7 downto 0);
signal DA : inout std_logic_vector( 7 downto 0);
signal ALE : out std_logic ;
signal RD : out std_logic ;
signal WR : out std_logic ;
signal DIR_buffer : in std_logic
) is
begin
RD <= '1';
WR <= '1';
wait until falling_edge(clk);
ALE <= '1';
wait until rising_edge(clk);
Address_H <= Address(15 downto 8);
DA <= Address(7 downto 0);
wait until falling_edge(clk);
ALE <= '0';
wait for 5 ns;
DA <= (others => 'Z');
wait until rising_edge(clk);
wait for 0.5*TCLCL - 20 ns;
RD <= '0';
wait until rising_edge(clk);
assert DIR_buffer = '1' report "buffer direction error" severity error;
value := DA;
RD <= '1';
wait until falling_edge(clk);
DA <= (others => 'Z');
Address_H <= (others => 'Z');
end procedure atmega_read;
end package body atmega_pkg;
|
102chute
|
trunk/code/vhdl_v2/testbench/atmega_pkg.vhd
|
VHDL
|
gpl2
| 3,273
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 01/05/2008
-- File : Wb_pwm.vhd
--
-- Abstract : A simple IP to drive pwm
--
--0x00 : |speed(7 downto 0)|
--0x01 : |dir|x|x|x|x|x|speed(9 downto 8)|
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
---------------------------------------------------------------------------
Entity Wb_pwm is
---------------------------------------------------------------------------
generic(
-- fpga frequency at 50MHz
constant freq_fpga : natural := 50000000;
-- pwm frequency at 10kHz
constant freq_pwm : natural := 10000
);
port
(
-- syscon signals
reset_n : in std_logic ;
clk : in std_logic ;
--Wishbone signals
wbs_address : in std_logic ;
wbs_writedata : in std_logic_vector( 7 downto 0);
wbs_readdata : out std_logic_vector( 7 downto 0);
wbs_strobe : in std_logic ;
wbs_write : in std_logic ;
wbs_ack : out std_logic ;
-- output
pwm : out std_logic ;
pwm_dir : out std_logic
);
end entity;
---------------------------------------------------------------------------
Architecture Wb_pwm_1 of Wb_pwm is
---------------------------------------------------------------------------
signal speed : std_logic_vector( 9 downto 0);
signal dir : std_logic ;
signal refresh : std_logic ;
signal slow_clk : std_logic; -- clock for pwm generation
signal debug : std_logic ;
signal pwmdebug: natural;
begin
wbs_ack <= wbs_strobe;
pwm_dir <= dir;
-- Write value
writeproc : process (clk,reset_n)
begin
if reset_n = '0' then
speed <= (others => '0');
dir <= '0';
refresh<= '0';
elsif rising_edge(clk) then
refresh <= '0';
if ((wbs_strobe and wbs_write) = '1') then -- if write
if(wbs_address = '0') then -- address decoding
speed(7 downto 0) <= wbs_writedata;
dir <= dir;
else
speed(9 downto 8) <= wbs_writedata(1 downto 0);
dir <= wbs_writedata(7);
refresh <= '1';
end if;
end if;
end if;
end process writeproc;
--read value
readproc : process(clk,reset_n)
begin
if reset_n = '0' then
wbs_readdata <= (others => '0');
elsif rising_edge(clk) then
if(wbs_strobe and (not wbs_write)) = '1' then -- if read
if (wbs_address = '0') then -- address decoding
wbs_readdata <= speed(7 downto 0);
else
wbs_readdata <= dir&"00000"&speed(9 downto 8);
end if;
end if;
end if;
end process readproc;
-- under frequency clock generation (here 2.5MHz)
clk_pwm : process (clk,reset_n)
variable cmpt : natural range 1 to (freq_fpga/(256 * 2 * freq_pwm));
begin
if reset_n = '0' then
slow_clk <= '0';
cmpt := 1;
elsif rising_edge(clk) then
cmpt := cmpt + 1;
if (cmpt = (freq_fpga / (512 *2* freq_pwm))) then
slow_clk <= not slow_clk;
cmpt := 1;
end if;
end if;
end process clk_pwm;
-- pwm generation
pwmproc : process (clk,reset_n)
variable cmpt_pwm : natural range 0 to 1023;
variable slow_clk_old : std_logic ;
variable speedpwm : natural range 0 to 1023;
begin
if reset_n = '0' then
pwm <= '0';
cmpt_pwm := 0;
slow_clk_old := slow_clk;
speedpwm := 0;
elsif rising_edge(clk) then
debug <= '0';
-- if new speed value wrote
if refresh = '1' then
speedpwm := to_integer(unsigned(speed));
debug <= '1';
end if;
-- manage pwm on rising edge of slow_clk
if slow_clk_old = '0' and slow_clk = '1' then
cmpt_pwm := cmpt_pwm + 1;
pwmdebug <= cmpt_pwm;
if(cmpt_pwm = speedpwm) then
pwm <= '0';
-- TODO: better function
elsif cmpt_pwm = 1023 then -- When buffer overflow
cmpt_pwm := 0;
debug <= '1';
pwm <= '1';
end if;
end if;
slow_clk_old := slow_clk;
end if ;
end process pwmproc;
end architecture Wb_pwm_1;
|
102chute
|
trunk/code/vhdl_v2/src/Wb_pwm.vhd
|
VHDL
|
gpl2
| 3,969
|
---------------------------------------------------------------------------
-- Company : ARMadeus Systems
-- Author(s) : Fabien Marteau
--
-- Creation Date : 05/03/2008
-- File : Wb_led.vhd
--
-- Abstract : drive one led with Wishbone bus
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
-----------------------------------------------------------------------
Entity Wb_led is
-----------------------------------------------------------------------
port
(
-- Syscon signals
reset_n : in std_logic ;
clk : in std_logic ;
-- Wishbone signals
wbs_writedata : in std_logic_vector( 7 downto 0);
wbs_readdata : out std_logic_vector( 7 downto 0);
wbs_strobe : in std_logic ;
wbs_write : in std_logic ;
wbs_ack : out std_logic;
-- out signals
LED : out std_logic
);
end entity;
-----------------------------------------------------------------------
Architecture Wb_led_1 of Wb_led is
-----------------------------------------------------------------------
signal reg : std_logic_vector( 7 downto 0);
begin
-- connect led
LED <= reg(0);
-- manage register
reg_bloc : process(clk,reset_n)
begin
if reset_n = '0' then
reg <= (others => '0');
elsif rising_edge(clk) then
if ((wbs_strobe and wbs_write) = '1' ) then
reg <= wbs_writedata;
else
reg <= reg;
end if;
end if;
end process reg_bloc;
wbs_ack <= wbs_strobe;
wbs_readdata <= reg;
end architecture Wb_led_1;
|
102chute
|
trunk/code/vhdl_v2/src/Wb_led.vhd
|
VHDL
|
gpl2
| 1,548
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 24/04/2008
-- File : intercon.vhd
--
-- Abstract : Intercon is the component where we do
-- the address decoding
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
---------------------------------------------------------------------------
Entity intercon is
---------------------------------------------------------------------------
port
(
-- general clock and reset
gls_reset_n : in std_logic ;
gls_clock : in std_logic ;
-- Master wrapper port
wbm_reset_n : out std_logic ;
wbm_clk : out std_logic ;
wbm_address : in std_logic_vector( 15 downto 0);
wbm_readdata : out std_logic_vector( 7 downto 0);
wbm_writedata : in std_logic_vector( 7 downto 0);
wbm_strobe : in std_logic ;
wbm_write : in std_logic ;
wbm_ack : out std_logic ;
wbm_cycle : in std_logic ;
-- Slave LED port
wbs_reset_n : out std_logic ;
wbs_clk : out std_logic ;
wbs_writedata : out std_logic_vector(7 downto 0);
wbs_readdata : in std_logic_vector( 7 downto 0);
wbs_strobe : out std_logic ;
wbs_write : out std_logic ;
wbs_ack : in std_logic;
-- Slave pwm port
wbs_reset_n_pwm : out std_logic ;
wbs_clk_pwm : out std_logic ;
wbs_address_pwm : out std_logic;
wbs_writedata_pwm : out std_logic_vector( 7 downto 0);
wbs_readdata_pwm : in std_logic_vector( 7 downto 0);
wbs_strobe_pwm : out std_logic ;
wbs_write_pwm : out std_logic ;
wbs_ack_pwm : in std_logic
);
end entity;
---------------------------------------------------------------------------
Architecture intercon_1 of intercon is
---------------------------------------------------------------------------
signal led_cs : std_logic ;
signal pwm_cs : std_logic ;
signal cs : std_logic_vector( 1 downto 0);
begin
-- clock and reset connection
wbm_clk <= gls_clock;
wbm_reset_n <= gls_reset_n;
wbs_clk <= gls_clock;
wbs_reset_n <= gls_reset_n;
wbs_clk_pwm <= gls_clock;
wbs_reset_n_pwm <= gls_reset_n;
-- address decoding (asynchrone but ...)
led_cs <= '1' when wbm_address = x"1300" and wbm_strobe = '1' else '0';
pwm_cs <= '1' when (wbm_address = x"1302" or wbm_address = x"1303")
and wbm_strobe = '1' else '0';
wbs_address_pwm <= wbm_address(0) when pwm_cs = '1' else '0';
-- slave LED connection
wbs_writedata <= wbm_writedata when led_cs = '1' else (others => '0');
wbs_strobe <= wbm_strobe and led_cs;
wbs_write <= wbm_write and led_cs;
-- Slave pwm connection
wbs_writedata_pwm <= wbm_writedata when pwm_cs = '1' else (others => '0');
wbs_strobe_pwm <= wbm_strobe and pwm_cs;
wbs_write_pwm <= wbm_write and pwm_cs;
cs(0) <= led_cs;
cs(1) <= pwm_cs;
-- master wrapper connection
with cs select
wbm_readdata <= wbs_readdata when "01",
wbs_readdata_pwm when "10",
(others => '0') when others;
with cs select
wbm_ack <= wbs_ack when "01",
wbs_ack_pwm when "10",
'0' when others;
end architecture intercon_1;
|
102chute
|
trunk/code/vhdl_v2/src/intercon.vhd
|
VHDL
|
gpl2
| 3,299
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 23/04/2008
-- File : atmega_wrapper.vhd
--
-- Abstract : An atmega128 to wishbone wrapper components.
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
---------------------------------------------------------------------------
Entity atmega_wrapper is
---------------------------------------------------------------------------
port
(
-- Atmega128 port
Address_H : in std_logic_vector( 7 downto 0);
DA : inout std_logic_vector( 7 downto 0);
ALE : in std_logic ;
RD : in std_logic ;
WR : in std_logic ;
DIR_buffer: out std_logic ;
-- Wishbone port
wbm_address : out std_logic_vector( 15 downto 0);
wbm_readdata : in std_logic_vector( 7 downto 0);
wbm_writedata: out std_logic_vector( 7 downto 0);
wbm_strobe : out std_logic ;
wbm_write : out std_logic ;
wbm_ack : in std_logic ;
wbm_cycle : out std_logic ;
-- clock 50MHz and reset
clk : in std_logic ;
reset_n : in std_logic
);
end entity;
---------------------------------------------------------------------------
Architecture atmega_wrapper_1 of atmega_wrapper is
---------------------------------------------------------------------------
signal write : std_logic ;
signal strobe : std_logic ;
signal cycle : std_logic ;
signal writedata : std_logic_vector( 7 downto 0);
signal address : std_logic_vector( 15 downto 0);
begin
synchro : process(clk,reset_n)
begin
if reset_n = '0' then
strobe <= '0';
write <= '0';
cycle <= '0';
address <= (others => '0');
writedata <= (others => '0');
elsif rising_edge(clk) then
-- Address bus latching
if ALE = '1' then
address(15 downto 8) <= Address_H;
address(7 downto 0) <= DA;
else
address <= address;
end if;
writedata <= DA;
-- signals controls
strobe <= not(RD and WR);
cycle <= not(RD and WR);
write <= (not WR);
end if;
end process synchro;
wbm_write <= write;
wbm_strobe<= strobe;
wbm_cycle <= cycle;
wbm_address <= address;
wbm_writedata <= writedata when (write = '1') else (others => '0');
-- buffer direction
DIR_buffer <= '1' when write = '0' and strobe='1' else '0';
DA <= wbm_readdata when write = '0' and strobe='1' else (others => 'Z');
end architecture atmega_wrapper_1;
|
102chute
|
trunk/code/vhdl_v2/src/atmega_wrapper.vhd
|
VHDL
|
gpl2
| 2,535
|
---------------------------------------------------------------------------
-- Company : Vim Inc
-- Author(s) : Fabien Marteau
--
-- Creation Date : 24/04/2008
-- File : Top.vhd
--
-- Abstract : Blink blink a led ...
--
---------------------------------------------------------------------------
library IEEE;
use IEEE.STD_LOGIC_1164.ALL;
use IEEE.numeric_std.all;
---------------------------------------------------------------------------
Entity Top is
---------------------------------------------------------------------------
port
(
-- Atmega128 port
Address_H : in std_logic_vector( 7 downto 0);
DA : inout std_logic_vector( 7 downto 0);
ALE : in std_logic ;
RD : in std_logic ;
WR : in std_logic ;
DIR_buffer : out std_logic ;
-- Clock and reset
clk : in std_logic ;
reset_n : in std_logic ;
-- Output
LED : out std_logic ;
pwm : out std_logic ;
pwm_dir : out std_logic
);
end entity;
---------------------------------------------------------------------------
Architecture Top_1 of Top is
---------------------------------------------------------------------------
component atmega_wrapper
port (
-- Atmega128 port
Address_H : in std_logic_vector( 7 downto 0);
DA : inout std_logic_vector( 7 downto 0);
ALE : in std_logic ;
RD : in std_logic ;
WR : in std_logic ;
DIR_buffer : out std_logic ;
-- Wishbone port
wbm_address : out std_logic_vector( 15 downto 0);
wbm_readdata : in std_logic_vector( 7 downto 0);
wbm_writedata : out std_logic_vector( 7 downto 0);
wbm_strobe : out std_logic ;
wbm_write : out std_logic ;
wbm_ack : in std_logic ;
wbm_cycle : out std_logic ;
-- clock 50MHz and reset
clk : in std_logic ;
reset_n : in std_logic
);
end component;
component Wb_led
port (
-- Syscon signals
reset_n : in std_logic ;
clk : in std_logic ;
-- Wishbone signals
wbs_writedata : in std_logic_vector( 7 downto 0);
wbs_readdata : out std_logic_vector( 7 downto 0);
wbs_strobe : in std_logic ;
wbs_write : in std_logic ;
wbs_ack : out std_logic;
-- out signals
LED : out std_logic
);
end component;
component Wb_pwm
port (
-- syscon signals
reset_n : in std_logic ;
clk : in std_logic ;
--Wishbone signals
wbs_address : in std_logic ;
wbs_writedata : in std_logic_vector( 7 downto 0);
wbs_readdata : out std_logic_vector( 7 downto 0);
wbs_strobe : in std_logic ;
wbs_write : in std_logic ;
wbs_ack : out std_logic ;
-- output
pwm : out std_logic ;
pwm_dir : out std_logic
);
end component;
component intercon
port (
-- general clock and reset
gls_reset_n : in std_logic ;
gls_clock : in std_logic ;
-- Master wrapper port
wbm_reset_n : out std_logic ;
wbm_clk : out std_logic ;
wbm_address : in std_logic_vector( 15 downto 0);
wbm_readdata : out std_logic_vector( 7 downto 0);
wbm_writedata : in std_logic_vector( 7 downto 0);
wbm_strobe : in std_logic ;
wbm_write : in std_logic ;
wbm_ack : out std_logic ;
wbm_cycle : in std_logic ;
-- Slave LED port
wbs_reset_n : out std_logic ;
wbs_clk : out std_logic ;
wbs_writedata : out std_logic_vector(7 downto 0);
wbs_readdata : in std_logic_vector( 7 downto 0);
wbs_strobe : out std_logic ;
wbs_write : out std_logic ;
wbs_ack : in std_logic;
-- Slave pwm port
wbs_reset_n_pwm : out std_logic ;
wbs_clk_pwm : out std_logic ;
wbs_address_pwm : out std_logic;
wbs_writedata_pwm : out std_logic_vector( 7 downto 0);
wbs_readdata_pwm : in std_logic_vector( 7 downto 0);
wbs_strobe_pwm : out std_logic ;
wbs_write_pwm : out std_logic ;
wbs_ack_pwm : in std_logic
);
end component;
-- Master wrapper port
signal wbm_reset_n : std_logic ;
signal wbm_clk : std_logic ;
signal wbm_address : std_logic_vector( 15 downto 0);
signal wbm_readdata : std_logic_vector( 7 downto 0);
signal wbm_writedata: std_logic_vector( 7 downto 0);
signal wbm_strobe : std_logic ;
signal wbm_write : std_logic ;
signal wbm_ack : std_logic ;
signal wbm_cycle : std_logic ;
-- Slave LED port
signal wbs_reset_n : std_logic ;
signal wbs_clk : std_logic ;
signal wbs_writedata : std_logic_vector( 7 downto 0);
signal wbs_readdata : std_logic_vector( 7 downto 0);
signal wbs_strobe : std_logic ;
signal wbs_write : std_logic ;
signal wbs_ack : std_logic ;
-- Slave pwm port
signal wbs_reset_n_pwm : std_logic ;
signal wbs_clk_pwm : std_logic ;
signal wbs_address_pwm : std_logic ;
signal wbs_writedata_pwm : std_logic_vector( 7 downto 0);
signal wbs_readdata_pwm : std_logic_vector( 7 downto 0);
signal wbs_strobe_pwm : std_logic ;
signal wbs_write_pwm : std_logic ;
signal wbs_ack_pwm : std_logic ;
begin
connect_intercon : intercon
port map (
-- general clock and reset
gls_reset_n => reset_n,
gls_clock => clk,
-- Master wrapper port
wbm_reset_n => wbm_reset_n,
wbm_clk => wbm_clk ,
wbm_address => wbm_address ,
wbm_readdata => wbm_readdata ,
wbm_writedata => wbm_writedata,
wbm_strobe => wbm_strobe ,
wbm_write => wbm_write ,
wbm_ack => wbm_ack ,
wbm_cycle => wbm_cycle ,
-- Slave LED port
wbs_reset_n => wbs_reset_n ,
wbs_clk => wbs_clk ,
wbs_writedata => wbs_writedata,
wbs_readdata => wbs_readdata ,
wbs_strobe => wbs_strobe ,
wbs_write => wbs_write ,
wbs_ack => wbs_ack,
-- Slave pwm port
wbs_reset_n_pwm => wbs_reset_n_pwm ,
wbs_clk_pwm => wbs_clk_pwm ,
wbs_address_pwm => wbs_address_pwm,
wbs_writedata_pwm => wbs_writedata_pwm,
wbs_readdata_pwm => wbs_readdata_pwm ,
wbs_strobe_pwm => wbs_strobe_pwm ,
wbs_write_pwm => wbs_write_pwm ,
wbs_ack_pwm => wbs_ack_pwm
);
connect_Wb_led : Wb_led
port map (
-- Syscon signals
reset_n => wbs_reset_n ,
clk => wbs_clk ,
-- Wishbone signa-- Wishbone sls
wbs_writedata => wbs_writedata,
wbs_readdata => wbs_readdata ,
wbs_strobe => wbs_strobe ,
wbs_write => wbs_write ,
wbs_ack => wbs_ack ,
-- out signals -- out signal
LED => LED
);
connect_Wb_pwm : Wb_pwm
port map (
-- syscon signals
reset_n => wbs_reset_n_pwm,
clk => wbs_clk_pwm,
--Wishbone signals
wbs_address => wbs_address_pwm,
wbs_writedata => wbs_writedata_pwm,
wbs_readdata => wbs_readdata_pwm,
wbs_strobe => wbs_strobe_pwm,
wbs_write => wbs_write_pwm,
wbs_ack => wbs_ack_pwm,
-- output
pwm => pwm,
pwm_dir => pwm_dir
);
connect_atmega_wrapper : atmega_wrapper
port map (
-- Atmega128 port
Address_H => Address_H ,
DA => DA ,
ALE => ALE ,
RD => RD ,
WR => WR ,
DIR_buffer => DIR_buffer ,
-- Wishbone port
wbm_address => wbm_address ,
wbm_readdata => wbm_readdata ,
wbm_writedata => wbm_writedata,
wbm_strobe => wbm_strobe ,
wbm_write => wbm_write ,
wbm_ack => wbm_ack ,
wbm_cycle => wbm_cycle ,
-- clock 50MHz and reset
clk => wbm_clk,
reset_n => wbm_reset_n
);
end architecture Top_1;
|
102chute
|
trunk/code/vhdl_v2/src/Top.vhd
|
VHDL
|
gpl2
| 7,996
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
import time
class SuspectIP:
def __init__(self,ip):
self.ip = ip
self.lastpacket_received = time.time()
#all the different step
self.step1_dns = False
self.step2_https = False
self.step3_home_request = False
self.step4_answer = False
self.chat_request = False
self.chat_reply = False
self.isauth = False
def getIP(self):
return self.ip
def getLastPacketDate(self):
return self.lastpacket_received
def addValue(self, name,string):
self.lastpacket_received = time.time()
if name == "step1": self.step1_dns = True
elif name == "step2": self.step2_https = True
elif name == "step3": self.step3_home_request = True
elif name == "step4":
if self.step3_home_request and not self.step4_answer:
print string # print message only if the request has been done before
self.step4_answer = True
elif name == "chat_q": self.chat_request = True
elif name == "chat_r":
if self.chat_request and not self.chat_reply:
print string # print message only if the request has been done before
self.chat_reply = True
def authenticated(self):#return true if all steps are true
if not self.isauth:
if self.step2_https and self.step3_home_request and self.step4_answer:
self.isauth = True
return True
else:
return False
else:
return False
#Note DNS request is exclud because not significant of authentication if the browser keep the ip in cache
class Facebook:
def __init__(self):
self.suspect_list = list()
self.ip_packet = list()
self.tcp_packet = list()
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
else:
return #jump early to do not slowdown traffic
if isUDP(self.ip_packet):
self.test_step1_dns()
elif isTCP(self.ip_packet):
#All packet from here are normally TCP !
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 443:
self.test_step2_https()
elif self.tcp_packet.get_th_dport() == 80:
self.test_step3_home_request()
self.test_chat_request()
elif self.tcp_packet.get_th_sport() == 80:
self.test_step4_answer()
self.test_chat_answer()
self.update_list()
def processPacket(self, ip, name,string=""):
exist = False
for suspect in self.suspect_list:
if suspect.getIP() == ip:
exist = True
suspect.addValue(name,string)
if suspect.authenticated() == True:
print "IP:",suspect.getIP()," seems fully authenticated on Facebook !"
if not exist:
new = SuspectIP(ip)
new.addValue(name,string)
self.suspect_list.append(new)
def update_list(self):
for i in range(len(self.suspect_list)):
if (time.time() - self.suspect_list[i].getLastPacketDate()) > 180:
#if the last packet of the host is older than 3 minutes
print self.suspect_list[i].getIP()," reseted (facebook)"
del self.suspect_list[i]
def test_step1_dns(self):
udp_packet = getTCPorUDPPacket(self.ip_packet)
srcip = getSrcIp(self.ip_packet)
#si double recup 3 ème charactère convertir en base 2 (see packet manager) et voir si le premier element et 0
if getDstPortUDP(udp_packet) == 53:
data = udp_packet.get_data_as_string()
if re.search("www.facebook.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:",srcip," DNS request for www.facebook.com"
self.processPacket(srcip,"step1")
def test_step2_https(self):
ipsrc = getSrcIp(self.ip_packet)
data = self.tcp_packet.get_data_as_string()
if re.search("www.facebook.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:",ipsrc," Possible HTTPS connection on www.facebook.com"
self.processPacket(ipsrc,"step2")
def test_step3_home_request(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0] #in theory in http taxonomy from client it is "command line" and from server it is "status line"
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if headers['Host'] == "www.facebook.com":
if re.match("GET /home.php HTTP/1.1",request) or re.match("GET /update_security_info.php\?wizard=1 HTTP/1.1",request):
print "%s %s:%s->%s:%s Facebook home page requested" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
self.processPacket(srcip,"step3")
def test_step4_answer(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if not headers['Content-Type'] == None:
if re.match("text/html",headers['Content-Type']) and re.match("HTTP/1.1 200 OK",request):
to_print = "%s %s:%s->%s:%s Server reply: 200 OK" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
#don't print the string here to avoid redundancy if buddy list request has not been done (and it is impossible to know it here)
self.processPacket(dstip,"step4",to_print)
def test_chat_request(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if headers['Host'] == "www.facebook.com":
if re.search("POST /ajax/chat/buddy_list.php\?__a=1 HTTP/1.1",request):
print "%s %s:%s->%s:%s Facebook contact chat list requested" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
self.processPacket(srcip,"chat_q")
def test_chat_answer(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if not headers['Content-Type'] == None:
if re.match("application/x-javascript",headers['Content-Type']) and re.match("HTTP/1.1 200 OK",request):
to_print = "%s %s:%s->%s:%s Server reply: 200 OK (for chat)" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
#don't print the string here to avoid redundancy if buddy list request has not been done (and it is impossible to know it here)
self.processPacket(dstip,"chat_r",to_print)
|
10014500-myids
|
trunk/facebook.py
|
Python
|
gpl3
| 7,445
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import sys #for future parsing args
import os
import threading
import socket
from pcapy import findalldevs, open_live, open_offline
from impacket import ImpactDecoder, ImpactPacket
import datetime
import time
import string
# --- Include of written modules ---
from sniffer import AnalysePacket
from PortScan import PortScan
from nmap_os_scan import OSScan
from msn_protocol import MSN
from facebook import Facebook
from bbc import BBC
from botnet import botnet
#-----------------------------------
def get_interface():
inter = findalldevs()
i=0
for eth in inter:
print " %d - %s" %(i,inter[i])
i+=1
value=input(" Select interface: ")
return inter[value]
#interface = get_interface()
def getLocalIP():
#if os.uname()[0].startswith("Li"):
if not os.name == "nt":
import fcntl, struct
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', interface[:15]))[20:24])
else:
return socket.gethostbyname(socket.gethostname())
#---- Instantiation of modules (even not used) ---#
interface = get_interface()
portscan = PortScan(getLocalIP(),["classic"] , False,"medium")
osscan = OSScan("192.168.0.57","perfect")
sniffer = AnalysePacket()
msn = MSN(getLocalIP(),True)
fb = Facebook()
bbc = BBC()
botnet = botnet()
#-------------------------------------------------#
def event_packet_received(header, data):
recieve_date = time.time()
#-- Call the analyse function --#
osscan.analyse(data,recieve_date)
portscan.analyse(data)
#sniffer.analyse(data)
msn.analyse(data)
fb.analyse(data)
bbc.analyse(data)
botnet.analyse(data,recieve_date)
#-------------------------------#
def launch_capture(interface_to_listen):
# Open a live capture
p = open_live(interface_to_listen, 1500, 0, 100)
#p = open_offline("mycapture.pcap")
print "Listening on %s: ip=%s net=%s, mask=%s\n" % (interface_to_listen, getLocalIP(), p.getnet(), p.getmask())
#p.setfilter(get_filter())
try:
p.loop(0, event_packet_received)
except KeyboardInterrupt:
print "Keybord interrupt recieved !"
sys.exit(0)
''' not used yet
def get_filter():
#Imagine you read a file and retrieve some filters
i=0
for f in filt:
fil += " "+filt
i+=1
return fil
'''
def main():
#Retreive normally arguments
if interface:
launch_capture(interface)
if __name__ == "__main__":
main()
|
10014500-myids
|
trunk/myids.py
|
Python
|
gpl3
| 2,672
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
class AnalysePacket:
def __init__(self):
self.packet = 0
def analyse(self, pack):
self.packet = pack
ether_packet = ImpactDecoder.EthDecoder().decode(self.packet) #Voir old
eth_mac_destination = getStringMac(ether_packet.get_ether_dhost())
eth_mac_source = getStringMac(ether_packet.get_ether_shost())
eth_type = hex(ether_packet.get_ether_type())
#others args
#eth_header_size = str(ether_packet.get_header_size());
#eth_datas = ether_packet.get_data_as_string();
protocol=getNameProtocolEthernet(eth_type)
#datetime.now().strftime("%H:%M:%S")
print "\n\nEthernet:\tMAC src:%s\tMAC dst:%s\tEthertype:%s(%s)" % (''.join(eth_mac_source),eth_mac_destination,eth_type,protocol)
if protocol=="IPv4":
self.analyseIP(ether_packet);
elif protocol=="ARP":
pass
#self.analyseARP(ether_packet)
def analyseIP(self,ether):
#For further informations:http://www.networksorcery.com/enp/default1101.htm
#http://www.wikistc.org/wiki/Packet_crafting
ip_packet = ether.child()
ip_version = ip_packet.get_ip_v() #ip version
head_length = ip_packet.get_ip_hl() # should be IHL for Internet Header Length
tos = ip_packet.get_ip_tos() # TOS field
total_length = ip_packet.get_ip_len() # field total length
identification = ip_packet.get_ip_id() # field identification of ip packet
flag_rf = ip_packet.get_ip_rf() # reserved flag
flag_df = ip_packet.get_ip_df() # flag don't fragment
flag_mf = ip_packet.get_ip_mf() # flag more fragmentation
flag_off = ip_packet.get_ip_off() # flag offset
ttl = ip_packet.get_ip_ttl() #TTL
protocol = ip_packet.get_ip_p() # protocol field
header_checksum = ip_packet.get_ip_sum()# checksum field
ip_source = ip_packet.get_ip_src() # ip source
ip_destination = ip_packet.get_ip_dst() # ip destination
'''
others args
ip_header_size = str(ip_packet.getheader_size());
ip_datas = ip_packet.get_data_as_string();
ip_offmask = ip_packet.get_ip_offmask() #should be to help processing of offset
pseudo_header = ip_packet.get_pseudo_header(); #should be additional headers
'''
protocol_name=getNameProtocolIP(protocol)
print "IPv%s:\tIP src:%s\tIP dst:%s\tProtocol:%s(%s)\tTTL:%s" % (ip_version,ip_source,ip_destination,protocol,protocol_name,ttl)
if protocol_name == "TCP":
self.analyseTCP(ip_packet)
elif protocol_name == "ICMP":
#self.analyseICMP(ip_packet)
pass
else:
pass
#for other protocol: http://www.networksorcery.com/enp/protocol/ip.htm
def analyseTCP(self,ip):
#for further info:http://www.networksorcery.com/enp/protocol/tcp.htm
tcp_packet = ip.child()
ecn_flag_CWR = tcp_packet.get_CWR() #flag cwr for ECN: Explicit Congestion Notification
ecn_flag_ECE = tcp_packet.get_ECE() #flag ECE for ECN
flag_URG = tcp_packet.get_URG()
flag_ACK = tcp_packet.get_ACK() #flag ack
flag_PSH = tcp_packet.get_PSH()
flag_RST = tcp_packet.get_RST()
flag_SYN = tcp_packet.get_SYN()
flag_FIN = tcp_packet.get_FIN() #flag fin
options = tcp_packet.get_options() #field options
port_dst = tcp_packet.get_th_dport()
port_src = tcp_packet.get_th_sport()
data_offset = tcp_packet.get_th_off()
seq_num = tcp_packet.get_th_seq()
ack_num = tcp_packet.get_th_ack()
checksum = tcp_packet.get_th_sum()
urgent_pointer = tcp_packet.get_th_urp()
window = tcp_packet.get_th_win()
'''
other args
get_flag(self, bit)
get_header_size
get_data_as_string
get_packet() #return the entire packet !
#others: get_padded_options, get_th_flags(may just return a string with all flags)
'''
name_portsrc = getNameApplicationTCP(port_src)
name_portdst = getNameApplicationTCP(port_dst)
flags = getFlagsString(flag_URG,flag_ACK,flag_PSH,flag_RST,flag_SYN,flag_FIN)
# Print the results
print "TCP: src port:%s\(%s)\tdst port:%s(%s)\tflags:%s\tSn:%s\tAn:%s\tWin:%s" % (port_src, name_portsrc,port_dst,name_portdst,flags,seq_num,ack_num,window)
def analyseTCPOption(self,opt):
opt=tcp_packet.get_options()
for elt in opt:
print "Kind:",elt.get_kind()
print "Length:",elt.get_len()
print "shift:",elt.get_shift_cnt()
|
10014500-myids
|
trunk/sniffer.py
|
Python
|
gpl3
| 4,507
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
class MSN:
def __init__(self,ip, parano=False):
self.local_ip = ip
self.ip_packet = list()
self.tcp_packet = list()
self.paranoid_mode = parano #will determine if all tcp packets are examined or just dst.port=1863
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
else:
return #jump early to do not slow down traffic
if isUDP(self.ip_packet):
udp_packet = getTCPorUDPPacket(self.ip_packet)
if getDstPortUDP(udp_packet) == 53:
data = udp_packet.get_data_as_string()
if re.search("login.live.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for login.live.com"
elif re.search("messenger.hotmail.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for messenger.hotmail.com"
elif re.search("g.live.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for g.live.com"
pass
elif isTCP(self.ip_packet):
#All packet from here are normally TCP !
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 80 or self.tcp_packet.get_th_sport() == 80:
return
#Directly skip all http traffic to avoid useless processing on it because we are not interested in
elif self.tcp_packet.get_th_dport() == 443 and getDecFlagsValue(self.tcp_packet) == 2:
#If we try to connect on a website in https, syn flags to trigger alarm once per connection(if it is)
if self.test_https_auth():
print datetime.now().strftime("%b %d, %H:%M:%S")," Connection on a HTTPS MSN Server (maybe to pick up a authentication ticket)"
elif self.tcp_packet.get_th_dport() == 1863 or self.tcp_packet.get_th_sport() == 1863:
self.test_msn_connection()
self.test_file_transfert()
elif self.paranoid_mode:
self.test_file_transfert()
else:
pass
else:
pass
def test_https_auth(self):
dst_ip = getDstIp(self.ip_packet)
msn_servers = ['65.54.165.137','65.54.165.141','65.54.165.139','65.54.165.169','65.54.165.179','65.54.186.77','65.54.165.136','65.54.165.177']
isMSNserver = False
#determined with an nslookup should be updated if needed
for ip in msn_servers:
if dst_ip == ip:
isMSNserver = True
return isMSNserver
def test_msn_connection(self):
data = self.tcp_packet.get_data_as_string()
if getDecFlagsValue(self.tcp_packet) == 2:
print "\n",datetime.now().strftime("%b %d, %H:%M:%S")," New Connection on the TCP 1863 (which can be a MSN notification server)!"
if re.match("VER 1 ",data):
#VER 1 MSNP21 MSNP20 MSNP19 MSNP18 MSNP17 CVR0
#VER 1 MSNP21
if getSrcIp(self.ip_packet) == self.local_ip:
print datetime.now().strftime("%b %d, %H:%M:%S")," VER Step detected Client->Server (Protocol version exchange)"
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," VER Step detected Server->Client (Version %s used)" % (data[6:12])
elif re.match("CVR 2 ",data):
#CVR 2 0x0409 winnt 6.1.0 i386 MSNMSGR 15.4.3502.0922 MSNMSGR me@hotmail.fr
#VmVyc2lvbjogMQ0KWGZyQ291bnQ6IDENCg==
if getSrcIp(self.ip_packet) == self.local_ip:
print datetime.now().strftime("%b %d, %H:%M:%S")," CVR Step detected Client->Server (client information sent)"
infos = data[6:].split(" ")
print "\t\tLocale:%s\tOS:%s(%s)\tArchi:%s\tClient:%s(%s)\tAddress:%s" % (infos[0],infos[1],infos[2],infos[3],infos[4],infos[5],infos[7])
#Further about locale :http://krafft.com/scripts/deluxe-calendar/lcid_chart.htm
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," CVR Step detected Server->Client (Stored client information received)"
elif re.match("USR 3 ",data):
#USR 3 SSO I me@hotmail.fr
#alert user send the initiation message of authentication
infos = data.split(" ")
print datetime.now().strftime("%b %d, %H:%M:%S")," USR Step detected (Initiation authentication) method:%s\tAddress:%s" % (infos[2],infos[4])
elif re.match("USR 4 ",data) and not re.match("USR 4 OK ",data):
# USR 4 SSO S t=E (s for subsequent and the ticket attached)
#Note SSO was not used to match because I don't know but, may other methods exists
print datetime.now().strftime("%b %d, %H:%M:%S")," USR Step detected (Ticket/Token dispatching)"
elif re.match("USR 4 OK ",data):
#USR 4 OK me@hotmail.fr 1 0
infos= data.split(" ")
print datetime.now().strftime("%b %d, %H:%M:%S")," Address %s connected and authenticated to msn !" % (infos[3])
def test_file_transfert(self):
data = self.tcp_packet.get_data_as_string()
new_data = ["",data]
if re.search("INVITE",data):#keep only invitation message
notFound = True
while notFound: #separate first line from the rest and delete useless \n before
new_data = new_data[1].split("\n",1)
if re.search("INVITE",new_data[0]):
notFound = False
else:
pass
#First element in the array contain invitation message
#The second contain mime elements
#should do this, because otherwise the mime parsing fail due to the first line which is not mime
if len(new_data) >= 2:#otherwise parsing below can fail due to out of range
new_data[1] = re.sub(r'\r\n\r\n','\r\n',new_data[1])
mime_elts = Parser().parsestr(new_data[1],True) # parse the packet as mime type (True means ignore payload)
#So to get payload remove True, and it is accessible with mime_elts.get_payload()
if mime_elts['EUF-GUID'] == "{5D3E02AB-6190-11D3-BBBB-00C04F795683}": #This is signature of file transfert !
if re.search("INVITE",new_data[0]):#if it was really an invitation
print "\n",datetime.now().strftime("%b %d, %H:%M:%S")," File transfer invitation !"
print "\t\tFrom:%s\n\t\tTo:%s" % (mime_elts['From'],mime_elts['To'])
#additional tests
if mime_elts['CSeq'] == "0 " or mime_elts['CSeq'] == "0":#windows live put a space other client not
print "\t\tAnymore CSeq = 0 (file transfer signature)"
if mime_elts['appID'] == '2':
print "\t\tAnymore AppID = 2 (file transfer signature)"
if mime_elts['Content-Type'] == "application/x-msnmsgr-sessionreqbody":
print "\t\tAnymore Content-Type = application/x-msnmsgr-sessionreqbody (file transfer signature)\n"
|
10014500-myids
|
trunk/msn_protocol.py
|
Python
|
gpl3
| 6,795
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
import time
class SuspectIP:
def __init__(self,ip):
self.ip = ip
self.lastpacket_received = time.time()
#all the different step
self.step1_dns = False
self.step2_https = False
self.step3_home_request = False
self.step4_answer = False
self.chat_request = False
self.chat_reply = False
self.isauth = False
def getIP(self):
return self.ip
def getLastPacketDate(self):
return self.lastpacket_received
def addValue(self, name,string):
self.lastpacket_received = time.time()
if name == "step1": self.step1_dns = True
elif name == "step2": self.step2_https = True
elif name == "step3": self.step3_home_request = True
elif name == "step4":
if self.step3_home_request and not self.step4_answer:
print string # print message only if the request has been done before
self.step4_answer = True
elif name == "chat_q": self.chat_request = True
elif name == "chat_r":
if self.chat_request and not self.chat_reply:
print string # print message only if the request has been done before
self.chat_reply = True
def authenticated(self):#return true if all steps are true
if not self.isauth:
if self.step2_https and self.step3_home_request and self.step4_answer:
self.isauth = True
return True
else:
return False
else:
return False
#Note DNS request is exclud because not significant of authentication if the browser keep the ip in cache
class Facebook:
def __init__(self):
self.suspect_list = list()
self.ip_packet = list()
self.tcp_packet = list()
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
else:
return #jump early to do not slowdown traffic
if isUDP(self.ip_packet):
self.test_step1_dns()
elif isTCP(self.ip_packet):
#All packet from here are normally TCP !
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 443:
self.test_step2_https()
elif self.tcp_packet.get_th_dport() == 80:
self.test_step3_home_request()
self.test_chat_request()
elif self.tcp_packet.get_th_sport() == 80:
self.test_step4_answer()
self.test_chat_answer()
self.update_list()
def processPacket(self, ip, name,string=""):
exist = False
for suspect in self.suspect_list:
if suspect.getIP() == ip:
exist = True
suspect.addValue(name,string)
if suspect.authenticated() == True:
print "IP:",suspect.getIP()," seems fully authenticated on Facebook !"
if not exist:
new = SuspectIP(ip)
new.addValue(name,string)
self.suspect_list.append(new)
def update_list(self):
for i in range(len(self.suspect_list)):
if (time.time() - self.suspect_list[i].getLastPacketDate()) > 180:
#if the last packet of the host is older than 3 minutes
print self.suspect_list[i].getIP()," reseted (facebook)"
del self.suspect_list[i]
def test_step1_dns(self):
udp_packet = getTCPorUDPPacket(self.ip_packet)
srcip = getSrcIp(self.ip_packet)
#si double recup 3 ème charactère convertir en base 2 (see packet manager) et voir si le premier element et 0
if getDstPortUDP(udp_packet) == 53:
data = udp_packet.get_data_as_string()
if re.search("www.facebook.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:",srcip," DNS request for www.facebook.com"
self.processPacket(srcip,"step1")
def test_step2_https(self):
ipsrc = getSrcIp(self.ip_packet)
data = self.tcp_packet.get_data_as_string()
if re.search("www.facebook.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:",ipsrc," Possible HTTPS connection on www.facebook.com"
self.processPacket(ipsrc,"step2")
def test_step3_home_request(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0] #in theory in http taxonomy from client it is "command line" and from server it is "status line"
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if headers['Host'] == "www.facebook.com":
if re.match("GET /home.php HTTP/1.1",request) or re.match("GET /update_security_info.php\?wizard=1 HTTP/1.1",request):
print "%s %s:%s->%s:%s Facebook home page requested" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
self.processPacket(srcip,"step3")
def test_step4_answer(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if not headers['Content-Type'] == None:
if re.match("text/html",headers['Content-Type']) and re.match("HTTP/1.1 200 OK",request):
to_print = "%s %s:%s->%s:%s Server reply: 200 OK" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
#don't print the string here to avoid redundancy if buddy list request has not been done (and it is impossible to know it here)
self.processPacket(dstip,"step4",to_print)
def test_chat_request(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if headers['Host'] == "www.facebook.com":
if re.search("POST /ajax/chat/buddy_list.php\?__a=1 HTTP/1.1",request):
print "%s %s:%s->%s:%s Facebook contact chat list requested" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
self.processPacket(srcip,"chat_q")
def test_chat_answer(self):
srcip = getSrcIp(self.ip_packet)
dstip = getDstIp(self.ip_packet)
srcport = self.tcp_packet.get_th_sport()
dstport = self.tcp_packet.get_th_dport()
data = self.tcp_packet.get_data_as_string()
new_data= data.split("\n",1)
if len(new_data) >= 2:
request = new_data[0]
raw_headers = new_data[1]
headers = Parser().parsestr(raw_headers,True) #true ignore payload
if not headers['Content-Type'] == None:
if re.match("application/x-javascript",headers['Content-Type']) and re.match("HTTP/1.1 200 OK",request):
to_print = "%s %s:%s->%s:%s Server reply: 200 OK (for chat)" % (datetime.now().strftime("%b %d, %H:%M:%S"),srcip,srcport,dstip,dstport)
#don't print the string here to avoid redundancy if buddy list request has not been done (and it is impossible to know it here)
self.processPacket(dstip,"chat_r",to_print)
|
10014500-myids
|
trunk/.svn/text-base/facebook.py.svn-base
|
Python
|
gpl3
| 7,445
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
def getStringMac(mac_in):
#Convert mac address from array to a string with ":"
joined_str = ''
for i in xrange(5):
joined_str += str(hex(mac_in[i])[2:])+":"
return joined_str + hex(mac_in[5])[2:]
def getNameProtocolEthernet(proto_in):
if proto_in == "0x800":
return "IPv4"
elif proto_in == "0x86DD":
return "IPv6"
elif proto_in == "0x806":
return "ARP"
elif proto_in == "0x8035":
return "RARP"
elif proto_in == "0x88CD":
return "SERCOS III"
elif proto_in == "0x8100":
return "IEEE 802.1Q"
elif proto_in == "0x8137":
return "SNMP"
elif proto_in == "0x880B":
return "PPP"
elif proto_in == "0x809B":
return "AppleTalk"
elif proto_in == "0x8137":
return "NetWare IPX/SPX"
else:
return "Unknown"
#there is lot's of others check :http://www.networksorcery.com/enp/protocol/802/ethertypes.htm
def getNameProtocolIP(proto_in):
if proto_in == 1:
return "ICMP"
elif proto_in == 6:
return "TCP"
elif proto_in == 4:
return "IPv4 Encapsulation"
elif proto_in == 17:
return "UDP"
else:
return "Unknown"
#http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml
def getNameApplicationTCP(port):
if port == 80:
return "HTTP"
elif port == 21:
return "FTP"
elif port == 22:
return "SSH"
elif port == 23:
return "telnet"
elif port == 21:
return "FTP"
elif port == 53:
return "DNS"
elif port == 110:
return "POP3"
elif port == 143:
return "IMAP"
elif port == 389:
return "LDAP"
elif port == 443:
return "HTTPS"
elif port == 1863:
return "MSNP"
else:
return "nc"
#http://www.iana.org/assignments/port-numbers
def getFlagsString(URG,ACK,PSH,RST,SYN,FIN):
st = ""
if URG: st += "U"
else:st += "-"
if ACK: st += "A"
else: st+= "-"
if PSH: st += "P"
else: st += "-"
if RST: st += "R"
else: st += "-"
if SYN: st += "S"
else: st += "-"
if FIN: st += "F"
else: st += "-"
return st
def getDecFlagsValue(p):
val=""
if p.get_URG(): val +="1"
else: val += "0"
if p.get_ACK(): val +="1"
else: val += "0"
if p.get_PSH(): val +="1"
else: val += "0"
if p.get_RST(): val += "1"
else: val += "0"
if p.get_SYN(): val += "1"
else: val += "0"
if p.get_FIN(): val += "1"
else: val += "0"
return int(val,2)#return the value of val converted into base 2
def isIP(p):
ether_packet = ImpactDecoder.EthDecoder().decode(p)
eth_type = hex(ether_packet.get_ether_type())
if getNameProtocolEthernet(eth_type) == "IPv4":
return True
else:
return False
def getIPPacket(p):
return ImpactDecoder.EthDecoder().decode(p).child()
def getTCPorUDPPacket(p):
return p.child()
def isTCP(p):
return getNameProtocolIP(p.get_ip_p()) == "TCP"
def isUDP(p):
if getNameProtocolIP(p.get_ip_p()) == "UDP":
return True
else:
return False
def getDstIp(p):
return p.get_ip_dst()
def getSrcIp(p):
return p.get_ip_src()
def getDstPortTCP(p):
return p.get_th_dport()
def getDstPortUDP(p):
return p.get_uh_dport()
|
10014500-myids
|
trunk/.svn/text-base/packet_function.py.svn-base
|
Python
|
gpl3
| 3,217
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
class MSN:
def __init__(self,ip, parano=False):
self.local_ip = ip
self.ip_packet = list()
self.tcp_packet = list()
self.paranoid_mode = parano #will determine if all tcp packets are examined or just dst.port=1863
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
else:
return #jump early to do not slow down traffic
if isUDP(self.ip_packet):
udp_packet = getTCPorUDPPacket(self.ip_packet)
if getDstPortUDP(udp_packet) == 53:
data = udp_packet.get_data_as_string()
if re.search("login.live.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for login.live.com"
elif re.search("messenger.hotmail.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for messenger.hotmail.com"
elif re.search("g.live.com", data):
print datetime.now().strftime("%b %d, %H:%M:%S")," DNS request for g.live.com"
pass
elif isTCP(self.ip_packet):
#All packet from here are normally TCP !
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 80 or self.tcp_packet.get_th_sport() == 80:
return
#Directly skip all http traffic to avoid useless processing on it because we are not interested in
elif self.tcp_packet.get_th_dport() == 443 and getDecFlagsValue(self.tcp_packet) == 2:
#If we try to connect on a website in https, syn flags to trigger alarm once per connection(if it is)
if self.test_https_auth():
print datetime.now().strftime("%b %d, %H:%M:%S")," Connection on a HTTPS MSN Server (maybe to pick up a authentication ticket)"
elif self.tcp_packet.get_th_dport() == 1863 or self.tcp_packet.get_th_sport() == 1863:
self.test_msn_connection()
self.test_file_transfert()
elif self.paranoid_mode:
self.test_file_transfert()
else:
pass
else:
pass
def test_https_auth(self):
dst_ip = getDstIp(self.ip_packet)
msn_servers = ['65.54.165.137','65.54.165.141','65.54.165.139','65.54.165.169','65.54.165.179','65.54.186.77','65.54.165.136','65.54.165.177']
isMSNserver = False
#determined with an nslookup should be updated if needed
for ip in msn_servers:
if dst_ip == ip:
isMSNserver = True
return isMSNserver
def test_msn_connection(self):
data = self.tcp_packet.get_data_as_string()
if getDecFlagsValue(self.tcp_packet) == 2:
print "\n",datetime.now().strftime("%b %d, %H:%M:%S")," New Connection on the TCP 1863 (which can be a MSN notification server)!"
if re.match("VER 1 ",data):
#VER 1 MSNP21 MSNP20 MSNP19 MSNP18 MSNP17 CVR0
#VER 1 MSNP21
if getSrcIp(self.ip_packet) == self.local_ip:
print datetime.now().strftime("%b %d, %H:%M:%S")," VER Step detected Client->Server (Protocol version exchange)"
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," VER Step detected Server->Client (Version %s used)" % (data[6:12])
elif re.match("CVR 2 ",data):
#CVR 2 0x0409 winnt 6.1.0 i386 MSNMSGR 15.4.3502.0922 MSNMSGR me@hotmail.fr
#VmVyc2lvbjogMQ0KWGZyQ291bnQ6IDENCg==
if getSrcIp(self.ip_packet) == self.local_ip:
print datetime.now().strftime("%b %d, %H:%M:%S")," CVR Step detected Client->Server (client information sent)"
infos = data[6:].split(" ")
print "\t\tLocale:%s\tOS:%s(%s)\tArchi:%s\tClient:%s(%s)\tAddress:%s" % (infos[0],infos[1],infos[2],infos[3],infos[4],infos[5],infos[7])
#Further about locale :http://krafft.com/scripts/deluxe-calendar/lcid_chart.htm
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," CVR Step detected Server->Client (Stored client information received)"
elif re.match("USR 3 ",data):
#USR 3 SSO I me@hotmail.fr
#alert user send the initiation message of authentication
infos = data.split(" ")
print datetime.now().strftime("%b %d, %H:%M:%S")," USR Step detected (Initiation authentication) method:%s\tAddress:%s" % (infos[2],infos[4])
elif re.match("USR 4 ",data) and not re.match("USR 4 OK ",data):
# USR 4 SSO S t=E (s for subsequent and the ticket attached)
#Note SSO was not used to match because I don't know but, may other methods exists
print datetime.now().strftime("%b %d, %H:%M:%S")," USR Step detected (Ticket/Token dispatching)"
elif re.match("USR 4 OK ",data):
#USR 4 OK me@hotmail.fr 1 0
infos= data.split(" ")
print datetime.now().strftime("%b %d, %H:%M:%S")," Address %s connected and authenticated to msn !" % (infos[3])
def test_file_transfert(self):
data = self.tcp_packet.get_data_as_string()
new_data = ["",data]
if re.search("INVITE",data):#keep only invitation message
notFound = True
while notFound: #separate first line from the rest and delete useless \n before
new_data = new_data[1].split("\n",1)
if re.search("INVITE",new_data[0]):
notFound = False
else:
pass
#First element in the array contain invitation message
#The second contain mime elements
#should do this, because otherwise the mime parsing fail due to the first line which is not mime
if len(new_data) >= 2:#otherwise parsing below can fail due to out of range
new_data[1] = re.sub(r'\r\n\r\n','\r\n',new_data[1])
mime_elts = Parser().parsestr(new_data[1],True) # parse the packet as mime type (True means ignore payload)
#So to get payload remove True, and it is accessible with mime_elts.get_payload()
if mime_elts['EUF-GUID'] == "{5D3E02AB-6190-11D3-BBBB-00C04F795683}": #This is signature of file transfert !
if re.search("INVITE",new_data[0]):#if it was really an invitation
print "\n",datetime.now().strftime("%b %d, %H:%M:%S")," File transfer invitation !"
print "\t\tFrom:%s\n\t\tTo:%s" % (mime_elts['From'],mime_elts['To'])
#additional tests
if mime_elts['CSeq'] == "0 " or mime_elts['CSeq'] == "0":#windows live put a space other client not
print "\t\tAnymore CSeq = 0 (file transfer signature)"
if mime_elts['appID'] == '2':
print "\t\tAnymore AppID = 2 (file transfer signature)"
if mime_elts['Content-Type'] == "application/x-msnmsgr-sessionreqbody":
print "\t\tAnymore Content-Type = application/x-msnmsgr-sessionreqbody (file transfer signature)\n"
|
10014500-myids
|
trunk/.svn/text-base/msn_protocol.py.svn-base
|
Python
|
gpl3
| 6,795
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
import time
import re #regular expression
from email.parser import Parser #parser for mime type !
from packet_function import *
class BBC:
def __init__(self):
self.ip_packet = list()
self.tcp_packet = list()
self.lastmessage = ""
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
if isTCP(self.ip_packet):
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 1935:
data = self.tcp_packet.get_data_as_string()
if re.search("www..?bbc.c.?o.uk",data): #if pattern found then try to pick up path of stream
url_path = re.findall("(?!www\.bbc\/c.?o\.uk).*www\..?bbc\.co\.uk(.*)...$",data)[0]
ip = getSrcIp(self.ip_packet)
mess = "IP:%s\t Stream:www.bbc.co.uk%s" % (ip,url_path)
if mess != self.lastmessage: #avoid redundancy of message for same request and same ip
print datetime.now().strftime("%b %d, %H:%M:%S"),mess
self.lastmessage = mess
|
10014500-myids
|
trunk/.svn/text-base/bbc.py.svn-base
|
Python
|
gpl3
| 1,341
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import time
class SuspectHost:
def __init__(self, ip):
self.ip = ip
self.portlist = list()
self.lastpacketdate = time.time()
def getName(self):
return self.ip
def getPorts(self):
return self.portlist
def addPort(self, port):
exist = False
for i in range(len(self.portlist)):
if self.portlist[i][0] == port:
exist = True
self.portlist[i][1] += 1 #add 1 to the number of packets
if not exist:
self.portlist.append([port,1])
self.lastpacketdate = time.time() #update the date of the reception of the last packet
def calculateThreat_ratio(self):
sum_rate = 0
nb_packets = 0
for i in range(len(self.portlist)):
nb_packets += self.portlist[i][1]
sum_rate += 100 / self.portlist[i][1]
return sum_rate / len(self.portlist)
def getLastPacketDate(self):
return self.lastpacketdate
class PortScan:
def __init__(self, ip, scantype, node=True, sensibility="medium"): # may add parameters
self.my_listtcp = list()
self.my_listudp = list()
self.ip_packet = list()
self.tcp_packet = list()
self.udp_packet = list()
self.endnode = node
self.totalpackets = 0
if sensibility == "high":
self.sensibility = 50
elif sensibility == "medium":
self.sensibility = 70
elif sensibility == "low":
self.sensibility = 90
self.local_ip = ip # !!! Sometimes ip should be put manualy (when virtual machine use same real interface)
self.classic_detection=False
self.syn_scan=False
self.fin_scan=False
self.null_scan=False
self.ack_scan=False
self.xmas_scan=False
for element in scantype:
if element == "classic":
self.classic_detection=True
break
elif element == "syn_scan":
self.syn_scan=True
elif element == "ack_scan":
self.ack_scan=True
elif element == "null_scan":
self.null_scan=True
elif element == "xmas_scan":
self.xmas_scan=True
elif element == "fin_scan":
self.fin_scan=True
def analyse(self, data):
self.totalpackets += 1
if isIP(data): #Quit if not ip packet
self.ip_packet = getIPPacket(data)
else:
return
if isTCP(self.ip_packet):
#print "n°",self.totalpackets," TCP\r"
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
elif isUDP(self.ip_packet):
#print "n°",self.totalpackets," UDP"
self.udp_packet = getTCPorUDPPacket(self.ip_packet)
else:
return
#From here we just manipulate TCP or UDP packet
if self.endnode:
if not getDstIp(self.ip_packet) == self.local_ip:
return
#for end node we just keep incoming connection
#print "go in endnode", self.local_ip, " src:" , self.ip_packet.get_ip_src(), " dst:",self.ip_packet.get_ip_dst()
if self.classic_detection:
#In classic we don't care about flags (which are not reliable)
if isTCP(self.ip_packet):
self.processPacket(self.my_listtcp,getDstPortTCP(self.tcp_packet))
elif isUDP(self.ip_packet):
self.processPacket(self.my_listudp,getDstPortUDP(self.udp_packet))
else:
if isUDP(self.ip_packet):
self.processPacket(self.my_listudp,getDstPortUDP(self.udp_packet))
#UDP packet are process as in classic, because they don't have any flags
else:
flag_dec_value = getDecFlagsValue(self.tcp_packet)
#using dec value of flag we can check that a flag is activated and be sure not the others
if (self.syn_scan and flag_dec_value == 2) or (self.ack_scan and flag_dec_value == 16) or (self.fin_scan and flag_dec_value == 1) or (self.null_scan and flag_dec_value == 0) or (self.xmas_scan and flag_dec_value == 41):
self.processPacket(self.my_listtcp,getDstPortTCP(self.tcp_packet))
def processPacket(self, given_list,port):
if self.endnode:
suspect_ip = getSrcIp(self.ip_packet)
else:
suspect_ip = getDstIp(self.ip_packet)
exist = False
for i in range(len( given_list)):
if given_list[i].getName() == suspect_ip:
exist = True
given_list[i].addPort(port)
threatvalue = given_list[i].calculateThreat_ratio()
if not exist:
new = SuspectHost(suspect_ip)
given_list.append(new)
new.addPort(port);
threatvalue = new.calculateThreat_ratio()
self.update_lists()
self.checkThreat(suspect_ip, threatvalue,given_list)
def update_lists(self):
for i in range(len(self.my_listtcp)):
if (time.time() - self.my_listtcp[i].getLastPacketDate()) > 300:
#if the last packet of the host is older than 5 minutes
del my_listtcp[i]
for i in range(len(self.my_listudp)):
if (time.time() - self.my_listudp[i].getLastPacketDate()) > 300:
#if the last packet of the host is older than 5 minutes
del my_listudp[i]
def checkThreat(self,ip,threat,given_list):
alert = False
if threat >= self.sensibility: # If the threat calculated with all ports and their ponderation > sensibility
for i in range(len(given_list)):
if given_list[i].getName() == ip:
if (len(given_list[i].getPorts())) > 10: # Updated to 10 (old was 3 and too much alert)
if self.endnode:
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:%s is scanning with a threat of:%s and as scanned the following ports:" % (ip,threat)
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:%s is being scanned with a threat of:%s and the following ports are scanned" % (ip,threat)
print given_list[i].getPorts(),"\n"
del given_list[i]
break
|
10014500-myids
|
trunk/.svn/text-base/PortScan.py.svn-base
|
Python
|
gpl3
| 5,937
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import sys #for future parsing args
import os
import threading
import socket
from pcapy import findalldevs, open_live, open_offline
from impacket import ImpactDecoder, ImpactPacket
import datetime
import time
import string
# --- Include of written modules ---
from sniffer import AnalysePacket
from PortScan import PortScan
from nmap_os_scan import OSScan
from msn_protocol import MSN
from facebook import Facebook
from bbc import BBC
from botnet import botnet
#-----------------------------------
def get_interface():
inter = findalldevs()
i=0
for eth in inter:
print " %d - %s" %(i,inter[i])
i+=1
value=input(" Select interface: ")
return inter[value]
#interface = get_interface()
def getLocalIP():
#if os.uname()[0].startswith("Li"):
if not os.name == "nt":
import fcntl, struct
s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(s.fileno(),0x8915,struct.pack('256s', interface[:15]))[20:24])
else:
return socket.gethostbyname(socket.gethostname())
#---- Instantiation of modules (even not used) ---#
interface = get_interface()
portscan = PortScan(getLocalIP(),["classic"] , False,"medium")
osscan = OSScan("192.168.0.57","perfect")
sniffer = AnalysePacket()
msn = MSN(getLocalIP(),True)
fb = Facebook()
bbc = BBC()
botnet = botnet()
#-------------------------------------------------#
def event_packet_received(header, data):
recieve_date = time.time()
#-- Call the analyse function --#
osscan.analyse(data,recieve_date)
portscan.analyse(data)
#sniffer.analyse(data)
msn.analyse(data)
fb.analyse(data)
bbc.analyse(data)
botnet.analyse(data,recieve_date)
#-------------------------------#
def launch_capture(interface_to_listen):
# Open a live capture
p = open_live(interface_to_listen, 1500, 0, 100)
#p = open_offline("mycapture.pcap")
print "Listening on %s: ip=%s net=%s, mask=%s\n" % (interface_to_listen, getLocalIP(), p.getnet(), p.getmask())
#p.setfilter(get_filter())
try:
p.loop(0, event_packet_received)
except KeyboardInterrupt:
print "Keybord interrupt recieved !"
sys.exit(0)
''' not used yet
def get_filter():
#Imagine you read a file and retrieve some filters
i=0
for f in filt:
fil += " "+filt
i+=1
return fil
'''
def main():
#Retreive normally arguments
if interface:
launch_capture(interface)
if __name__ == "__main__":
main()
|
10014500-myids
|
trunk/.svn/text-base/myids.py.svn-base
|
Python
|
gpl3
| 2,672
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
class AnalysePacket:
def __init__(self):
self.packet = 0
def analyse(self, pack):
self.packet = pack
ether_packet = ImpactDecoder.EthDecoder().decode(self.packet) #Voir old
eth_mac_destination = getStringMac(ether_packet.get_ether_dhost())
eth_mac_source = getStringMac(ether_packet.get_ether_shost())
eth_type = hex(ether_packet.get_ether_type())
#others args
#eth_header_size = str(ether_packet.get_header_size());
#eth_datas = ether_packet.get_data_as_string();
protocol=getNameProtocolEthernet(eth_type)
#datetime.now().strftime("%H:%M:%S")
print "\n\nEthernet:\tMAC src:%s\tMAC dst:%s\tEthertype:%s(%s)" % (''.join(eth_mac_source),eth_mac_destination,eth_type,protocol)
if protocol=="IPv4":
self.analyseIP(ether_packet);
elif protocol=="ARP":
pass
#self.analyseARP(ether_packet)
def analyseIP(self,ether):
#For further informations:http://www.networksorcery.com/enp/default1101.htm
#http://www.wikistc.org/wiki/Packet_crafting
ip_packet = ether.child()
ip_version = ip_packet.get_ip_v() #ip version
head_length = ip_packet.get_ip_hl() # should be IHL for Internet Header Length
tos = ip_packet.get_ip_tos() # TOS field
total_length = ip_packet.get_ip_len() # field total length
identification = ip_packet.get_ip_id() # field identification of ip packet
flag_rf = ip_packet.get_ip_rf() # reserved flag
flag_df = ip_packet.get_ip_df() # flag don't fragment
flag_mf = ip_packet.get_ip_mf() # flag more fragmentation
flag_off = ip_packet.get_ip_off() # flag offset
ttl = ip_packet.get_ip_ttl() #TTL
protocol = ip_packet.get_ip_p() # protocol field
header_checksum = ip_packet.get_ip_sum()# checksum field
ip_source = ip_packet.get_ip_src() # ip source
ip_destination = ip_packet.get_ip_dst() # ip destination
'''
others args
ip_header_size = str(ip_packet.getheader_size());
ip_datas = ip_packet.get_data_as_string();
ip_offmask = ip_packet.get_ip_offmask() #should be to help processing of offset
pseudo_header = ip_packet.get_pseudo_header(); #should be additional headers
'''
protocol_name=getNameProtocolIP(protocol)
print "IPv%s:\tIP src:%s\tIP dst:%s\tProtocol:%s(%s)\tTTL:%s" % (ip_version,ip_source,ip_destination,protocol,protocol_name,ttl)
if protocol_name == "TCP":
self.analyseTCP(ip_packet)
elif protocol_name == "ICMP":
#self.analyseICMP(ip_packet)
pass
else:
pass
#for other protocol: http://www.networksorcery.com/enp/protocol/ip.htm
def analyseTCP(self,ip):
#for further info:http://www.networksorcery.com/enp/protocol/tcp.htm
tcp_packet = ip.child()
ecn_flag_CWR = tcp_packet.get_CWR() #flag cwr for ECN: Explicit Congestion Notification
ecn_flag_ECE = tcp_packet.get_ECE() #flag ECE for ECN
flag_URG = tcp_packet.get_URG()
flag_ACK = tcp_packet.get_ACK() #flag ack
flag_PSH = tcp_packet.get_PSH()
flag_RST = tcp_packet.get_RST()
flag_SYN = tcp_packet.get_SYN()
flag_FIN = tcp_packet.get_FIN() #flag fin
options = tcp_packet.get_options() #field options
port_dst = tcp_packet.get_th_dport()
port_src = tcp_packet.get_th_sport()
data_offset = tcp_packet.get_th_off()
seq_num = tcp_packet.get_th_seq()
ack_num = tcp_packet.get_th_ack()
checksum = tcp_packet.get_th_sum()
urgent_pointer = tcp_packet.get_th_urp()
window = tcp_packet.get_th_win()
'''
other args
get_flag(self, bit)
get_header_size
get_data_as_string
get_packet() #return the entire packet !
#others: get_padded_options, get_th_flags(may just return a string with all flags)
'''
name_portsrc = getNameApplicationTCP(port_src)
name_portdst = getNameApplicationTCP(port_dst)
flags = getFlagsString(flag_URG,flag_ACK,flag_PSH,flag_RST,flag_SYN,flag_FIN)
# Print the results
print "TCP: src port:%s\(%s)\tdst port:%s(%s)\tflags:%s\tSn:%s\tAn:%s\tWin:%s" % (port_src, name_portsrc,port_dst,name_portdst,flags,seq_num,ack_num,window)
def analyseTCPOption(self,opt):
opt=tcp_packet.get_options()
for elt in opt:
print "Kind:",elt.get_kind()
print "Length:",elt.get_len()
print "shift:",elt.get_shift_cnt()
|
10014500-myids
|
trunk/.svn/text-base/sniffer.py.svn-base
|
Python
|
gpl3
| 4,507
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
import time
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
class Triplet:
def __init__(self, port_nb):
self.port = port_nb
self.packet_list = list() #list of the date of the reception of the 3 packets !
def getPortName(self):
return self.port
def getIndex(self):
return len(self.packet_list)-1
def addElement(self,time):
if len(self.packet_list) < 3:
self.packet_list.append(time)
def getElement(self,i):
return self.packet_list[i]
class SuspectIP:
def __init__(self,ip,time):
self.ip = ip
self.nbpacket = 0
self.triplet_list = list() #List of triplet (normally maximum 10 triplets (3*10))
self.firstpacket_received = time
self.lastpacket_received = 0
def getIP(self):
return self.ip
def getLastPacketDate(self):
return self.lastpacket_received
def addPacket(self,port,time_recep):
self.lastpacket_received = time_recep
exist = False
for i in range(len(self.triplet_list)): #check all element of the list of suspect
if self.triplet_list[i].getPortName() == port: #if already in the list
exist = True
cur = self.triplet_list[i]
cur.addElement(time_recep) #add element to the triplet
index = cur.getIndex()
self.nbpacket += 1
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s Port:%s(%s/3) BOTNET packet Date:%s(difference:%s) Total count:%s" % (self.ip,cur.getPortName(),index+1, datetime.fromtimestamp(cur.getElement(index)).strftime("%H:%M:%S"), cur.getElement(index) - cur.getElement(index-1),self.nbpacket)
if self.nbpacket == 30:
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s all packet from botnet signature detected in %s seconds" % (self.ip, self.lastpacket_received - self.firstpacket_received)
if not exist:
new = Triplet(port) #Creation of the new suspect and push it in the list
new.addElement(time_recep)
self.nbpacket += 1
self.triplet_list.append(new)
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s Port:%s(1/3) BOTNET packet Date:%s Total count:%s" % (self.ip,port,datetime.fromtimestamp(time_recep).strftime("%H:%M:%S"),self.nbpacket)
#--------------------#
# Class Botnet #
#--------------------#
class botnet:
def __init__(self):
self.ip_packet = list()
self.tcp_packet = list()
self.suspect_list = list()
def analyse(self, data,time_recep):
if isIP(data):
self.ip_packet = getIPPacket(data)
srcip = getSrcIp(self.ip_packet)
if isTCP(self.ip_packet):
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 1013 and getDstIp(self.ip_packet) == "192.168.5.13" and getDecFlagsValue(self.tcp_packet) == 2: #if the packet matches all requirements
self.processPacket(srcip,self.tcp_packet.get_th_sport(),time_recep)
self.update_list()
def processPacket(self, ip,port,rec_time):
exist = False
for suspect in self.suspect_list:
if suspect.getIP() == ip:
exist = True
suspect.addPacket(port,rec_time)
if not exist:
new = SuspectIP(ip,rec_time)
new.addPacket(port,rec_time)
self.suspect_list.append(new)
def update_list(self):
for i in range(len(self.suspect_list)):
if (time.time() - self.suspect_list[i].getLastPacketDate()) > 240:
#if the last packet of the host is older than 4 minutes
print self.suspect_list[i].getIP()," reseted (botnet)"
del self.suspect_list[i]
|
10014500-myids
|
trunk/.svn/text-base/botnet.py.svn-base
|
Python
|
gpl3
| 3,857
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
import time
from packet_function import *
import re #regular expression
from email.parser import Parser #parser for mime type !
class Triplet:
def __init__(self, port_nb):
self.port = port_nb
self.packet_list = list() #list of the date of the reception of the 3 packets !
def getPortName(self):
return self.port
def getIndex(self):
return len(self.packet_list)-1
def addElement(self,time):
if len(self.packet_list) < 3:
self.packet_list.append(time)
def getElement(self,i):
return self.packet_list[i]
class SuspectIP:
def __init__(self,ip,time):
self.ip = ip
self.nbpacket = 0
self.triplet_list = list() #List of triplet (normally maximum 10 triplets (3*10))
self.firstpacket_received = time
self.lastpacket_received = 0
def getIP(self):
return self.ip
def getLastPacketDate(self):
return self.lastpacket_received
def addPacket(self,port,time_recep):
self.lastpacket_received = time_recep
exist = False
for i in range(len(self.triplet_list)): #check all element of the list of suspect
if self.triplet_list[i].getPortName() == port: #if already in the list
exist = True
cur = self.triplet_list[i]
cur.addElement(time_recep) #add element to the triplet
index = cur.getIndex()
self.nbpacket += 1
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s Port:%s(%s/3) BOTNET packet Date:%s(difference:%s) Total count:%s" % (self.ip,cur.getPortName(),index+1, datetime.fromtimestamp(cur.getElement(index)).strftime("%H:%M:%S"), cur.getElement(index) - cur.getElement(index-1),self.nbpacket)
if self.nbpacket == 30:
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s all packet from botnet signature detected in %s seconds" % (self.ip, self.lastpacket_received - self.firstpacket_received)
if not exist:
new = Triplet(port) #Creation of the new suspect and push it in the list
new.addElement(time_recep)
self.nbpacket += 1
self.triplet_list.append(new)
print datetime.now().strftime("%b %d, %H:%M:%S"),"IP:%s Port:%s(1/3) BOTNET packet Date:%s Total count:%s" % (self.ip,port,datetime.fromtimestamp(time_recep).strftime("%H:%M:%S"),self.nbpacket)
#--------------------#
# Class Botnet #
#--------------------#
class botnet:
def __init__(self):
self.ip_packet = list()
self.tcp_packet = list()
self.suspect_list = list()
def analyse(self, data,time_recep):
if isIP(data):
self.ip_packet = getIPPacket(data)
srcip = getSrcIp(self.ip_packet)
if isTCP(self.ip_packet):
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 1013 and getDstIp(self.ip_packet) == "192.168.5.13" and getDecFlagsValue(self.tcp_packet) == 2: #if the packet matches all requirements
self.processPacket(srcip,self.tcp_packet.get_th_sport(),time_recep)
self.update_list()
def processPacket(self, ip,port,rec_time):
exist = False
for suspect in self.suspect_list:
if suspect.getIP() == ip:
exist = True
suspect.addPacket(port,rec_time)
if not exist:
new = SuspectIP(ip,rec_time)
new.addPacket(port,rec_time)
self.suspect_list.append(new)
def update_list(self):
for i in range(len(self.suspect_list)):
if (time.time() - self.suspect_list[i].getLastPacketDate()) > 240:
#if the last packet of the host is older than 4 minutes
print self.suspect_list[i].getIP()," reseted (botnet)"
del self.suspect_list[i]
|
10014500-myids
|
trunk/botnet.py
|
Python
|
gpl3
| 3,857
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
def getStringMac(mac_in):
#Convert mac address from array to a string with ":"
joined_str = ''
for i in xrange(5):
joined_str += str(hex(mac_in[i])[2:])+":"
return joined_str + hex(mac_in[5])[2:]
def getNameProtocolEthernet(proto_in):
if proto_in == "0x800":
return "IPv4"
elif proto_in == "0x86DD":
return "IPv6"
elif proto_in == "0x806":
return "ARP"
elif proto_in == "0x8035":
return "RARP"
elif proto_in == "0x88CD":
return "SERCOS III"
elif proto_in == "0x8100":
return "IEEE 802.1Q"
elif proto_in == "0x8137":
return "SNMP"
elif proto_in == "0x880B":
return "PPP"
elif proto_in == "0x809B":
return "AppleTalk"
elif proto_in == "0x8137":
return "NetWare IPX/SPX"
else:
return "Unknown"
#there is lot's of others check :http://www.networksorcery.com/enp/protocol/802/ethertypes.htm
def getNameProtocolIP(proto_in):
if proto_in == 1:
return "ICMP"
elif proto_in == 6:
return "TCP"
elif proto_in == 4:
return "IPv4 Encapsulation"
elif proto_in == 17:
return "UDP"
else:
return "Unknown"
#http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xml
def getNameApplicationTCP(port):
if port == 80:
return "HTTP"
elif port == 21:
return "FTP"
elif port == 22:
return "SSH"
elif port == 23:
return "telnet"
elif port == 21:
return "FTP"
elif port == 53:
return "DNS"
elif port == 110:
return "POP3"
elif port == 143:
return "IMAP"
elif port == 389:
return "LDAP"
elif port == 443:
return "HTTPS"
elif port == 1863:
return "MSNP"
else:
return "nc"
#http://www.iana.org/assignments/port-numbers
def getFlagsString(URG,ACK,PSH,RST,SYN,FIN):
st = ""
if URG: st += "U"
else:st += "-"
if ACK: st += "A"
else: st+= "-"
if PSH: st += "P"
else: st += "-"
if RST: st += "R"
else: st += "-"
if SYN: st += "S"
else: st += "-"
if FIN: st += "F"
else: st += "-"
return st
def getDecFlagsValue(p):
val=""
if p.get_URG(): val +="1"
else: val += "0"
if p.get_ACK(): val +="1"
else: val += "0"
if p.get_PSH(): val +="1"
else: val += "0"
if p.get_RST(): val += "1"
else: val += "0"
if p.get_SYN(): val += "1"
else: val += "0"
if p.get_FIN(): val += "1"
else: val += "0"
return int(val,2)#return the value of val converted into base 2
def isIP(p):
ether_packet = ImpactDecoder.EthDecoder().decode(p)
eth_type = hex(ether_packet.get_ether_type())
if getNameProtocolEthernet(eth_type) == "IPv4":
return True
else:
return False
def getIPPacket(p):
return ImpactDecoder.EthDecoder().decode(p).child()
def getTCPorUDPPacket(p):
return p.child()
def isTCP(p):
return getNameProtocolIP(p.get_ip_p()) == "TCP"
def isUDP(p):
if getNameProtocolIP(p.get_ip_p()) == "UDP":
return True
else:
return False
def getDstIp(p):
return p.get_ip_dst()
def getSrcIp(p):
return p.get_ip_src()
def getDstPortTCP(p):
return p.get_th_dport()
def getDstPortUDP(p):
return p.get_uh_dport()
|
10014500-myids
|
trunk/packet_function.py
|
Python
|
gpl3
| 3,217
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
import time
import re #regular expression
from email.parser import Parser #parser for mime type !
from packet_function import *
class BBC:
def __init__(self):
self.ip_packet = list()
self.tcp_packet = list()
self.lastmessage = ""
def analyse(self, data):
if isIP(data):
self.ip_packet = getIPPacket(data)
if isTCP(self.ip_packet):
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
if self.tcp_packet.get_th_dport() == 1935:
data = self.tcp_packet.get_data_as_string()
if re.search("www..?bbc.c.?o.uk",data): #if pattern found then try to pick up path of stream
url_path = re.findall("(?!www\.bbc\/c.?o\.uk).*www\..?bbc\.co\.uk(.*)...$",data)[0]
ip = getSrcIp(self.ip_packet)
mess = "IP:%s\t Stream:www.bbc.co.uk%s" % (ip,url_path)
if mess != self.lastmessage: #avoid redundancy of message for same request and same ip
print datetime.now().strftime("%b %d, %H:%M:%S"),mess
self.lastmessage = mess
|
10014500-myids
|
trunk/bbc.py
|
Python
|
gpl3
| 1,341
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#-----------------------------------#
#Author: Robin David
#Matriculation: 10014500
#License: Creative Commons
#-----------------------------------#
import string
from impacket import ImpactDecoder, ImpactPacket #packet manipulation module
from datetime import datetime
from packet_function import *
import time
class SuspectHost:
def __init__(self, ip):
self.ip = ip
self.portlist = list()
self.lastpacketdate = time.time()
def getName(self):
return self.ip
def getPorts(self):
return self.portlist
def addPort(self, port):
exist = False
for i in range(len(self.portlist)):
if self.portlist[i][0] == port:
exist = True
self.portlist[i][1] += 1 #add 1 to the number of packets
if not exist:
self.portlist.append([port,1])
self.lastpacketdate = time.time() #update the date of the reception of the last packet
def calculateThreat_ratio(self):
sum_rate = 0
nb_packets = 0
for i in range(len(self.portlist)):
nb_packets += self.portlist[i][1]
sum_rate += 100 / self.portlist[i][1]
return sum_rate / len(self.portlist)
def getLastPacketDate(self):
return self.lastpacketdate
class PortScan:
def __init__(self, ip, scantype, node=True, sensibility="medium"): # may add parameters
self.my_listtcp = list()
self.my_listudp = list()
self.ip_packet = list()
self.tcp_packet = list()
self.udp_packet = list()
self.endnode = node
self.totalpackets = 0
if sensibility == "high":
self.sensibility = 50
elif sensibility == "medium":
self.sensibility = 70
elif sensibility == "low":
self.sensibility = 90
self.local_ip = ip # !!! Sometimes ip should be put manualy (when virtual machine use same real interface)
self.classic_detection=False
self.syn_scan=False
self.fin_scan=False
self.null_scan=False
self.ack_scan=False
self.xmas_scan=False
for element in scantype:
if element == "classic":
self.classic_detection=True
break
elif element == "syn_scan":
self.syn_scan=True
elif element == "ack_scan":
self.ack_scan=True
elif element == "null_scan":
self.null_scan=True
elif element == "xmas_scan":
self.xmas_scan=True
elif element == "fin_scan":
self.fin_scan=True
def analyse(self, data):
self.totalpackets += 1
if isIP(data): #Quit if not ip packet
self.ip_packet = getIPPacket(data)
else:
return
if isTCP(self.ip_packet):
#print "n°",self.totalpackets," TCP\r"
self.tcp_packet = getTCPorUDPPacket(self.ip_packet)
elif isUDP(self.ip_packet):
#print "n°",self.totalpackets," UDP"
self.udp_packet = getTCPorUDPPacket(self.ip_packet)
else:
return
#From here we just manipulate TCP or UDP packet
if self.endnode:
if not getDstIp(self.ip_packet) == self.local_ip:
return
#for end node we just keep incoming connection
#print "go in endnode", self.local_ip, " src:" , self.ip_packet.get_ip_src(), " dst:",self.ip_packet.get_ip_dst()
if self.classic_detection:
#In classic we don't care about flags (which are not reliable)
if isTCP(self.ip_packet):
self.processPacket(self.my_listtcp,getDstPortTCP(self.tcp_packet))
elif isUDP(self.ip_packet):
self.processPacket(self.my_listudp,getDstPortUDP(self.udp_packet))
else:
if isUDP(self.ip_packet):
self.processPacket(self.my_listudp,getDstPortUDP(self.udp_packet))
#UDP packet are process as in classic, because they don't have any flags
else:
flag_dec_value = getDecFlagsValue(self.tcp_packet)
#using dec value of flag we can check that a flag is activated and be sure not the others
if (self.syn_scan and flag_dec_value == 2) or (self.ack_scan and flag_dec_value == 16) or (self.fin_scan and flag_dec_value == 1) or (self.null_scan and flag_dec_value == 0) or (self.xmas_scan and flag_dec_value == 41):
self.processPacket(self.my_listtcp,getDstPortTCP(self.tcp_packet))
def processPacket(self, given_list,port):
if self.endnode:
suspect_ip = getSrcIp(self.ip_packet)
else:
suspect_ip = getDstIp(self.ip_packet)
exist = False
for i in range(len( given_list)):
if given_list[i].getName() == suspect_ip:
exist = True
given_list[i].addPort(port)
threatvalue = given_list[i].calculateThreat_ratio()
if not exist:
new = SuspectHost(suspect_ip)
given_list.append(new)
new.addPort(port);
threatvalue = new.calculateThreat_ratio()
self.update_lists()
self.checkThreat(suspect_ip, threatvalue,given_list)
def update_lists(self):
for i in range(len(self.my_listtcp)):
if (time.time() - self.my_listtcp[i].getLastPacketDate()) > 300:
#if the last packet of the host is older than 5 minutes
del my_listtcp[i]
for i in range(len(self.my_listudp)):
if (time.time() - self.my_listudp[i].getLastPacketDate()) > 300:
#if the last packet of the host is older than 5 minutes
del my_listudp[i]
def checkThreat(self,ip,threat,given_list):
alert = False
if threat >= self.sensibility: # If the threat calculated with all ports and their ponderation > sensibility
for i in range(len(given_list)):
if given_list[i].getName() == ip:
if (len(given_list[i].getPorts())) > 10: # Updated to 10 (old was 3 and too much alert)
if self.endnode:
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:%s is scanning with a threat of:%s and as scanned the following ports:" % (ip,threat)
else:
print datetime.now().strftime("%b %d, %H:%M:%S")," IP:%s is being scanned with a threat of:%s and the following ports are scanned" % (ip,threat)
print given_list[i].getPorts(),"\n"
del given_list[i]
break
|
10014500-myids
|
trunk/PortScan.py
|
Python
|
gpl3
| 5,937
|
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; minimum-scale=1.0; user-scalable=0" />
<meta content="text/html; charset=utf-8" http-equiv="Content-type">
<meta content="IE=8" http-equiv="X-UA-Compatible">
<meta content=
"Google I/O 2011 brings together thousands of developers for two days of deep technical content, focused on building the next generation of web, mobile, and enterprise applications with Google and open web technologies such as Android, Google Chrome, Google APIs, Google Web Toolkit, App Engine, and more."
name="description">
<meta content=
"event, google, i/o, programming, android, chrome, developers, moscone, san francisco" name=
"keywords">
<meta content="Google" name="author">
<title>
Google I/O 2011
</title>
<link href="map.css" media="all" rel="stylesheet">
<style type="text/css">
html, body, #map-canvas {
margin: 0;
padding: 0;
height: 100%;
}
#level-select {
height: 22px;
}
</style>
<script src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
window['ioEmbed'] = true;
</script>
<script src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/maplabel/src/maplabel-compiled.js"></script>
<script src="floor.js"></script>
<script src="levelcontrol.js"></script>
<script src="smartmarker.js"></script>
<script src="map.js"></script>
<script src="http://www.google.com/js/gweb/analytics/autotrack.js"></script>
<script>
new gweb.analytics.AutoTrack({
profile: 'UA-20834900-1'
});
</script>
</head>
<body>
<div id="map-canvas"></div>
</div>
</body>
</html>
|
1162584980-google-io
|
map/embed.html
|
HTML
|
asf20
| 1,825
|
/**
* Creates a new Floor.
* @constructor
* @param {google.maps.Map=} opt_map
*/
function Floor(opt_map) {
/**
* @type Array.<google.maps.MVCObject>
*/
this.overlays_ = [];
/**
* @type boolean
*/
this.shown_ = true;
if (opt_map) {
this.setMap(opt_map);
}
}
/**
* @param {google.maps.Map} map
*/
Floor.prototype.setMap = function(map) {
this.map_ = map;
};
/**
* @param {google.maps.MVCObject} overlay For example, a Marker or MapLabel.
* Requires a setMap method.
*/
Floor.prototype.addOverlay = function(overlay) {
if (!overlay) return;
this.overlays_.push(overlay);
overlay.setMap(this.shown_ ? this.map_ : null);
};
/**
* Sets the map on all the overlays
* @param {google.maps.Map} map The map to set.
*/
Floor.prototype.setMapAll_ = function(map) {
this.shown_ = !!map;
for (var i = 0, overlay; overlay = this.overlays_[i]; i++) {
overlay.setMap(map);
}
};
/**
* Hides the floor and all associated overlays.
*/
Floor.prototype.hide = function() {
this.setMapAll_(null);
};
/**
* Shows the floor and all associated overlays.
*/
Floor.prototype.show = function() {
this.setMapAll_(this.map_);
};
|
1162584980-google-io
|
map/floor.js
|
JavaScript
|
asf20
| 1,176
|
/**
* Creates a new level control.
* @constructor
* @param {IoMap} iomap the IO map controller.
* @param {Array.<string>} levels the levels to create switchers for.
*/
function LevelControl(iomap, levels) {
var that = this;
this.iomap_ = iomap;
this.el_ = this.initDom_(levels);
google.maps.event.addListener(iomap, 'level_changed', function() {
that.changeLevel_(iomap.get('level'));
});
}
/**
* Gets the DOM element for the control.
* @return {Element}
*/
LevelControl.prototype.getElement = function() {
return this.el_;
};
/**
* Creates the necessary DOM for the control.
* @return {Element}
*/
LevelControl.prototype.initDom_ = function(levelDefinition) {
var controlDiv = document.createElement('DIV');
controlDiv.setAttribute('id', 'levels-wrapper');
var levels = document.createElement('DIV');
levels.setAttribute('id', 'levels');
controlDiv.appendChild(levels);
var levelSelect = this.levelSelect_ = document.createElement('DIV');
levelSelect.setAttribute('id', 'level-select');
levels.appendChild(levelSelect);
this.levelDivs_ = [];
var that = this;
for (var i = 0, level; level = levelDefinition[i]; i++) {
var div = document.createElement('DIV');
div.innerHTML = 'Level ' + level;
div.setAttribute('id', 'level-' + level);
div.className = 'level';
levels.appendChild(div);
this.levelDivs_.push(div);
google.maps.event.addDomListener(div, 'click', function(e) {
var id = e.currentTarget.getAttribute('id');
var level = parseInt(id.replace('level-', ''), 10);
that.iomap_.setHash('level' + level);
});
}
controlDiv.index = 1;
return controlDiv;
};
/**
* Changes the highlighted level in the control.
* @param {number} level the level number to select.
*/
LevelControl.prototype.changeLevel_ = function(level) {
if (this.currentLevelDiv_) {
this.currentLevelDiv_.className =
this.currentLevelDiv_.className.replace(' level-selected', '');
}
var h = 25;
if (window['ioEmbed']) {
h = (window.screen.availWidth > 600) ? 34 : 24;
}
this.levelSelect_.style.top = 9 + ((level - 1) * h) + 'px';
var div = this.levelDivs_[level - 1];
div.className += ' level-selected';
this.currentLevelDiv_ = div;
};
|
1162584980-google-io
|
map/levelcontrol.js
|
JavaScript
|
asf20
| 2,264
|
/**
* @license
*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview SmartMarker.
*
* @author Chris Broadfoot (cbro@google.com)
*/
/**
* A google.maps.Marker that has some smarts about the zoom levels it should be
* shown.
*
* Options are the same as google.maps.Marker, with the addition of minZoom and
* maxZoom. These zoom levels are inclusive. That is, a SmartMarker with
* a minZoom and maxZoom of 13 will only be shown at zoom level 13.
* @constructor
* @extends google.maps.Marker
* @param {Object=} opts Same as MarkerOptions, plus minZoom and maxZoom.
*/
function SmartMarker(opts) {
var marker = new google.maps.Marker;
// default min/max Zoom - shows the marker all the time.
marker.setValues({
'minZoom': 0,
'maxZoom': Infinity
});
// the current listener (if any), triggered on map zoom_changed
var mapZoomListener;
google.maps.event.addListener(marker, 'map_changed', function() {
if (mapZoomListener) {
google.maps.event.removeListener(mapZoomListener);
}
var map = marker.getMap();
if (map) {
var listener = SmartMarker.newZoomListener_(marker);
mapZoomListener = google.maps.event.addListener(map, 'zoom_changed',
listener);
// Call the listener straight away. The map may already be initialized,
// so it will take user input for zoom_changed to be fired.
listener();
}
});
marker.setValues(opts);
return marker;
}
window['SmartMarker'] = SmartMarker;
/**
* Creates a new listener to be triggered on 'zoom_changed' event.
* Hides and shows the target Marker based on the map's zoom level.
* @param {google.maps.Marker} marker The target marker.
* @return Function
*/
SmartMarker.newZoomListener_ = function(marker) {
var map = marker.getMap();
return function() {
var zoom = map.getZoom();
var minZoom = Number(marker.get('minZoom'));
var maxZoom = Number(marker.get('maxZoom'));
marker.setVisible(zoom >= minZoom && zoom <= maxZoom);
};
};
|
1162584980-google-io
|
map/smartmarker.js
|
JavaScript
|
asf20
| 2,564
|
#map-canvas {
height: 500px;
}
#levels-wrapper {
margin: 10px;
padding: 5px;
background: #fff;
-webkit-border-radius: 6px;
-moz-border-radius: 6px;
border-radius: 6px;
-webkit-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
-moz-box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
box-shadow: 0px 1px 3px rgba(0, 0, 0, 0.3);
}
#levels {
padding: 3px;
font-family: 'Droid Sans',Arial;
font-size: 16px;
color: #205aaf;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
background: #FFFFFF;
background: -moz-linear-gradient(top, #E8E8E8 0%, #FFFFFF 100%);
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#E8E8E8), color-stop(100%,#FFFFFF));
-webkit-box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
-moz-box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
box-shadow: inset 0px 0px 2px rgba(0, 0, 0, 0.5);
}
.level {
position: relative;
z-index: 100;
padding: 3px 5px;
cursor: pointer;
}
#level-select {
position: absolute;
top: 9px;
left: 10px;
right: 10px;
height: 24px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
border-radius: 3px;
z-index: 1;
background: #1C72D0; /* old browsers */
background: -moz-linear-gradient(top, #1C72D0 0%, #015CB9 100%); /* firefox */
background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1C72D0), color-stop(100%,#015CB9)); /* webkit */
}
@media only screen and (min-device-width:600px) {
#level-select {
height: 32px !important;
}
.level {
font-size: 24px;
}
}
.level-selected {
color: #fff;
}
.level-selected, #level-select {
-webkit-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-moz-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-o-transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
transition: all 500ms cubic-bezier(0.645, 0.045, 0.355, 1.000);
-webkit-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
-moz-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
-o-transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.645, 0.045, 0.355, 1.000);
}
.infowindow {
max-width: 330px;
}
.infowindow h3 {
margin: 0 0 4px 0;
padding: 0;
font-size: 13px;
color: #000;
font-family: 'Droid Sans', arial, helvetica;
text-align: left;
}
.session, .sandbox {
padding: 2px 0;
clear: both;
font-size: 13px;
font-family: 'Droid Sans', arial, helvetica;
}
.session-time {
float: left;
width: 8.1em;
color: #999;
}
.session-title, .session-products {
margin-left: 8.5em;
}
|
1162584980-google-io
|
map/map.css
|
CSS
|
asf20
| 2,657
|
// Copyright 2011 Google
/**
* 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.
*/
/**
* The Google IO Map
* @constructor
*/
var IoMap = function() {
var moscone = new google.maps.LatLng(37.78313383211993, -122.40394949913025);
/** @type {Node} */
this.mapDiv_ = document.getElementById(this.MAP_ID);
var ioStyle = [
{
'featureType': 'road',
stylers: [
{ hue: '#00aaff' },
{ gamma: 1.67 },
{ saturation: -24 },
{ lightness: -38 }
]
},{
'featureType': 'road',
'elementType': 'labels',
stylers: [
{ invert_lightness: true }
]
}];
/** @type {boolean} */
this.ready_ = false;
/** @type {google.maps.Map} */
this.map_ = new google.maps.Map(this.mapDiv_, {
zoom: 18,
center: moscone,
navigationControl: true,
mapTypeControl: false,
scaleControl: true,
mapTypeId: 'io',
streetViewControl: false
});
var style = /** @type {*} */(new google.maps.StyledMapType(ioStyle));
this.map_.mapTypes.set('io', /** @type {google.maps.MapType} */(style));
google.maps.event.addListenerOnce(this.map_, 'tilesloaded', function() {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['onMapReady']();
}
});
/** @type {Array.<Floor>} */
this.floors_ = [];
for (var i = 0; i < this.LEVELS_.length; i++) {
this.floors_.push(new Floor(this.map_));
}
this.addLevelControl_();
this.addMapOverlay_();
this.loadMapContent_();
this.initLocationHashWatcher_();
if (!document.location.hash) {
this.showLevel(1, true);
}
}
IoMap.prototype = new google.maps.MVCObject;
/**
* The id of the Element to add the map to.
*
* @type {string}
* @const
*/
IoMap.prototype.MAP_ID = 'map-canvas';
/**
* The levels of the Moscone Center.
*
* @type {Array.<string>}
* @private
*/
IoMap.prototype.LEVELS_ = ['1', '2', '3'];
/**
* Location where the tiles are hosted.
*
* @type {string}
* @private
*/
IoMap.prototype.BASE_TILE_URL_ =
'http://www.gstatic.com/io2010maps/tiles/5/';
/**
* The minimum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MIN_ZOOM_ = 16;
/**
* The maximum zoom level to show the overlay.
*
* @type {number}
* @private
*/
IoMap.prototype.MAX_ZOOM_ = 20;
/**
* The template for loading tiles. Replace {L} with the level, {Z} with the
* zoom level, {X} and {Y} with respective tile coordinates.
*
* @type {string}
* @private
*/
IoMap.prototype.TILE_TEMPLATE_URL_ = IoMap.prototype.BASE_TILE_URL_ +
'L{L}_{Z}_{X}_{Y}.png';
/**
* @type {string}
* @private
*/
IoMap.prototype.SIMPLE_TILE_TEMPLATE_URL_ =
IoMap.prototype.BASE_TILE_URL_ + '{Z}_{X}_{Y}.png';
/**
* The extent of the overlay at certain zoom levels.
*
* @type {Object.<string, Array.<Array.<number>>>}
* @private
*/
IoMap.prototype.RESOLUTION_BOUNDS_ = {
16: [[10484, 10485], [25328, 25329]],
17: [[20969, 20970], [50657, 50658]],
18: [[41939, 41940], [101315, 101317]],
19: [[83878, 83881], [202631, 202634]],
20: [[167757, 167763], [405263, 405269]]
};
/**
* The previous hash to compare against.
*
* @type {string?}
* @private
*/
IoMap.prototype.prevHash_ = null;
/**
* Initialise the location hash watcher.
*
* @private
*/
IoMap.prototype.initLocationHashWatcher_ = function() {
var that = this;
if ('onhashchange' in window) {
window.addEventListener('hashchange', function() {
that.parseHash_();
}, true);
} else {
var that = this
window.setInterval(function() {
that.parseHash_();
}, 100);
}
this.parseHash_();
};
/**
* Called from Android.
*
* @param {Number} x A percentage to pan left by.
*/
IoMap.prototype.panLeft = function(x) {
var div = this.map_.getDiv();
var left = div.clientWidth * x;
this.map_.panBy(left, 0);
};
IoMap.prototype['panLeft'] = IoMap.prototype.panLeft;
/**
* Adds the level switcher to the top left of the map.
*
* @private
*/
IoMap.prototype.addLevelControl_ = function() {
var control = new LevelControl(this, this.LEVELS_).getElement();
this.map_.controls[google.maps.ControlPosition.TOP_LEFT].push(control);
};
/**
* Shows a floor based on the content of location.hash.
*
* @private
*/
IoMap.prototype.parseHash_ = function() {
var hash = document.location.hash;
if (hash == this.prevHash_) {
return;
}
this.prevHash_ = hash;
var level = 1;
if (hash) {
var match = hash.match(/level(\d)(?:\:([\w-]+))?/);
if (match && match[1]) {
level = parseInt(match[1], 10);
}
}
this.showLevel(level, true);
};
/**
* Updates location.hash based on the currently shown floor.
*
* @param {string?} opt_hash
*/
IoMap.prototype.setHash = function(opt_hash) {
var hash = document.location.hash.substring(1);
if (hash == opt_hash) {
return;
}
if (opt_hash) {
document.location.hash = opt_hash;
} else {
document.location.hash = 'level' + this.get('level');
}
};
IoMap.prototype['setHash'] = IoMap.prototype.setHash;
/**
* Called from spreadsheets.
*/
IoMap.prototype.loadSandboxCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.companyName = entry['gsx$companyname']['$t'];
item.companyUrl = entry['gsx$companyurl']['$t'];
var p = entry['gsx$companypod']['$t'];
item.pod = p;
p = p.toLowerCase().replace(/\s+/, '');
item.sessionRoom = p;
contentItems.push(item);
};
this.sandboxItems_ = contentItems;
this.ready_ = true;
this.addMapContent_();
};
/**
* Called from spreadsheets.
*
* @param {Object} json The json feed from the spreadsheet.
*/
IoMap.prototype.loadSessionsCallback = function(json) {
var updated = json['feed']['updated']['$t'];
var contentItems = [];
var ids = {};
var entries = json['feed']['entry'];
for (var i = 0, entry; entry = entries[i]; i++) {
var item = {};
item.sessionDate = entry['gsx$sessiondate']['$t'];
item.sessionAbstract = entry['gsx$sessionabstract']['$t'];
item.sessionHashtag = entry['gsx$sessionhashtag']['$t'];
item.sessionLevel = entry['gsx$sessionlevel']['$t'];
item.sessionTitle = entry['gsx$sessiontitle']['$t'];
item.sessionTrack = entry['gsx$sessiontrack']['$t'];
item.sessionUrl = entry['gsx$sessionurl']['$t'];
item.sessionYoutubeUrl = entry['gsx$sessionyoutubeurl']['$t'];
item.sessionTime = entry['gsx$sessiontime']['$t'];
item.sessionRoom = entry['gsx$sessionroom']['$t'];
item.sessionTags = entry['gsx$sessiontags']['$t'];
item.sessionSpeakers = entry['gsx$sessionspeakers']['$t'];
if (item.sessionDate.indexOf('10') != -1) {
item.sessionDay = 10;
} else {
item.sessionDay = 11;
}
var timeParts = item.sessionTime.split('-');
item.sessionStart = this.convertTo24Hour_(timeParts[0]);
item.sessionEnd = this.convertTo24Hour_(timeParts[1]);
contentItems.push(item);
}
this.sessionItems_ = contentItems;
};
/**
* Converts the time in the spread sheet to 24 hour time.
*
* @param {string} time The time like 10:42am.
*/
IoMap.prototype.convertTo24Hour_ = function(time) {
var pm = time.indexOf('pm') != -1;
time = time.replace(/[am|pm]/ig, '');
if (pm) {
var bits = time.split(':');
var hr = parseInt(bits[0], 10);
if (hr < 12) {
time = (hr + 12) + ':' + bits[1];
}
}
return time;
};
/**
* Loads the map content from Google Spreadsheets.
*
* @private
*/
IoMap.prototype.loadMapContent_ = function() {
// Initiate a JSONP request.
var that = this;
// Add a exposed call back function
window['loadSessionsCallback'] = function(json) {
that.loadSessionsCallback(json);
}
// Add a exposed call back function
window['loadSandboxCallback'] = function(json) {
that.loadSandboxCallback(json);
}
var key = 'tmaLiaNqIWYYtuuhmIyG0uQ';
var worksheetIDs = {
sessions: 'od6',
sandbox: 'od4'
};
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sessions + '/public/values' +
'?alt=json-in-script&callback=loadSessionsCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
var jsonpUrl = 'http://spreadsheets.google.com/feeds/list/' +
key + '/' + worksheetIDs.sandbox + '/public/values' +
'?alt=json-in-script&callback=loadSandboxCallback';
var script = document.createElement('script');
script.setAttribute('src', jsonpUrl);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
/**
* Called from Android.
*
* @param {string} roomId The id of the room to load.
*/
IoMap.prototype.showLocationById = function(roomId) {
var locations = this.LOCATIONS_;
for (var level in locations) {
var levelId = level.replace('LEVEL', '');
for (var loc in locations[level]) {
var room = locations[level][loc];
if (loc == roomId) {
var pos = new google.maps.LatLng(room.lat, room.lng);
this.map_.panTo(pos);
this.map_.setZoom(19);
this.showLevel(levelId);
if (room.marker_) {
room.marker_.setAnimation(google.maps.Animation.BOUNCE);
// Disable the animation after 5 seconds.
window.setTimeout(function() {
room.marker_.setAnimation();
}, 5000);
}
return;
}
}
}
};
IoMap.prototype['showLocationById'] = IoMap.prototype.showLocationById;
/**
* Called when the level is changed. Hides and shows floors.
*/
IoMap.prototype['level_changed'] = function() {
var level = this.get('level');
if (this.infoWindow_) {
this.infoWindow_.setMap(null);
}
for (var i = 1, floor; floor = this.floors_[i - 1]; i++) {
if (i == level) {
floor.show();
} else {
floor.hide();
}
}
this.setHash('level' + level);
};
/**
* Shows a particular floor.
*
* @param {string} level The level to show.
* @param {boolean=} opt_force if true, changes the floor even if it's already
* the current floor.
*/
IoMap.prototype.showLevel = function(level, opt_force) {
if (!opt_force && level == this.get('level')) {
return;
}
this.set('level', level);
};
IoMap.prototype['showLevel'] = IoMap.prototype.showLevel;
/**
* Create a marker with the content item's correct icon.
*
* @param {Object} item The content item for the marker.
* @return {google.maps.Marker} The new marker.
* @private
*/
IoMap.prototype.createContentMarker_ = function(item) {
if (!item.icon) {
item.icon = 'generic';
}
var image;
var shadow;
switch(item.icon) {
case 'generic':
case 'info':
case 'media':
var image = new google.maps.MarkerImage(
'marker-' + item.icon + '.png',
new google.maps.Size(30, 28),
new google.maps.Point(0, 0),
new google.maps.Point(13, 26));
var shadow = new google.maps.MarkerImage(
'marker-shadow.png',
new google.maps.Size(30, 28),
new google.maps.Point(0,0),
new google.maps.Point(13, 26));
break;
case 'toilets':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(35, 35),
new google.maps.Point(0, 0),
new google.maps.Point(17, 17));
break;
case 'elevator':
var image = new google.maps.MarkerImage(
item.icon + '.png',
new google.maps.Size(48, 26),
new google.maps.Point(0, 0),
new google.maps.Point(24, 13));
break;
}
var inactive = item.type == 'inactive';
var latLng = new google.maps.LatLng(item.lat, item.lng);
var marker = new SmartMarker({
position: latLng,
shadow: shadow,
icon: image,
title: item.title,
minZoom: inactive ? 19 : 18,
clickable: !inactive
});
marker['type_'] = item.type;
if (!inactive) {
var that = this;
google.maps.event.addListener(marker, 'click', function() {
that.openContentInfo_(item);
});
}
return marker;
};
/**
* Create a label with the content item's title atribute, if it exists.
*
* @param {Object} item The content item for the marker.
* @return {MapLabel?} The new label.
* @private
*/
IoMap.prototype.createContentLabel_ = function(item) {
if (!item.title || item.suppressLabel) {
return null;
}
var latLng = new google.maps.LatLng(item.lat, item.lng);
return new MapLabel({
'text': item.title,
'position': latLng,
'minZoom': item.labelMinZoom || 18,
'align': item.labelAlign || 'center',
'fontColor': item.labelColor,
'fontSize': item.labelSize || 12
});
}
/**
* Open a info window a content item.
*
* @param {Object} item A content item with content and a marker.
*/
IoMap.prototype.openContentInfo_ = function(item) {
if (window['MAP_CONTAINER'] !== undefined) {
window['MAP_CONTAINER']['openContentInfo'](item.room);
return;
}
var sessionBase = 'http://www.google.com/events/io/2011/sessions.html';
var now = new Date();
var may11 = new Date('May 11, 2011');
var day = now < may11 ? 10 : 11;
var type = item.type;
var id = item.id;
var title = item.title;
var content = ['<div class="infowindow">'];
var sessions = [];
var empty = true;
if (item.type == 'session') {
if (day == 10) {
content.push('<h3>' + title + ' - Tuesday May 10</h3>');
} else {
content.push('<h3>' + title + ' - Wednesday May 11</h3>');
}
for (var i = 0, session; session = this.sessionItems_[i]; i++) {
if (session.sessionRoom == item.room && session.sessionDay == day) {
sessions.push(session);
empty = false;
}
}
sessions.sort(this.sortSessions_);
for (var i = 0, session; session = sessions[i]; i++) {
content.push('<div class="session"><div class="session-time">' +
session.sessionTime + '</div><div class="session-title"><a href="' +
session.sessionUrl + '">' +
session.sessionTitle + '</a></div></div>');
}
}
if (item.type == 'sandbox') {
var sandboxName;
for (var i = 0, sandbox; sandbox = this.sandboxItems_[i]; i++) {
if (sandbox.sessionRoom == item.room) {
if (!sandboxName) {
sandboxName = sandbox.pod;
content.push('<h3>' + sandbox.pod + '</h3>');
content.push('<div class="sandbox">');
}
content.push('<div class="sandbox-items"><a href="http://' +
sandbox.companyUrl + '">' + sandbox.companyName + '</a></div>');
empty = false;
}
}
content.push('</div>');
empty = false;
}
if (empty) {
return;
}
content.push('</div>');
var pos = new google.maps.LatLng(item.lat, item.lng);
if (!this.infoWindow_) {
this.infoWindow_ = new google.maps.InfoWindow();
}
this.infoWindow_.setContent(content.join(''));
this.infoWindow_.setPosition(pos);
this.infoWindow_.open(this.map_);
};
/**
* A custom sort function to sort the sessions by start time.
*
* @param {string} a SessionA<enter description here>.
* @param {string} b SessionB.
* @return {boolean} True if sessionA is after sessionB.
*/
IoMap.prototype.sortSessions_ = function(a, b) {
var aStart = parseInt(a.sessionStart.replace(':', ''), 10);
var bStart = parseInt(b.sessionStart.replace(':', ''), 10);
return aStart > bStart;
};
/**
* Adds all overlays (markers, labels) to the map.
*/
IoMap.prototype.addMapContent_ = function() {
if (!this.ready_) {
return;
}
for (var i = 0, level; level = this.LEVELS_[i]; i++) {
var floor = this.floors_[i];
var locations = this.LOCATIONS_['LEVEL' + level];
for (var roomId in locations) {
var room = locations[roomId];
if (room.room == undefined) {
room.room = roomId;
}
if (room.type != 'label') {
var marker = this.createContentMarker_(room);
floor.addOverlay(marker);
room.marker_ = marker;
}
var label = this.createContentLabel_(room);
floor.addOverlay(label);
}
}
};
/**
* Gets the correct tile url for the coordinates and zoom.
*
* @param {google.maps.Point} coord The coordinate of the tile.
* @param {Number} zoom The current zoom level.
* @return {string} The url to the tile.
*/
IoMap.prototype.getTileUrl = function(coord, zoom) {
// Ensure that the requested resolution exists for this tile layer.
if (this.MIN_ZOOM_ > zoom || zoom > this.MAX_ZOOM_) {
return '';
}
// Ensure that the requested tile x,y exists.
if ((this.RESOLUTION_BOUNDS_[zoom][0][0] > coord.x ||
coord.x > this.RESOLUTION_BOUNDS_[zoom][0][1]) ||
(this.RESOLUTION_BOUNDS_[zoom][1][0] > coord.y ||
coord.y > this.RESOLUTION_BOUNDS_[zoom][1][1])) {
return '';
}
var template = this.TILE_TEMPLATE_URL_;
if (16 <= zoom && zoom <= 17) {
template = this.SIMPLE_TILE_TEMPLATE_URL_;
}
return template
.replace('{L}', /** @type string */(this.get('level')))
.replace('{Z}', /** @type string */(zoom))
.replace('{X}', /** @type string */(coord.x))
.replace('{Y}', /** @type string */(coord.y));
};
/**
* Add the floor overlay to the map.
*
* @private
*/
IoMap.prototype.addMapOverlay_ = function() {
var that = this;
var overlay = new google.maps.ImageMapType({
getTileUrl: function(coord, zoom) {
return that.getTileUrl(coord, zoom);
},
tileSize: new google.maps.Size(256, 256)
});
google.maps.event.addListener(this, 'level_changed', function() {
var overlays = that.map_.overlayMapTypes;
if (overlays.length) {
overlays.removeAt(0);
}
overlays.push(overlay);
});
};
/**
* All the features of the map.
* @type {Object.<string, Object.<string, Object.<string, *>>>}
*/
IoMap.prototype.LOCATIONS_ = {
'LEVEL1': {
'northentrance': {
lat: 37.78381535905965,
lng: -122.40362226963043,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'eastentrance': {
lat: 37.78328434094279,
lng: -122.40319311618805,
title: 'Entrance',
type: 'label',
labelColor: '#006600',
labelAlign: 'left',
labelSize: 10
},
'lunchroom': {
lat: 37.783112633669575,
lng: -122.40407556295395,
title: 'Lunch Room'
},
'restroom1a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator1a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'gearpickup': {
lat: 37.78367863020862,
lng: -122.4037617444992,
title: 'Gear Pickup',
type: 'label'
},
'checkin': {
lat: 37.78334369645064,
lng: -122.40335404872894,
title: 'Check In',
type: 'label'
},
'escalators1': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
}
},
'LEVEL2': {
'escalators2': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left',
labelMinZoom: 19
},
'press': {
lat: 37.78316774962791,
lng: -122.40360751748085,
title: 'Press Room',
type: 'label'
},
'restroom2a': {
lat: 37.7835334217721,
lng: -122.40386635065079,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom2b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator2a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'1': {
lat: 37.78346240732338,
lng: -122.40415401756763,
icon: 'media',
title: 'Room 1',
type: 'session',
room: '1'
},
'2': {
lat: 37.78335005596647,
lng: -122.40431495010853,
icon: 'media',
title: 'Room 2',
type: 'session',
room: '2'
},
'3': {
lat: 37.783215446097124,
lng: -122.404490634799,
icon: 'media',
title: 'Room 3',
type: 'session',
room: '3'
},
'4': {
lat: 37.78332461789977,
lng: -122.40381203591824,
icon: 'media',
title: 'Room 4',
type: 'session',
room: '4'
},
'5': {
lat: 37.783186828219335,
lng: -122.4039850383997,
icon: 'media',
title: 'Room 5',
type: 'session',
room: '5'
},
'6': {
lat: 37.783013000871364,
lng: -122.40420497953892,
icon: 'media',
title: 'Room 6',
type: 'session',
room: '6'
},
'7': {
lat: 37.7828783903882,
lng: -122.40438133478165,
icon: 'media',
title: 'Room 7',
type: 'session',
room: '7'
},
'8': {
lat: 37.78305009820564,
lng: -122.40378588438034,
icon: 'media',
title: 'Room 8',
type: 'session',
room: '8'
},
'9': {
lat: 37.78286673120095,
lng: -122.40402393043041,
icon: 'media',
title: 'Room 9',
type: 'session',
room: '9'
},
'10': {
lat: 37.782719401312626,
lng: -122.40420028567314,
icon: 'media',
title: 'Room 10',
type: 'session',
room: '10'
},
'appengine': {
lat: 37.783362774996625,
lng: -122.40335941314697,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'App Engine'
},
'chrome': {
lat: 37.783730566003555,
lng: -122.40378990769386,
type: 'sandbox',
icon: 'generic',
title: 'Chrome'
},
'googleapps': {
lat: 37.783303419504094,
lng: -122.40320384502411,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Apps'
},
'geo': {
lat: 37.783365954753805,
lng: -122.40314483642578,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
title: 'Geo'
},
'accessibility': {
lat: 37.783414711013485,
lng: -122.40342646837234,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Accessibility'
},
'developertools': {
lat: 37.783457107734876,
lng: -122.40347877144814,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Dev Tools'
},
'commerce': {
lat: 37.78349102509448,
lng: -122.40351900458336,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'Commerce'
},
'youtube': {
lat: 37.783537661438515,
lng: -122.40358605980873,
type: 'sandbox',
icon: 'generic',
labelMinZoom: 19,
labelAlign: 'right',
title: 'YouTube'
},
'officehoursfloor2a': {
lat: 37.78249045644304,
lng: -122.40410104393959,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2': {
lat: 37.78266852473624,
lng: -122.40387573838234,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor2b': {
lat: 37.782844472747406,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
}
},
'LEVEL3': {
'escalators3': {
lat: 37.78353872135503,
lng: -122.40336209535599,
title: 'Escalators',
type: 'label',
labelAlign: 'left'
},
'restroom3a': {
lat: 37.78372420652042,
lng: -122.40396961569786,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'restroom3b': {
lat: 37.78250317562106,
lng: -122.40423113107681,
icon: 'toilets',
type: 'inactive',
title: 'Restroom',
suppressLabel: true
},
'elevator3a': {
lat: 37.783669090977035,
lng: -122.40389987826347,
icon: 'elevator',
type: 'inactive',
title: 'Elevators',
suppressLabel: true
},
'keynote': {
lat: 37.783250423488326,
lng: -122.40417748689651,
icon: 'media',
title: 'Keynote',
type: 'label'
},
'11': {
lat: 37.78283069370135,
lng: -122.40408763289452,
icon: 'media',
title: 'Room 11',
type: 'session',
room: '11'
},
'googletv': {
lat: 37.7837125474666,
lng: -122.40362092852592,
type: 'sandbox',
icon: 'generic',
title: 'Google TV'
},
'android': {
lat: 37.783530242022124,
lng: -122.40358874201775,
type: 'sandbox',
icon: 'generic',
title: 'Android'
},
'officehoursfloor3': {
lat: 37.782843412820846,
lng: -122.40365579724312,
title: 'Office Hours',
type: 'label'
},
'officehoursfloor3a': {
lat: 37.78267170452323,
lng: -122.40387842059135,
title: 'Office Hours',
type: 'label'
}
}
};
google.maps.event.addDomListener(window, 'load', function() {
window['IoMap'] = new IoMap();
});
|
1162584980-google-io
|
map/map.js
|
JavaScript
|
asf20
| 26,216
|
<html><head><style> body { font-family: sans-serif; } pre { background-color: #eeeeee; padding: 1em; white-space: pre-wrap; } </style></head><body>
<h3>Notices for files:</h3><ul>
<li>AbstractImmutableTableTest.java</li>
<li>AtomicInteger.java</li>
<li>ConcurrentHashMap.java</li>
<li>ConcurrentMap.java</li>
<li>CustomSerializerTest.java</li>
<li>CustomSerializerTest.java.svn-base</li>
<li>EmptyImmutableTable.java</li>
<li>EmptyImmutableTableTest.java</li>
<li>FieldAttributes.java</li>
<li>FieldAttributes.java.svn-base</li>
<li>FieldAttributesTest.java</li>
<li>FieldAttributesTest.java.svn-base</li>
<li>GwtPlatform.java</li>
<li>ImmutableTable.java</li>
<li>ImmutableTableTest.java</li>
<li>InheritanceTest.java</li>
<li>InheritanceTest.java.svn-base</li>
<li>InstanceCreatorTest.java</li>
<li>InstanceCreatorTest.java.svn-base</li>
<li>JsonParser.java</li>
<li>JsonParser.java.svn-base</li>
<li>JsonParserTest.java</li>
<li>JsonParserTest.java.svn-base</li>
<li>JsonStreamParser.java</li>
<li>JsonStreamParser.java.svn-base</li>
<li>JsonStreamParserTest.java</li>
<li>JsonStreamParserTest.java.svn-base</li>
<li>LongSerializationPolicy.java</li>
<li>LongSerializationPolicy.java.svn-base</li>
<li>LongSerializationPolicyTest.java</li>
<li>LongSerializationPolicyTest.java.svn-base</li>
<li>MinimalCollectionTest.java</li>
<li>MinimalIterableTest.java</li>
<li>MinimalSetTest.java</li>
<li>OpenJdk6ListTests.java</li>
<li>OpenJdk6MapTests.java</li>
<li>OpenJdk6QueueTests.java</li>
<li>OpenJdk6SetTests.java</li>
<li>OpenJdk6Tests.java</li>
<li>RegularImmutableTable.java</li>
<li>RegularImmutableTableTest.java</li>
<li>SingletonImmutableTable.java</li>
<li>SingletonImmutableTableTest.java</li>
<li>guava</li>
</ul>
<pre>/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
</pre>
<h3>Notices for files:</h3><ul>
<li>NavUtils.java</li>
<li>NotificationCompat.java</li>
<li>NotificationCompatHoneycomb.java</li>
<li>TaskStackBuilder.java</li>
<li>TaskStackBuilderHoneycomb.java</li>
</ul>
<pre>/*
* Copyright (C) 2012 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractBiMap.java</li>
<li>AbstractCheckedFutureTest.java</li>
<li>AbstractCollectionTest.java</li>
<li>AbstractCollectionTester.java</li>
<li>AbstractConcurrentHashMultisetTest.java</li>
<li>AbstractFuture.java</li>
<li>AbstractIterator.java</li>
<li>AbstractIteratorTest.java</li>
<li>AbstractListIndexOfTester.java</li>
<li>AbstractListMultimap.java</li>
<li>AbstractListMultimapTest.java</li>
<li>AbstractListenableFutureTest.java</li>
<li>AbstractMapBasedMultiset.java</li>
<li>AbstractMapEntry.java</li>
<li>AbstractMapEntryTest.java</li>
<li>AbstractMapTester.java</li>
<li>AbstractMultimap.java</li>
<li>AbstractMultimapTest.java</li>
<li>AbstractMultiset.java</li>
<li>AbstractMultisetTest.java</li>
<li>AbstractSetMultimap.java</li>
<li>AbstractSetMultimapTest.java</li>
<li>AbstractSetTester.java</li>
<li>AbstractSortedSetMultimap.java</li>
<li>AllowConcurrentEvents.java</li>
<li>AnEnum.java</li>
<li>AnnotatedHandlerFinder.java</li>
<li>AppendableWriterTest.java</li>
<li>ArrayListMultimap.java</li>
<li>ArrayListMultimapTest.java</li>
<li>AsyncEventBus.java</li>
<li>AsyncEventBusTest.java</li>
<li>BiMap.java</li>
<li>ByFunctionOrdering.java</li>
<li>ByteStreams.java</li>
<li>ByteStreamsTest.java</li>
<li>CharStreams.java</li>
<li>CharStreamsTest.java</li>
<li>Charsets.java</li>
<li>CharsetsTest.java</li>
<li>CheckCloseSupplier.java</li>
<li>ClassToInstanceMap.java</li>
<li>Closeables.java</li>
<li>CloseablesTest.java</li>
<li>CollectionAddAllTester.java</li>
<li>CollectionAddTester.java</li>
<li>CollectionContainsAllTester.java</li>
<li>CollectionContainsTester.java</li>
<li>CollectionEqualsTester.java</li>
<li>CollectionIsEmptyTester.java</li>
<li>CollectionSizeTester.java</li>
<li>CollectionToArrayTester.java</li>
<li>CollectionToStringTester.java</li>
<li>ComparatorOrdering.java</li>
<li>CompoundOrdering.java</li>
<li>ConcurrentHashMultiset.java</li>
<li>ConcurrentHashMultisetTest.java</li>
<li>ConcurrentHashMultisetWithChmTest.java</li>
<li>ConstrainedMapImplementsMapTest.java</li>
<li>ConstrainedMultimapAsMapImplementsMapTest.java</li>
<li>ConstrainedSetMultimapTest.java</li>
<li>Constraint.java</li>
<li>Constraints.java</li>
<li>ConstraintsTest.java</li>
<li>CountingInputStream.java</li>
<li>CountingOutputStream.java</li>
<li>CountingOutputStreamTest.java</li>
<li>DeadEvent.java</li>
<li>Defaults.java</li>
<li>DefaultsTest.java</li>
<li>EmptyImmutableList.java</li>
<li>EmptyImmutableSet.java</li>
<li>EnumBiMap.java</li>
<li>EnumBiMapTest.java</li>
<li>EnumHashBiMap.java</li>
<li>EnumHashBiMapTest.java</li>
<li>EnumMultiset.java</li>
<li>EnumMultisetTest.java</li>
<li>EqualsTester.java</li>
<li>EqualsTesterTest.java</li>
<li>EventBus.java</li>
<li>EventBusTest.java</li>
<li>EventHandler.java</li>
<li>EventHandlerTest.java</li>
<li>ExecutionList.java</li>
<li>ExecutionListTest.java</li>
<li>ExplicitOrdering.java</li>
<li>Files.java</li>
<li>FinalizablePhantomReference.java</li>
<li>FinalizableReference.java</li>
<li>FinalizableReferenceQueue.java</li>
<li>FinalizableSoftReference.java</li>
<li>FinalizableWeakReference.java</li>
<li>Flushables.java</li>
<li>ForwardingCollection.java</li>
<li>ForwardingConcurrentMap.java</li>
<li>ForwardingIterator.java</li>
<li>ForwardingList.java</li>
<li>ForwardingListIterator.java</li>
<li>ForwardingListIteratorTest.java</li>
<li>ForwardingListTest.java</li>
<li>ForwardingMap.java</li>
<li>ForwardingMapEntry.java</li>
<li>ForwardingMultimap.java</li>
<li>ForwardingMultiset.java</li>
<li>ForwardingObject.java</li>
<li>ForwardingObjectTest.java</li>
<li>ForwardingQueue.java</li>
<li>ForwardingQueueTest.java</li>
<li>ForwardingSet.java</li>
<li>ForwardingSetTest.java</li>
<li>ForwardingSortedMap.java</li>
<li>ForwardingSortedMapImplementsMapTest.java</li>
<li>ForwardingSortedMapTest.java</li>
<li>ForwardingSortedSet.java</li>
<li>ForwardingTestCase.java</li>
<li>Function.java</li>
<li>Functions.java</li>
<li>HandlerFindingStrategy.java</li>
<li>HashBiMap.java</li>
<li>HashBiMapTest.java</li>
<li>HashMultimap.java</li>
<li>HashMultimapTest.java</li>
<li>HashMultiset.java</li>
<li>HashMultisetTest.java</li>
<li>ImmutableList.java</li>
<li>ImmutableListTest.java</li>
<li>ImmutableSet.java</li>
<li>ImmutableSetTest.java</li>
<li>InputSupplier.java</li>
<li>Interner.java</li>
<li>Interners.java</li>
<li>InternersTest.java</li>
<li>IoTestCase.java</li>
<li>Iterables.java</li>
<li>IterablesTest.java</li>
<li>IteratorTester.java</li>
<li>Iterators.java</li>
<li>IteratorsTest.java</li>
<li>LexicographicalOrdering.java</li>
<li>LimitInputStream.java</li>
<li>LimitInputStreamTest.java</li>
<li>LineBuffer.java</li>
<li>LineBufferTest.java</li>
<li>LineReader.java</li>
<li>LinkedHashMultimap.java</li>
<li>LinkedHashMultimapTest.java</li>
<li>LinkedHashMultiset.java</li>
<li>LinkedHashMultisetTest.java</li>
<li>LinkedListMultimap.java</li>
<li>LinkedListMultimapTest.java</li>
<li>ListAddAllTester.java</li>
<li>ListAddTester.java</li>
<li>ListIteratorTester.java</li>
<li>ListListIteratorTester.java</li>
<li>ListMultimap.java</li>
<li>ListenableFuture.java</li>
<li>Lists.java</li>
<li>ListsTest.java</li>
<li>LittleEndianDataInputStream.java</li>
<li>LittleEndianDataInputStreamTest.java</li>
<li>LittleEndianDataOutputStream.java</li>
<li>MapConstraint.java</li>
<li>MapConstraints.java</li>
<li>MapConstraintsTest.java</li>
<li>MapCreationTester.java</li>
<li>MapDifference.java</li>
<li>MapGetTester.java</li>
<li>MapIsEmptyTester.java</li>
<li>MapPutAllTester.java</li>
<li>MapPutTester.java</li>
<li>Maps.java</li>
<li>MapsTest.java</li>
<li>MinimalCollection.java</li>
<li>MoreExecutors.java</li>
<li>MultiInputStream.java</li>
<li>MultiInputStreamTest.java</li>
<li>Multimap.java</li>
<li>Multimaps.java</li>
<li>MultimapsTest.java</li>
<li>Multiset.java</li>
<li>Multisets.java</li>
<li>MultisetsImmutableEntryTest.java</li>
<li>MultisetsTest.java</li>
<li>MutableClassToInstanceMap.java</li>
<li>MutableClassToInstanceMapTest.java</li>
<li>NaturalOrdering.java</li>
<li>NullsFirstOrdering.java</li>
<li>NullsLastOrdering.java</li>
<li>ObjectArrays.java</li>
<li>ObjectArraysTest.java</li>
<li>Objects.java</li>
<li>Ordering.java</li>
<li>OrderingTest.java</li>
<li>OutputSupplier.java</li>
<li>Platform.java</li>
<li>Preconditions.java</li>
<li>Predicate.java</li>
<li>Predicates.java</li>
<li>Primitives.java</li>
<li>PrimitivesTest.java</li>
<li>RandomAmountInputStream.java</li>
<li>ReentrantEventsTest.java</li>
<li>RegularImmutableSet.java</li>
<li>Resources.java</li>
<li>ReverseNaturalOrdering.java</li>
<li>ReverseOrdering.java</li>
<li>SerializableTester.java</li>
<li>SetAddAllTester.java</li>
<li>SetAddTester.java</li>
<li>SetMultimap.java</li>
<li>Sets.java</li>
<li>SetsTest.java</li>
<li>SimpleAbstractMultisetTest.java</li>
<li>SingletonImmutableSet.java</li>
<li>SortedSetMultimap.java</li>
<li>StringCatcher.java</li>
<li>Subscribe.java</li>
<li>Supplier.java</li>
<li>Suppliers.java</li>
<li>SuppliersTest.java</li>
<li>Synchronized.java</li>
<li>SynchronizedBiMapTest.java</li>
<li>SynchronizedEventHandler.java</li>
<li>SynchronizedMapTest.java</li>
<li>SynchronizedMultimapTest.java</li>
<li>SynchronizedSetTest.java</li>
<li>TestCharacterListGenerator.java</li>
<li>TestCollectionGenerator.java</li>
<li>TestCollidingSetGenerator.java</li>
<li>TestEnumSetGenerator.java</li>
<li>TestIntegerSetGenerator.java</li>
<li>TestListGenerator.java</li>
<li>TestSetGenerator.java</li>
<li>TestStringListGenerator.java</li>
<li>TestStringSetGenerator.java</li>
<li>Throwables.java</li>
<li>ThrowablesTest.java</li>
<li>TransformedImmutableSet.java</li>
<li>TreeMultimap.java</li>
<li>TreeMultimapExplicitTest.java</li>
<li>TreeMultimapNaturalTest.java</li>
<li>TreeMultiset.java</li>
<li>TreeMultisetTest.java</li>
<li>TypeTokenTest.java</li>
<li>UnmodifiableCollectionTests.java</li>
<li>UsingToStringOrdering.java</li>
<li>WrongType.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Absent.java</li>
<li>AbstractCache.java</li>
<li>AbstractCacheTest.java</li>
<li>AbstractCompositeHashFunction.java</li>
<li>AbstractFutureTest.java</li>
<li>AbstractHasher.java</li>
<li>AbstractLoadingCache.java</li>
<li>AbstractLoadingCacheTest.java</li>
<li>AbstractNonStreamingHashFunction.java</li>
<li>AbstractNonStreamingHashFunctionTest.java</li>
<li>AbstractRangeSetTest.java</li>
<li>AbstractScheduledService.java</li>
<li>AbstractScheduledServiceTest.java</li>
<li>AbstractSortedMultiset.java</li>
<li>AbstractStreamingHashFunction.java</li>
<li>AbstractStreamingHasherTest.java</li>
<li>AsyncFunction.java</li>
<li>AtomicLongMap.java</li>
<li>AtomicLongMapTest.java</li>
<li>BigIntegerMath.java</li>
<li>BigIntegerMathTest.java</li>
<li>BloomFilter.java</li>
<li>BloomFilterStrategies.java</li>
<li>BloomFilterTest.java</li>
<li>BoundType.java</li>
<li>Cache.java</li>
<li>CacheBuilder.java</li>
<li>CacheBuilderFactory.java</li>
<li>CacheBuilderSpec.java</li>
<li>CacheBuilderSpecTest.java</li>
<li>CacheEvictionTest.java</li>
<li>CacheExpirationTest.java</li>
<li>CacheLoader.java</li>
<li>CacheLoadingTest.java</li>
<li>CacheManualTest.java</li>
<li>CacheReferencesTest.java</li>
<li>CacheRefreshTest.java</li>
<li>CacheStats.java</li>
<li>CacheStatsTest.java</li>
<li>CacheTesting.java</li>
<li>ComputingConcurrentHashMapTest.java</li>
<li>ConcurrentHashMultisetBasherTest.java</li>
<li>ContiguousSetNonGwtTest.java</li>
<li>ContiguousSetTest.java</li>
<li>Count.java</li>
<li>CountTest.java</li>
<li>DescendingImmutableSortedMultiset.java</li>
<li>DiscreteDomainsTest.java</li>
<li>DoubleMath.java</li>
<li>DoubleMathTest.java</li>
<li>DoubleUtils.java</li>
<li>DoubleUtilsTest.java</li>
<li>EmptyCachesTest.java</li>
<li>EmptyContiguousSet.java</li>
<li>EmptyImmutableSortedMultiset.java</li>
<li>Enums.java</li>
<li>EnumsTest.java</li>
<li>EquivalenceTester.java</li>
<li>EquivalenceTesterTest.java</li>
<li>ExecutionError.java</li>
<li>FilteredMultimapTest.java</li>
<li>ForwardingCache.java</li>
<li>ForwardingCheckedFuture.java</li>
<li>ForwardingCheckedFutureTest.java</li>
<li>ForwardingExecutorService.java</li>
<li>ForwardingListeningExecutorService.java</li>
<li>ForwardingLoadingCache.java</li>
<li>ForwardingNavigableMapTest.java</li>
<li>FunctionalEquivalence.java</li>
<li>Funnel.java</li>
<li>Funnels.java</li>
<li>FunnelsTest.java</li>
<li>FutureCallback.java</li>
<li>GcFinalization.java</li>
<li>GcFinalizationTest.java</li>
<li>GeneralRange.java</li>
<li>GeneralRangeTest.java</li>
<li>GwtTransient.java</li>
<li>HashCode.java</li>
<li>HashCodes.java</li>
<li>HashCodesTest.java</li>
<li>HashFunction.java</li>
<li>HashTestUtils.java</li>
<li>Hasher.java</li>
<li>Hashing.java</li>
<li>HashingTest.java</li>
<li>HostAndPort.java</li>
<li>HttpHeaders.java</li>
<li>HttpHeadersTest.java</li>
<li>ImmutableSortedMultiset.java</li>
<li>ImmutableSortedMultisetFauxverideShim.java</li>
<li>ImmutableSortedMultisetTest.java</li>
<li>IntMath.java</li>
<li>IntMathTest.java</li>
<li>InterruptionUtil.java</li>
<li>LenientSerializableTester.java</li>
<li>ListeningScheduledExecutorService.java</li>
<li>LoadingCache.java</li>
<li>LocalCacheTest.java</li>
<li>LocalLoadingCacheTest.java</li>
<li>LongMath.java</li>
<li>LongMathTest.java</li>
<li>MapMakerInternalMapTest.java</li>
<li>MapMakerTest.java</li>
<li>MapsSortedTransformValuesTest.java</li>
<li>MapsTransformValuesUnmodifiableIteratorTest.java</li>
<li>MathPreconditions.java</li>
<li>MathTesting.java</li>
<li>MediaType.java</li>
<li>MediaTypeTest.java</li>
<li>MessageDigestHashFunction.java</li>
<li>MessageDigestHashFunctionTest.java</li>
<li>MultimapsFilterEntriesAsMapTest.java</li>
<li>MultisetIteratorTester.java</li>
<li>Murmur3Hash128Test.java</li>
<li>Murmur3Hash32Test.java</li>
<li>Murmur3_128HashFunction.java</li>
<li>Murmur3_32HashFunction.java</li>
<li>NullCacheTest.java</li>
<li>Optional.java</li>
<li>OptionalTest.java</li>
<li>OutsideEventBusTest.java</li>
<li>PairwiseEquivalence.java</li>
<li>PairwiseEquivalence_CustomFieldSerializer.java</li>
<li>ParseRequest.java</li>
<li>Platform.java</li>
<li>PopulatedCachesTest.java</li>
<li>Present.java</li>
<li>PrimitiveSink.java</li>
<li>Queues.java</li>
<li>QueuesTest.java</li>
<li>RangeMap.java</li>
<li>RangeMapTest.java</li>
<li>RangesTest.java</li>
<li>RegularContiguousSet.java</li>
<li>RegularImmutableMultiset.java</li>
<li>RegularImmutableMultiset_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedMultiset.java</li>
<li>RelationshipTester.java</li>
<li>RemovalCause.java</li>
<li>RemovalListener.java</li>
<li>RemovalListeners.java</li>
<li>RemovalNotification.java</li>
<li>SortedIterable.java</li>
<li>SortedIterables.java</li>
<li>SortedIterablesTest.java</li>
<li>SortedMultiset.java</li>
<li>SortedMultisets.java</li>
<li>TablesTransformValuesTest.java</li>
<li>TestPlatform.java</li>
<li>TestingCacheLoaders.java</li>
<li>TestingRemovalListeners.java</li>
<li>TestingWeighers.java</li>
<li>Ticker.java</li>
<li>TreeRangeSet.java</li>
<li>TreeRangeSetTest.java</li>
<li>TypeParameter.java</li>
<li>TypeParameterTest.java</li>
<li>Types.java</li>
<li>TypesTest.java</li>
<li>UncheckedExecutionException.java</li>
<li>Uninterruptibles.java</li>
<li>UnsignedInteger.java</li>
<li>UnsignedIntegerTest.java</li>
<li>UnsignedInts.java</li>
<li>UnsignedIntsTest.java</li>
<li>UnsignedLong.java</li>
<li>UnsignedLongTest.java</li>
<li>UnsignedLongs.java</li>
<li>UnsignedLongsTest.java</li>
<li>Weigher.java</li>
<li>WellBehavedMap.java</li>
<li>WellBehavedMapTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2011 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__config.xml</li>
</ul>
<pre>/*
** Copyright 2009, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__dimens.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/dimens.xml
**
** Copyright 2006, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>org.eclipse.jdt.ui.prefs</li>
</ul>
<pre>/*\n * Copyright (c) 2012 Google Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except\n * in compliance with the License. You may obtain a copy of the License at\n *\n * http\://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software distributed under the License\n * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express\n * or implied. See the License for the specific language governing permissions and limitations under\n * the License.\n */</pre>
<h3>Notices for files:</h3><ul>
<li>MenuItem.java</li>
</ul>
<pre>/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAppEngineCallbackServlet.java</li>
<li>AbstractAppEngineFlowServlet.java</li>
<li>AbstractCallbackServlet.java</li>
<li>AbstractFlowUserServlet.java</li>
<li>AbstractHttpContent.java</li>
<li>AbstractHttpContentTest.java</li>
<li>AbstractInputStreamContent.java</li>
<li>AccessProtectedResourceTest.java</li>
<li>AccessTokenRequestTest.java</li>
<li>AndroidHttp.java</li>
<li>AndroidJsonFactory.java</li>
<li>AndroidJsonGenerator.java</li>
<li>AndroidJsonParser.java</li>
<li>ApacheHttpTransportTest.java</li>
<li>AppEngineServletUtils.java</li>
<li>ArrayTypeAdapter.java</li>
<li>ArrayTypeAdapter.java.svn-base</li>
<li>ArrayValueMap.java</li>
<li>AtomContent.java</li>
<li>AtomicLong.java</li>
<li>AuthorizationCodeRequestUrl.java</li>
<li>AuthorizationCodeRequestUrlTest.java</li>
<li>AuthorizationCodeResponseUrl.java</li>
<li>AuthorizationCodeResponseUrlTest.java</li>
<li>AuthorizationCodeTokenRequest.java</li>
<li>AuthorizationCodeTokenRequestTest.java</li>
<li>AuthorizationRequestUrl.java</li>
<li>AuthorizationRequestUrlTest.java</li>
<li>BackOffPolicy.java</li>
<li>BagOfPrimitives.java</li>
<li>BagOfPrimitives.java.svn-base</li>
<li>BagOfPrimitivesDeserializationBenchmark.java</li>
<li>BagOfPrimitivesDeserializationBenchmark.java.svn-base</li>
<li>BasicAuthentication.java</li>
<li>BasicAuthenticationTest.java</li>
<li>BearerToken.java</li>
<li>BrowserClientRequestUrl.java</li>
<li>BrowserClientRequestUrlTest.java</li>
<li>ByteArrayContent.java</li>
<li>ByteArrayContentTest.java</li>
<li>ByteCountingOutputStream.java</li>
<li>Callable.java</li>
<li>Cart.java</li>
<li>Cart.java.svn-base</li>
<li>ClientLoginResponseException.java</li>
<li>ClientParametersAuthentication.java</li>
<li>ClientParametersAuthenticationTest.java</li>
<li>CollectionTypeAdapterFactory.java</li>
<li>CollectionTypeAdapterFactory.java.svn-base</li>
<li>CollectionsDeserializationBenchmark.java</li>
<li>CollectionsDeserializationBenchmark.java.svn-base</li>
<li>ConstructorConstructor.java</li>
<li>ConstructorConstructor.java.svn-base</li>
<li>Credential.java</li>
<li>CredentialStoreRefreshListener.java</li>
<li>CredentialTest.java</li>
<li>Data.java</li>
<li>DataMapTest.java</li>
<li>DataTest.java</li>
<li>DateTypeAdapter.java</li>
<li>DateTypeAdapter.java.svn-base</li>
<li>DefaultInetAddressTypeAdapterTest.java</li>
<li>DefaultInetAddressTypeAdapterTest.java.svn-base</li>
<li>ExecutionException.java</li>
<li>ExponentialBackOffPolicy.java</li>
<li>ExponentialBackOffPolicyTest.java</li>
<li>ExposeAnnotationExclusionStrategyTest.java</li>
<li>ExposeAnnotationExclusionStrategyTest.java.svn-base</li>
<li>FieldNamingTest.java</li>
<li>FieldNamingTest.java.svn-base</li>
<li>FileContent.java</li>
<li>GenericJsonTest.java</li>
<li>GoogleAccessProtectedResource.java</li>
<li>GoogleAccessTokenRequest.java</li>
<li>GoogleAccessTokenRequestTest.java</li>
<li>GoogleAccountManager.java</li>
<li>GoogleAuthorizationCodeRequestUrl.java</li>
<li>GoogleAuthorizationCodeRequestUrlTest.java</li>
<li>GoogleAuthorizationCodeTokenRequest.java</li>
<li>GoogleAuthorizationCodeTokenRequestTest.java</li>
<li>GoogleAuthorizationRequestUrl.java</li>
<li>GoogleAuthorizationRequestUrlTest.java</li>
<li>GoogleBrowserClientRequestUrl.java</li>
<li>GoogleBrowserClientRequestUrlTest.java</li>
<li>GoogleClient.java</li>
<li>GoogleClientSecrets.java</li>
<li>GoogleClientTest.java</li>
<li>GoogleCredential.java</li>
<li>GoogleJsonError.java</li>
<li>GoogleJsonErrorTest.java</li>
<li>GoogleJsonResponseException.java</li>
<li>GoogleJsonResponseExceptionTest.java</li>
<li>GoogleOAuth2ThreeLeggedFlow.java</li>
<li>GoogleOAuth2ThreeLeggedFlowTest.java</li>
<li>GoogleOAuthConstants.java</li>
<li>GoogleOAuthHmacThreeLeggedFlow.java</li>
<li>GoogleRefreshTokenRequest.java</li>
<li>GraphAdapterBuilder.java</li>
<li>GraphAdapterBuilder.java.svn-base</li>
<li>GraphAdapterBuilderTest.java</li>
<li>GraphAdapterBuilderTest.java.svn-base</li>
<li>GsonFactory.java</li>
<li>GsonGenerator.java</li>
<li>GsonParser.java</li>
<li>GsonProguardExampleActivity.java</li>
<li>GsonProguardExampleActivity.java.svn-base</li>
<li>HttpRequestFactory.java</li>
<li>HttpRequestInitializer.java</li>
<li>HttpResponseExceptionTest.java</li>
<li>HttpStatusCodes.java</li>
<li>HttpTesting.java</li>
<li>InstalledApp.java</li>
<li>JdoPersistedCredential.java</li>
<li>JsonArrayTest.java</li>
<li>JsonArrayTest.java.svn-base</li>
<li>JsonElementReaderTest.java</li>
<li>JsonElementReaderTest.java.svn-base</li>
<li>JsonHttpClient.java</li>
<li>JsonHttpClientTest.java</li>
<li>JsonHttpRequest.java</li>
<li>JsonHttpRequestInitializer.java</li>
<li>JsonNullTest.java</li>
<li>JsonNullTest.java.svn-base</li>
<li>JsonReaderInternalAccess.java</li>
<li>JsonReaderInternalAccess.java.svn-base</li>
<li>JsonString.java</li>
<li>JsonTreeReader.java</li>
<li>JsonTreeReader.java.svn-base</li>
<li>JsonTreeWriter.java</li>
<li>JsonTreeWriter.java.svn-base</li>
<li>JsonTreeWriterTest.java</li>
<li>JsonTreeWriterTest.java.svn-base</li>
<li>LazilyParsedNumber.java</li>
<li>LazilyParsedNumber.java.svn-base</li>
<li>LineItem.java</li>
<li>LineItem.java.svn-base</li>
<li>LogContentTest.java</li>
<li>MapTypeAdapterFactory.java</li>
<li>MapTypeAdapterFactory.java.svn-base</li>
<li>MediaExponentialBackOffPolicy.java</li>
<li>MediaHttpUploader.java</li>
<li>MediaHttpUploaderProgressListener.java</li>
<li>MediaHttpUploaderTest.java</li>
<li>MediaUploadExponentialBackOffPolicy.java</li>
<li>MockHttpUnsuccessfulResponseHandler.java</li>
<li>MoreSpecificTypeSerializationTest.java</li>
<li>MoreSpecificTypeSerializationTest.java.svn-base</li>
<li>MultipartRelatedContent.java</li>
<li>MultipartRelatedContentTest.java</li>
<li>MultisetNavigationTester.java</li>
<li>NullValue.java</li>
<li>OAuth2Credential.java</li>
<li>OAuth2ThreeLeggedFlow.java</li>
<li>OAuthHmacCredential.java</li>
<li>OAuthHmacThreeLeggedFlow.java</li>
<li>ObjectTypeAdapter.java</li>
<li>ObjectTypeAdapter.java.svn-base</li>
<li>ObjectTypeAdapterTest.java</li>
<li>ObjectTypeAdapterTest.java.svn-base</li>
<li>ParseBenchmark.java</li>
<li>ParseBenchmark.java.svn-base</li>
<li>ProtoHttpContent.java</li>
<li>ProtoHttpContentTest.java</li>
<li>ProtoHttpParser.java</li>
<li>ProtoHttpParserTest.java</li>
<li>ProtocolBuffers.java</li>
<li>ProtocolBuffersTest.java</li>
<li>RangeSet.java</li>
<li>RawCollectionsExample.java</li>
<li>RawCollectionsExample.java.svn-base</li>
<li>ReflectiveTypeAdapterFactory.java</li>
<li>ReflectiveTypeAdapterFactory.java.svn-base</li>
<li>RefreshTokenRequest.java</li>
<li>RefreshTokenRequestTest.java</li>
<li>RuntimeTypeAdapterFactory.java</li>
<li>RuntimeTypeAdapterFactory.java.svn-base</li>
<li>RuntimeTypeAdapterFactoryTest.java</li>
<li>RuntimeTypeAdapterFactoryTest.java.svn-base</li>
<li>SerializationBenchmark.java</li>
<li>SerializationBenchmark.java.svn-base</li>
<li>SortedMultisetTestSuiteBuilder.java</li>
<li>SqlDateTypeAdapter.java</li>
<li>SqlDateTypeAdapter.java.svn-base</li>
<li>StreamingTypeAdaptersTest.java</li>
<li>StreamingTypeAdaptersTest.java.svn-base</li>
<li>StringPool.java</li>
<li>StringPool.java.svn-base</li>
<li>ThreeLeggedFlow.java</li>
<li>TimeTypeAdapter.java</li>
<li>TimeTypeAdapter.java.svn-base</li>
<li>TokenErrorResponse.java</li>
<li>TokenErrorResponseTest.java</li>
<li>TokenRequest.java</li>
<li>TokenRequestTest.java</li>
<li>TokenResponse.java</li>
<li>TokenResponseException.java</li>
<li>TokenResponseTest.java</li>
<li>TreeTypeAdapter.java</li>
<li>TreeTypeAdapter.java.svn-base</li>
<li>TreeTypeAdaptersTest.java</li>
<li>TreeTypeAdaptersTest.java.svn-base</li>
<li>TypeAdapter.java</li>
<li>TypeAdapter.java.svn-base</li>
<li>TypeAdapterFactory.java</li>
<li>TypeAdapterFactory.java.svn-base</li>
<li>TypeAdapterPrecedenceTest.java</li>
<li>TypeAdapterPrecedenceTest.java.svn-base</li>
<li>TypeAdapterRuntimeTypeWrapper.java</li>
<li>TypeAdapterRuntimeTypeWrapper.java.svn-base</li>
<li>TypeAdapters.java</li>
<li>TypeAdapters.java.svn-base</li>
<li>TypeHierarchyAdapterTest.java</li>
<li>TypeHierarchyAdapterTest.java.svn-base</li>
<li>Types.java</li>
<li>TypesTest.java</li>
<li>UnsafeAllocator.java</li>
<li>UnsafeAllocator.java.svn-base</li>
<li>UriTemplate.java</li>
<li>UriTemplateTest.java</li>
<li>UrlFetchTransportTest.java</li>
<li>Value.java</li>
<li>XmlTest.java</li>
<li>package-info.java</li>
<li>simple_proto.proto</li>
</ul>
<pre>/*
* Copyright (c) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>NullOutputStream.java</li>
</ul>
<pre>/*
* Copyright (C) 2004 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__action_mode_bar.xml</li>
</ul>
<pre>/*
** Copyright 2010, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AppendableWriter.java</li>
<li>CaseFormat.java</li>
<li>CaseFormatTest.java</li>
<li>FakeTimeLimiter.java</li>
<li>Futures.java</li>
<li>ObjectsTest.java</li>
<li>PatternFilenameFilter.java</li>
<li>PreconditionsTest.java</li>
<li>ReflectionTest.java</li>
<li>SimpleTimeLimiter.java</li>
<li>SimpleTimeLimiterTest.java</li>
<li>TimeLimiter.java</li>
<li>TypeToken.java</li>
<li>UncheckedTimeoutException.java</li>
<li>VisibleForTesting.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>MenuInflater.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
* 2011 Jake Wharton
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractChainedListenableFutureTest.java</li>
<li>AbstractCheckedFuture.java</li>
<li>AbstractCollectionTestSuiteBuilder.java</li>
<li>AbstractContainerTester.java</li>
<li>AbstractImmutableSetTest.java</li>
<li>AbstractIteratorTester.java</li>
<li>AbstractListTester.java</li>
<li>AbstractMultimapAsMapImplementsMapTest.java</li>
<li>AbstractMultisetTester.java</li>
<li>AbstractQueueTester.java</li>
<li>AbstractTableReadTest.java</li>
<li>AbstractTableTest.java</li>
<li>AbstractTester.java</li>
<li>BiMapCollectionTest.java</li>
<li>BiMapGenerators.java</li>
<li>Booleans.java</li>
<li>BooleansTest.java</li>
<li>ByteArrayAsListTest.java</li>
<li>Bytes.java</li>
<li>BytesTest.java</li>
<li>CharArrayAsListTest.java</li>
<li>CharMatcher.java</li>
<li>CharMatcherTest.java</li>
<li>Chars.java</li>
<li>CharsTest.java</li>
<li>CheckedFuture.java</li>
<li>CollectionClearTester.java</li>
<li>CollectionCreationTester.java</li>
<li>CollectionFeature.java</li>
<li>CollectionIteratorTester.java</li>
<li>CollectionRemoveAllTester.java</li>
<li>CollectionRemoveTester.java</li>
<li>CollectionRetainAllTester.java</li>
<li>CollectionSize.java</li>
<li>CollectionTestSuiteBuilder.java</li>
<li>Collections2.java</li>
<li>Collections2Test.java</li>
<li>ConcurrentHashMultisetWithCslmTest.java</li>
<li>ConcurrentMapInterfaceTest.java</li>
<li>ConflictingRequirementsException.java</li>
<li>ConstrainedBiMapTest.java</li>
<li>CountingInputStreamTest.java</li>
<li>DerivedCollectionGenerators.java</li>
<li>DerivedIteratorTestSuiteBuilder.java</li>
<li>DerivedTestIteratorGenerator.java</li>
<li>DoubleArrayAsListTest.java</li>
<li>Doubles.java</li>
<li>DoublesTest.java</li>
<li>EmptyImmutableBiMap.java</li>
<li>EmptyImmutableListMultimap.java</li>
<li>EmptyImmutableMap.java</li>
<li>EmptyImmutableMultiset.java</li>
<li>EmptyImmutableSortedSet.java</li>
<li>FakeTicker.java</li>
<li>FakeTickerTest.java</li>
<li>Feature.java</li>
<li>FeatureSpecificTestSuiteBuilder.java</li>
<li>FeatureUtil.java</li>
<li>FileBackedOutputStream.java</li>
<li>FileBackedOutputStreamTest.java</li>
<li>Finalizer.java</li>
<li>FloatArrayAsListTest.java</li>
<li>Floats.java</li>
<li>FloatsTest.java</li>
<li>FluentIterable.java</li>
<li>ForMapMultimapAsMapImplementsMapTest.java</li>
<li>ForwardingConcurrentMapTest.java</li>
<li>FuturesTest.java</li>
<li>FuturesTransformAsyncFunctionTest.java</li>
<li>FuturesTransformTest.java</li>
<li>HashBasedTable.java</li>
<li>HashBasedTableTest.java</li>
<li>Hashing.java</li>
<li>HelpersTest.java</li>
<li>ImmutableBiMap.java</li>
<li>ImmutableBiMapTest.java</li>
<li>ImmutableCollection.java</li>
<li>ImmutableEntry.java</li>
<li>ImmutableListMultimap.java</li>
<li>ImmutableListMultimapTest.java</li>
<li>ImmutableMap.java</li>
<li>ImmutableMapEntrySet.java</li>
<li>ImmutableMapKeySet.java</li>
<li>ImmutableMapTest.java</li>
<li>ImmutableMapValues.java</li>
<li>ImmutableMultimap.java</li>
<li>ImmutableMultimapAsMapImplementsMapTest.java</li>
<li>ImmutableMultimapTest.java</li>
<li>ImmutableMultiset.java</li>
<li>ImmutableMultisetTest.java</li>
<li>ImmutableSetCollectionTest.java</li>
<li>ImmutableSortedSet.java</li>
<li>ImmutableSortedSetTest.java</li>
<li>InetAddresses.java</li>
<li>InetAddressesTest.java</li>
<li>IntArrayAsListTest.java</li>
<li>Ints.java</li>
<li>IntsTest.java</li>
<li>IteratorFeature.java</li>
<li>IteratorTestSuiteBuilder.java</li>
<li>Joiner.java</li>
<li>JoinerTest.java</li>
<li>ListAddAllAtIndexTester.java</li>
<li>ListAddAtIndexTester.java</li>
<li>ListCreationTester.java</li>
<li>ListEqualsTester.java</li>
<li>ListFeature.java</li>
<li>ListGetTester.java</li>
<li>ListHashCodeTester.java</li>
<li>ListIndexOfTester.java</li>
<li>ListLastIndexOfTester.java</li>
<li>ListRemoveAllTester.java</li>
<li>ListRemoveAtIndexTester.java</li>
<li>ListRemoveTester.java</li>
<li>ListRetainAllTester.java</li>
<li>ListSetTester.java</li>
<li>ListSubListTester.java</li>
<li>ListTestSuiteBuilder.java</li>
<li>ListToArrayTester.java</li>
<li>ListenableFutureTask.java</li>
<li>LongArrayAsListTest.java</li>
<li>Longs.java</li>
<li>LongsTest.java</li>
<li>MapClearTester.java</li>
<li>MapContainsKeyTester.java</li>
<li>MapContainsValueTester.java</li>
<li>MapEqualsTester.java</li>
<li>MapFeature.java</li>
<li>MapHashCodeTester.java</li>
<li>MapInterfaceTest.java</li>
<li>MapRemoveTester.java</li>
<li>MapSizeTester.java</li>
<li>MapTestSuiteBuilder.java</li>
<li>MapsTransformValuesTest.java</li>
<li>MinMaxPriorityQueueTest.java</li>
<li>MockFutureListener.java</li>
<li>MoreExecutorsTest.java</li>
<li>MultiReader.java</li>
<li>MultiReaderTest.java</li>
<li>MultimapCollectionTest.java</li>
<li>MultisetCollectionTest.java</li>
<li>MultisetReadsTester.java</li>
<li>MultisetTestSuiteBuilder.java</li>
<li>MultisetWritesTester.java</li>
<li>NewCustomTableTest.java</li>
<li>OneSizeGenerator.java</li>
<li>OneSizeTestContainerGenerator.java</li>
<li>PeekingIterator.java</li>
<li>PeekingIteratorTest.java</li>
<li>PerCollectionSizeTestSuiteBuilder.java</li>
<li>Platform.java</li>
<li>QueueElementTester.java</li>
<li>QueueOfferTester.java</li>
<li>QueuePeekTester.java</li>
<li>QueuePollTester.java</li>
<li>QueueRemoveTester.java</li>
<li>QueueTestSuiteBuilder.java</li>
<li>Range.java</li>
<li>RangeTest.java</li>
<li>RegularImmutableBiMap.java</li>
<li>RegularImmutableMap.java</li>
<li>ReserializingTestCollectionGenerator.java</li>
<li>ReserializingTestSetGenerator.java</li>
<li>ResourcesTest.java</li>
<li>SampleElements.java</li>
<li>Serialization.java</li>
<li>SetCreationTester.java</li>
<li>SetEqualsTester.java</li>
<li>SetFeature.java</li>
<li>SetGenerators.java</li>
<li>SetHashCodeTester.java</li>
<li>SetOperationsTest.java</li>
<li>SetRemoveTester.java</li>
<li>SetTestSuiteBuilder.java</li>
<li>ShortArrayAsListTest.java</li>
<li>Shorts.java</li>
<li>ShortsTest.java</li>
<li>SignedBytesTest.java</li>
<li>SingletonImmutableMap.java</li>
<li>StandardRowSortedTable.java</li>
<li>StandardTable.java</li>
<li>Stopwatch.java</li>
<li>StopwatchTest.java</li>
<li>Table.java</li>
<li>TableCollectionTest.java</li>
<li>Tables.java</li>
<li>TablesTest.java</li>
<li>TearDown.java</li>
<li>TearDownAccepter.java</li>
<li>TearDownStack.java</li>
<li>TestContainerGenerator.java</li>
<li>TestEnumMultisetGenerator.java</li>
<li>TestIntegerSortedSetGenerator.java</li>
<li>TestIteratorGenerator.java</li>
<li>TestLogHandler.java</li>
<li>TestMapEntrySetGenerator.java</li>
<li>TestMapGenerator.java</li>
<li>TestMultisetGenerator.java</li>
<li>TestQueueGenerator.java</li>
<li>TestStringCollectionGenerator.java</li>
<li>TestStringMapGenerator.java</li>
<li>TestStringMultisetGenerator.java</li>
<li>TestStringQueueGenerator.java</li>
<li>TestStringSortedMapGenerator.java</li>
<li>TestStringSortedSetGenerator.java</li>
<li>TestSubjectGenerator.java</li>
<li>TesterAnnotation.java</li>
<li>TesterRequirements.java</li>
<li>TransposedTableTest.java</li>
<li>TreeBasedTable.java</li>
<li>TreeBasedTableTest.java</li>
<li>UnmodifiableIterator.java</li>
<li>UnmodifiableIteratorTest.java</li>
<li>UnmodifiableMultimapAsMapImplementsMapTest.java</li>
<li>UnsignedBytesTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2008 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>JsonFactory.java</li>
</ul>
<pre>/*
* Copyright (c) 2010 Google Inc.J
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Absent_CustomFieldSerializer.java</li>
<li>AbstractBiMapTester.java</li>
<li>AbstractInvocationHandler.java</li>
<li>AbstractInvocationHandlerTest.java</li>
<li>AbstractMultimapTester.java</li>
<li>AllEqualOrdering.java</li>
<li>AnnotatedHandlerFinderTests.java</li>
<li>ArbitraryInstances.java</li>
<li>ArbitraryInstancesTest.java</li>
<li>BiMapClearTester.java</li>
<li>BiMapInverseTester.java</li>
<li>BiMapPutTester.java</li>
<li>BiMapRemoveTester.java</li>
<li>BiMapTestSuiteBuilder.java</li>
<li>Charset.java</li>
<li>CollectionSerializationEqualTester.java</li>
<li>CollectionSerializationTester.java</li>
<li>DerivedGenerator.java</li>
<li>DerivedGoogleCollectionGenerators.java</li>
<li>EmptyImmutableSortedMap.java</li>
<li>ForwardingDeque.java</li>
<li>ForwardingDequeTest.java</li>
<li>ForwardingImmutableList.java</li>
<li>ForwardingImmutableMap.java</li>
<li>ForwardingImmutableSet.java</li>
<li>ForwardingNavigableMap.java</li>
<li>ForwardingNavigableSet.java</li>
<li>ForwardingNavigableSetTest.java</li>
<li>IllegalCharsetNameException.java</li>
<li>ImmutableCollectionTest.java</li>
<li>ImmutableTypeToInstanceMap.java</li>
<li>ImmutableTypeToInstanceMapTest.java</li>
<li>ListMultimapTestSuiteBuilder.java</li>
<li>MapSerializationTester.java</li>
<li>MapsCollectionTest.java</li>
<li>MediumCharMatcher.java</li>
<li>MultimapContainsEntryTester.java</li>
<li>MultimapContainsKeyTester.java</li>
<li>MultimapContainsValueTester.java</li>
<li>MultimapGetTester.java</li>
<li>MultimapPutIterableTester.java</li>
<li>MultimapPutTester.java</li>
<li>MultimapRemoveAllTester.java</li>
<li>MultimapRemoveEntryTester.java</li>
<li>MultimapSizeTester.java</li>
<li>MultimapTestSuiteBuilder.java</li>
<li>MultisetSerializationTester.java</li>
<li>MutableTypeToInstanceMap.java</li>
<li>MutableTypeToInstanceMapTest.java</li>
<li>Present_CustomFieldSerializer.java</li>
<li>RegularImmutableAsList.java</li>
<li>RegularImmutableSortedMap.java</li>
<li>SetMultimapTestSuiteBuilder.java</li>
<li>SmallCharMatcher.java</li>
<li>SomeClassThatDoesNotUseNullable.java</li>
<li>SortedSetMultimapTestSuiteBuilder.java</li>
<li>TestBiMapGenerator.java</li>
<li>TestListMultimapGenerator.java</li>
<li>TestMultimapGenerator.java</li>
<li>TestSetMultimapGenerator.java</li>
<li>TestStringBiMapGenerator.java</li>
<li>TestStringListMultimapGenerator.java</li>
<li>TestStringSetMultimapGenerator.java</li>
<li>TransformedIterator.java</li>
<li>TransformedListIterator.java</li>
<li>TypeCapture.java</li>
<li>TypeToInstanceMap.java</li>
<li>UnsupportedCharsetException.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2012 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractExecutionThreadService.java</li>
<li>AbstractExecutionThreadServiceTest.java</li>
<li>AbstractIdleService.java</li>
<li>AbstractIdleServiceTest.java</li>
<li>AbstractIndexedListIterator.java</li>
<li>AbstractMultisetSetCountTester.java</li>
<li>AbstractService.java</li>
<li>AbstractServiceTest.java</li>
<li>AllEqualOrdering_CustomFieldSerializer.java</li>
<li>ArrayListMultimap_CustomFieldSerializer.java</li>
<li>ArrayTable.java</li>
<li>ArrayTableTest.java</li>
<li>AsynchronousComputationException.java</li>
<li>ByFunctionOrdering_CustomFieldSerializer.java</li>
<li>ByteArrayDataInput.java</li>
<li>ByteArrayDataOutput.java</li>
<li>ByteProcessor.java</li>
<li>CacheBuilder.java</li>
<li>CacheBuilderTest.java</li>
<li>Callables.java</li>
<li>CallablesTest.java</li>
<li>ClusterException.java</li>
<li>ComparatorOrdering_CustomFieldSerializer.java</li>
<li>ComparisonChain.java</li>
<li>ComparisonChainTest.java</li>
<li>CompoundOrdering_CustomFieldSerializer.java</li>
<li>ComputationException.java</li>
<li>Cut.java</li>
<li>DiscreteDomain.java</li>
<li>EmptyImmutableBiMap.java</li>
<li>EmptyImmutableBiMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableList.java</li>
<li>EmptyImmutableListMultimap_CustomFieldSerializer.java</li>
<li>EmptyImmutableList_CustomFieldSerializer.java</li>
<li>EmptyImmutableMap.java</li>
<li>EmptyImmutableMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableMultiset_CustomFieldSerializer.java</li>
<li>EmptyImmutableSet.java</li>
<li>EmptyImmutableSetMultimap.java</li>
<li>EmptyImmutableSetMultimap_CustomFieldSerializer.java</li>
<li>EmptyImmutableSet_CustomFieldSerializer.java</li>
<li>EmptyImmutableSortedMap_CustomFieldSerializer.java</li>
<li>EmptyImmutableSortedSet.java</li>
<li>EmptyImmutableSortedSet_CustomFieldSerializer.java</li>
<li>ExampleIteratorTester.java</li>
<li>ExplicitOrdering_CustomFieldSerializer.java</li>
<li>FauxveridesTest.java</li>
<li>FilesSimplifyPathTest.java</li>
<li>ForwardingCacheTest.java</li>
<li>ForwardingCollectionTest.java</li>
<li>ForwardingFuture.java</li>
<li>ForwardingImmutableCollection.java</li>
<li>ForwardingImmutableList.java</li>
<li>ForwardingImmutableList_CustomFieldSerializer.java</li>
<li>ForwardingImmutableMap.java</li>
<li>ForwardingImmutableSet.java</li>
<li>ForwardingImmutableSet_CustomFieldSerializer.java</li>
<li>ForwardingListenableFuture.java</li>
<li>ForwardingListenableFutureTest.java</li>
<li>ForwardingLoadingCacheTest.java</li>
<li>ForwardingMapTest.java</li>
<li>ForwardingMultimapTest.java</li>
<li>ForwardingMultisetTest.java</li>
<li>ForwardingService.java</li>
<li>ForwardingTable.java</li>
<li>ForwardingTableTest.java</li>
<li>GwtCompatible.java</li>
<li>GwtIncompatible.java</li>
<li>GwtPlatform.java</li>
<li>GwtSerializationDependencies.java</li>
<li>HashBasedTable_CustomFieldSerializer.java</li>
<li>HashMultimap_CustomFieldSerializer.java</li>
<li>HashMultiset_CustomFieldSerializer.java</li>
<li>Helpers.java</li>
<li>HostSpecifier.java</li>
<li>HostSpecifierTest.java</li>
<li>ImmutableAsList.java</li>
<li>ImmutableAsList_CustomFieldSerializer.java</li>
<li>ImmutableBiMap.java</li>
<li>ImmutableBiMap_CustomFieldSerializer.java</li>
<li>ImmutableClassToInstanceMap.java</li>
<li>ImmutableClassToInstanceMapTest.java</li>
<li>ImmutableEntry_CustomFieldSerializer.java</li>
<li>ImmutableEnumSet.java</li>
<li>ImmutableEnumSet_CustomFieldSerializer.java</li>
<li>ImmutableList.java</li>
<li>ImmutableListMultimap_CustomFieldSerializer.java</li>
<li>ImmutableList_CustomFieldSerializer.java</li>
<li>ImmutableMap.java</li>
<li>ImmutableMultiset_CustomFieldSerializer.java</li>
<li>ImmutableSet.java</li>
<li>ImmutableSetMultimap.java</li>
<li>ImmutableSetMultimapAsMapImplementsMapTest.java</li>
<li>ImmutableSetMultimapTest.java</li>
<li>ImmutableSetMultimap_CustomFieldSerializer.java</li>
<li>ImmutableSet_CustomFieldSerializer.java</li>
<li>ImmutableSortedAsList.java</li>
<li>ImmutableSortedMap.java</li>
<li>ImmutableSortedMapFauxverideShim.java</li>
<li>ImmutableSortedMapTest.java</li>
<li>ImmutableSortedMap_CustomFieldSerializer.java</li>
<li>ImmutableSortedMap_CustomFieldSerializerBase.java</li>
<li>ImmutableSortedSet.java</li>
<li>ImmutableSortedSetFauxverideShim.java</li>
<li>ImmutableSortedSet_CustomFieldSerializer.java</li>
<li>InternetDomainName.java</li>
<li>InternetDomainNameTest.java</li>
<li>JdkFutureAdapters.java</li>
<li>JdkFutureAdaptersTest.java</li>
<li>LegacyComparable.java</li>
<li>LexicographicalOrdering_CustomFieldSerializer.java</li>
<li>LineProcessor.java</li>
<li>LinkedHashMultimap_CustomFieldSerializer.java</li>
<li>LinkedHashMultiset_CustomFieldSerializer.java</li>
<li>LinkedListMultimap_CustomFieldSerializer.java</li>
<li>ListGenerators.java</li>
<li>ListenableFutureTaskTest.java</li>
<li>ListenableFutureTester.java</li>
<li>LocalCache.java</li>
<li>MapGenerators.java</li>
<li>MapMaker.java</li>
<li>MapMakerInternalMap.java</li>
<li>MinimalIterable.java</li>
<li>MinimalSet.java</li>
<li>Multimap_CustomFieldSerializerBase.java</li>
<li>MultisetSetCountConditionallyTester.java</li>
<li>MultisetSetCountUnconditionallyTester.java</li>
<li>Multiset_CustomFieldSerializerBase.java</li>
<li>NaturalOrdering_CustomFieldSerializer.java</li>
<li>NullsFirstOrdering_CustomFieldSerializer.java</li>
<li>NullsLastOrdering_CustomFieldSerializer.java</li>
<li>PatternFilenameFilterTest.java</li>
<li>Platform.java</li>
<li>RangeNonGwtTest.java</li>
<li>Ranges.java</li>
<li>RegularImmutableBiMap_CustomFieldSerializer.java</li>
<li>RegularImmutableList.java</li>
<li>RegularImmutableList_CustomFieldSerializer.java</li>
<li>RegularImmutableMap.java</li>
<li>RegularImmutableMap_CustomFieldSerializer.java</li>
<li>RegularImmutableSet.java</li>
<li>RegularImmutableSet_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedMap_CustomFieldSerializer.java</li>
<li>RegularImmutableSortedSet.java</li>
<li>RegularImmutableSortedSet_CustomFieldSerializer.java</li>
<li>ReverseNaturalOrdering_CustomFieldSerializer.java</li>
<li>ReverseOrdering_CustomFieldSerializer.java</li>
<li>SerializableTesterTest.java</li>
<li>Service.java</li>
<li>SettableFuture.java</li>
<li>SettableFutureTest.java</li>
<li>SignedBytes.java</li>
<li>SingletonImmutableList.java</li>
<li>SingletonImmutableList_CustomFieldSerializer.java</li>
<li>SingletonImmutableMap.java</li>
<li>SingletonImmutableMap_CustomFieldSerializer.java</li>
<li>SingletonImmutableSet.java</li>
<li>SingletonImmutableSet_CustomFieldSerializer.java</li>
<li>SloppyTearDown.java</li>
<li>SortedMapGenerators.java</li>
<li>SortedMapInterfaceTest.java</li>
<li>Splitter.java</li>
<li>SplitterTest.java</li>
<li>SubMapMultimapAsMapImplementsMapTest.java</li>
<li>TestEnumMapGenerator.java</li>
<li>TestUnhashableCollectionGenerator.java</li>
<li>TestsForListsInJavaUtil.java</li>
<li>TestsForMapsInJavaUtil.java</li>
<li>TestsForQueuesInJavaUtil.java</li>
<li>TestsForSetsInJavaUtil.java</li>
<li>ToStringHelperTest.java</li>
<li>TreeBasedTable_CustomFieldSerializer.java</li>
<li>TreeMultimap_CustomFieldSerializer.java</li>
<li>TypeResolver.java</li>
<li>TypeTokenResolutionTest.java</li>
<li>UnhashableObject.java</li>
<li>UnsignedBytes.java</li>
<li>UsingToStringOrdering_CustomFieldSerializer.java</li>
</ul>
<pre>/*
* Copyright (C) 2009 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbsActionBarView.java</li>
<li>AccessibilityDelegateCompat.java</li>
<li>AccessibilityDelegateCompatIcs.java</li>
<li>AccessibilityEventCompat.java</li>
<li>AccessibilityEventCompatIcs.java</li>
<li>AccessibilityManagerCompat.java</li>
<li>AccessibilityManagerCompatIcs.java</li>
<li>AccessibilityNodeInfoCompat.java</li>
<li>AccessibilityNodeInfoCompatIcs.java</li>
<li>AccessibilityRecordCompat.java</li>
<li>AccessibilityRecordCompatIcs.java</li>
<li>AccessibilityServiceInfoCompat.java</li>
<li>AccessibilityServiceInfoCompatIcs.java</li>
<li>ActionMenuPresenter.java</li>
<li>ActionProvider.java</li>
<li>ActivityChooserModel.java</li>
<li>ActivityChooserView.java</li>
<li>ActivityCompat.java</li>
<li>ActivityCompatHoneycomb.java</li>
<li>ActivityInfoCompat.java</li>
<li>AsyncTaskLoader.java</li>
<li>BackStackRecord.java</li>
<li>BaseMenuPresenter.java</li>
<li>CollapsibleActionView.java</li>
<li>CursorAdapter.java</li>
<li>CursorFilter.java</li>
<li>CursorLoader.java</li>
<li>DatabaseUtilsCompat.java</li>
<li>DebugUtils.java</li>
<li>DialogFragment.java</li>
<li>EdgeEffectCompat.java</li>
<li>EdgeEffectCompatIcs.java</li>
<li>Fragment.java</li>
<li>FragmentActivity.java</li>
<li>FragmentManager.java</li>
<li>FragmentPagerAdapter.java</li>
<li>FragmentStatePagerAdapter.java</li>
<li>FragmentTransaction.java</li>
<li>HCSparseArray.java</li>
<li>IntentCompat.java</li>
<li>KeyEventCompat.java</li>
<li>KeyEventCompatHoneycomb.java</li>
<li>ListFragment.java</li>
<li>Loader.java</li>
<li>LoaderManager.java</li>
<li>LocalBroadcastManager.java</li>
<li>LogWriter.java</li>
<li>LruCache.java</li>
<li>MenuCompat.java</li>
<li>MenuItemCompat.java</li>
<li>MenuItemCompatHoneycomb.java</li>
<li>MenuPresenter.java</li>
<li>ModernAsyncTask.java</li>
<li>MotionEventCompat.java</li>
<li>MotionEventCompatEclair.java</li>
<li>NoSaveStateFrameLayout.java</li>
<li>PagerAdapter.java</li>
<li>PagerTitleStrip.java</li>
<li>ParcelableCompat.java</li>
<li>ParcelableCompatCreatorCallbacks.java</li>
<li>ParcelableCompatHoneycombMR2.java</li>
<li>ResourceCursorAdapter.java</li>
<li>ScrollingTabContainerView.java</li>
<li>SearchViewCompat.java</li>
<li>SearchViewCompatHoneycomb.java</li>
<li>ServiceCompat.java</li>
<li>ShareActionProvider.java</li>
<li>ShareCompat.java</li>
<li>ShareCompatICS.java</li>
<li>SimpleCursorAdapter.java</li>
<li>SuperNotCalledException.java</li>
<li>TimeUtils.java</li>
<li>VelocityTrackerCompat.java</li>
<li>VelocityTrackerCompatHoneycomb.java</li>
<li>ViewCompat.java</li>
<li>ViewCompatGingerbread.java</li>
<li>ViewCompatICS.java</li>
<li>ViewConfigurationCompat.java</li>
<li>ViewConfigurationCompatFroyo.java</li>
<li>ViewGroupCompat.java</li>
<li>ViewGroupCompatIcs.java</li>
<li>ViewPager.java</li>
</ul>
<pre>/*
* Copyright (C) 2011 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>ActionBar.java</li>
<li>ActionBarContainer.java</li>
<li>ActionBarContextView.java</li>
<li>ActionBarImpl.java</li>
<li>ActionBarView.java</li>
<li>ActionMenu.java</li>
<li>ActionMenuItem.java</li>
<li>ActionMenuItemView.java</li>
<li>ActionMenuView.java</li>
<li>ActionMode.java</li>
<li>Animator.java</li>
<li>AnimatorListenerAdapter.java</li>
<li>AnimatorSet.java</li>
<li>FloatEvaluator.java</li>
<li>FloatKeyframeSet.java</li>
<li>IntEvaluator.java</li>
<li>IntKeyframeSet.java</li>
<li>Keyframe.java</li>
<li>KeyframeSet.java</li>
<li>MenuPopupHelper.java</li>
<li>ObjectAnimator.java</li>
<li>PropertyValuesHolder.java</li>
<li>StandaloneActionMode.java</li>
<li>TypeEvaluator.java</li>
<li>ValueAnimator.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>Window.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>FinalizableReferenceQueueClassLoaderUnloadingTest.java</li>
<li>FinalizableReferenceQueueTest.java</li>
<li>FunctionsTest.java</li>
<li>NullPointerTester.java</li>
<li>NullPointerTesterTest.java</li>
<li>PredicatesTest.java</li>
<li>Reflection.java</li>
</ul>
<pre>/*
* Copyright (C) 2005 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AndroidInteger.java</li>
<li>StringMap.java</li>
<li>StringMap.java.svn-base</li>
</ul>
<pre>/*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>sherlock_spinner_item.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/layout/simple_spinner_item.xml
**
** Copyright 2006, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAtomFeedParser.java</li>
<li>AbstractJsonFactoryTest.java</li>
<li>AbstractJsonFeedParser.java</li>
<li>AbstractOAuthGetToken.java</li>
<li>AbstractXmlHttpContent.java</li>
<li>AccessProtectedResource.java</li>
<li>AccessTokenErrorResponse.java</li>
<li>AccessTokenRequest.java</li>
<li>AccessTokenResponse.java</li>
<li>ApacheHttpRequest.java</li>
<li>ApacheHttpResponse.java</li>
<li>ApacheHttpTransport.java</li>
<li>ArrayMap.java</li>
<li>ArrayMapTest.java</li>
<li>Atom.java</li>
<li>AtomFeedParser.java</li>
<li>AtomParser.java</li>
<li>AtomPatchContent.java</li>
<li>AtomPatchRelativeToOriginalContent.java</li>
<li>AuthKeyValueParser.java</li>
<li>AuthorizationRequestUrl.java</li>
<li>AuthorizationRequestUrlTest.java</li>
<li>AuthorizationResponse.java</li>
<li>AuthorizationResponseTest.java</li>
<li>CharEscapers.java</li>
<li>ClassInfo.java</li>
<li>ClassInfoTest.java</li>
<li>ClientLogin.java</li>
<li>CommentsTest.java</li>
<li>CommentsTest.java.svn-base</li>
<li>ContentEntity.java</li>
<li>CustomizeJsonParser.java</li>
<li>DataMap.java</li>
<li>DateTime.java</li>
<li>DateTimeTest.java</li>
<li>Escaper.java</li>
<li>FieldInfo.java</li>
<li>FieldInfoTest.java</li>
<li>GZipContent.java</li>
<li>GenericData.java</li>
<li>GenericDataTest.java</li>
<li>GenericJson.java</li>
<li>GenericUrl.java</li>
<li>GenericUrlTest.java</li>
<li>GenericXml.java</li>
<li>GenericXmlTest.java</li>
<li>GoogleAtom.java</li>
<li>GoogleAtomTest.java</li>
<li>GoogleHeaders.java</li>
<li>GoogleJsonRpcHttpTransport.java</li>
<li>GoogleOAuthAuthorizeTemporaryTokenUrl.java</li>
<li>GoogleOAuthDomainWideDelegation.java</li>
<li>GoogleOAuthGetAccessToken.java</li>
<li>GoogleOAuthGetTemporaryToken.java</li>
<li>GoogleUrl.java</li>
<li>GsonFactoryTest.java</li>
<li>HttpContent.java</li>
<li>HttpExecuteInterceptor.java</li>
<li>HttpHeaders.java</li>
<li>HttpHeadersTest.java</li>
<li>HttpMethod.java</li>
<li>HttpParser.java</li>
<li>HttpPatch.java</li>
<li>HttpRequest.java</li>
<li>HttpRequestTest.java</li>
<li>HttpResponse.java</li>
<li>HttpResponseException.java</li>
<li>HttpResponseTest.java</li>
<li>HttpTransport.java</li>
<li>HttpUnsuccessfulResponseHandler.java</li>
<li>InputStreamContent.java</li>
<li>JacksonFactory.java</li>
<li>JacksonFactoryTest.java</li>
<li>JacksonGenerator.java</li>
<li>JacksonParser.java</li>
<li>Json.java</li>
<li>JsonCContent.java</li>
<li>JsonCParser.java</li>
<li>JsonEncoding.java</li>
<li>JsonFeedParser.java</li>
<li>JsonGenerator.java</li>
<li>JsonHttpContent.java</li>
<li>JsonHttpParser.java</li>
<li>JsonMultiKindFeedParser.java</li>
<li>JsonParser.java</li>
<li>JsonReader.java</li>
<li>JsonReader.java.svn-base</li>
<li>JsonReaderTest.java</li>
<li>JsonReaderTest.java.svn-base</li>
<li>JsonRpcRequest.java</li>
<li>JsonScope.java</li>
<li>JsonScope.java.svn-base</li>
<li>JsonSyntaxException.java</li>
<li>JsonSyntaxException.java.svn-base</li>
<li>JsonToken.java</li>
<li>JsonToken.java.svn-base</li>
<li>JsonWriter.java</li>
<li>JsonWriter.java.svn-base</li>
<li>JsonWriterTest.java</li>
<li>JsonWriterTest.java.svn-base</li>
<li>Key.java</li>
<li>LogContent.java</li>
<li>LowLevelHttpRequest.java</li>
<li>LowLevelHttpResponse.java</li>
<li>MalformedJsonException.java</li>
<li>MalformedJsonException.java.svn-base</li>
<li>MapAsArrayTypeAdapterTest.java</li>
<li>MapAsArrayTypeAdapterTest.java.svn-base</li>
<li>MethodOverride.java</li>
<li>MethodOverrideTest.java</li>
<li>MixedStreamTest.java</li>
<li>MixedStreamTest.java.svn-base</li>
<li>MockHttpContent.java</li>
<li>MockHttpTransport.java</li>
<li>MockLowLevelHttpRequest.java</li>
<li>MockLowLevelHttpResponse.java</li>
<li>MultiKindFeedParser.java</li>
<li>NetHttpRequest.java</li>
<li>NetHttpResponse.java</li>
<li>NetHttpTransport.java</li>
<li>OAuthAuthorizeTemporaryTokenUrl.java</li>
<li>OAuthCallbackUrl.java</li>
<li>OAuthCredentialsResponse.java</li>
<li>OAuthGetAccessToken.java</li>
<li>OAuthGetTemporaryToken.java</li>
<li>OAuthHmacSigner.java</li>
<li>OAuthParameters.java</li>
<li>OAuthParametersTest.java</li>
<li>OAuthRsaSigner.java</li>
<li>OAuthSigner.java</li>
<li>PercentEscaper.java</li>
<li>Platform.java</li>
<li>ProtoTypeAdapter.java</li>
<li>ProtoTypeAdapter.java.svn-base</li>
<li>ProtosWithComplexAndRepeatedFieldsTest.java</li>
<li>ProtosWithComplexAndRepeatedFieldsTest.java.svn-base</li>
<li>ProtosWithPrimitiveTypesTest.java</li>
<li>ProtosWithPrimitiveTypesTest.java.svn-base</li>
<li>RawSerializationTest.java</li>
<li>RawSerializationTest.java.svn-base</li>
<li>SafeTreeMapTest.java</li>
<li>SafeTreeSetTest.java</li>
<li>Streams.java</li>
<li>Streams.java.svn-base</li>
<li>StringUtilsTest.java</li>
<li>TearDownStackTest.java</li>
<li>TypeTokenTest.java</li>
<li>TypeTokenTest.java.svn-base</li>
<li>TypeVariableTest.java</li>
<li>TypeVariableTest.java.svn-base</li>
<li>UnicodeEscaper.java</li>
<li>UrlEncodedContent.java</li>
<li>UrlEncodedContentTest.java</li>
<li>UrlEncodedParser.java</li>
<li>UrlEncodedParserTest.java</li>
<li>UrlFetchRequest.java</li>
<li>UrlFetchResponse.java</li>
<li>UrlFetchTransport.java</li>
<li>Xml.java</li>
<li>XmlHttpContent.java</li>
<li>XmlHttpParser.java</li>
<li>XmlNamespaceDictionary.java</li>
<li>XmlNamespaceDictionaryTest.java</li>
<li>XmlObjectParser.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (c) 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li></li>
</ul>
<pre>Google Gson
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2008-2011 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
</pre>
<h3>Notices for files:</h3><ul>
<li>$Gson$Preconditions.java</li>
<li>$Gson$Preconditions.java.svn-base</li>
<li>$Gson$Types.java</li>
<li>$Gson$Types.java.svn-base</li>
<li>ArrayTest.java</li>
<li>ArrayTest.java.svn-base</li>
<li>CircularReferenceTest.java</li>
<li>CircularReferenceTest.java.svn-base</li>
<li>CollectionTest.java</li>
<li>CollectionTest.java.svn-base</li>
<li>ConcurrencyTest.java</li>
<li>ConcurrencyTest.java.svn-base</li>
<li>CustomDeserializerTest.java</li>
<li>CustomDeserializerTest.java.svn-base</li>
<li>CustomTypeAdaptersTest.java</li>
<li>CustomTypeAdaptersTest.java.svn-base</li>
<li>DefaultDateTypeAdapter.java</li>
<li>DefaultDateTypeAdapter.java.svn-base</li>
<li>DefaultDateTypeAdapterTest.java</li>
<li>DefaultDateTypeAdapterTest.java.svn-base</li>
<li>DefaultMapJsonSerializerTest.java</li>
<li>DefaultMapJsonSerializerTest.java.svn-base</li>
<li>DefaultTypeAdaptersTest.java</li>
<li>DefaultTypeAdaptersTest.java.svn-base</li>
<li>EnumTest.java</li>
<li>EnumTest.java.svn-base</li>
<li>EscapingTest.java</li>
<li>EscapingTest.java.svn-base</li>
<li>Excluder.java</li>
<li>Excluder.java.svn-base</li>
<li>ExclusionStrategy.java</li>
<li>ExclusionStrategy.java.svn-base</li>
<li>ExclusionStrategyFunctionalTest.java</li>
<li>ExclusionStrategyFunctionalTest.java.svn-base</li>
<li>Expose.java</li>
<li>Expose.java.svn-base</li>
<li>ExposeFieldsTest.java</li>
<li>ExposeFieldsTest.java.svn-base</li>
<li>FeatureEnumTest.java</li>
<li>FeatureUtilTest.java</li>
<li>FieldExclusionTest.java</li>
<li>FieldExclusionTest.java.svn-base</li>
<li>FieldNamingPolicy.java</li>
<li>FieldNamingPolicy.java.svn-base</li>
<li>FieldNamingStrategy.java</li>
<li>FieldNamingStrategy.java.svn-base</li>
<li>FluentIterableTest.java</li>
<li>GenericArrayTypeTest.java</li>
<li>GenericArrayTypeTest.java.svn-base</li>
<li>Gson.java</li>
<li>Gson.java.svn-base</li>
<li>GsonBuilder.java</li>
<li>GsonBuilder.java.svn-base</li>
<li>GsonBuilderTest.java</li>
<li>GsonBuilderTest.java.svn-base</li>
<li>GsonTypeAdapterTest.java</li>
<li>GsonTypeAdapterTest.java.svn-base</li>
<li>InnerClassExclusionStrategyTest.java</li>
<li>InnerClassExclusionStrategyTest.java.svn-base</li>
<li>InstanceCreator.java</li>
<li>InstanceCreator.java.svn-base</li>
<li>InterfaceTest.java</li>
<li>InterfaceTest.java.svn-base</li>
<li>InternationalizationTest.java</li>
<li>InternationalizationTest.java.svn-base</li>
<li>IteratorTesterTest.java</li>
<li>JsonArray.java</li>
<li>JsonArray.java.svn-base</li>
<li>JsonDeserializationContext.java</li>
<li>JsonDeserializationContext.java.svn-base</li>
<li>JsonDeserializer.java</li>
<li>JsonDeserializer.java.svn-base</li>
<li>JsonElement.java</li>
<li>JsonElement.java.svn-base</li>
<li>JsonIOException.java</li>
<li>JsonIOException.java.svn-base</li>
<li>JsonNull.java</li>
<li>JsonNull.java.svn-base</li>
<li>JsonObject.java</li>
<li>JsonObject.java.svn-base</li>
<li>JsonObjectTest.java</li>
<li>JsonObjectTest.java.svn-base</li>
<li>JsonParseException.java</li>
<li>JsonParseException.java.svn-base</li>
<li>JsonParserTest.java</li>
<li>JsonParserTest.java.svn-base</li>
<li>JsonPrimitive.java</li>
<li>JsonPrimitive.java.svn-base</li>
<li>JsonPrimitiveTest.java</li>
<li>JsonPrimitiveTest.java.svn-base</li>
<li>JsonSerializationContext.java</li>
<li>JsonSerializationContext.java.svn-base</li>
<li>JsonSerializer.java</li>
<li>JsonSerializer.java.svn-base</li>
<li>MapTest.java</li>
<li>MapTest.java.svn-base</li>
<li>MapTestSuiteBuilderTests.java</li>
<li>MockExclusionStrategy.java</li>
<li>MockExclusionStrategy.java.svn-base</li>
<li>MoreAsserts.java</li>
<li>MoreAsserts.java.svn-base</li>
<li>NamingPolicyTest.java</li>
<li>NamingPolicyTest.java.svn-base</li>
<li>NullObjectAndFieldTest.java</li>
<li>NullObjectAndFieldTest.java.svn-base</li>
<li>ObjectConstructor.java</li>
<li>ObjectConstructor.java.svn-base</li>
<li>ObjectTest.java</li>
<li>ObjectTest.java.svn-base</li>
<li>ParameterizedTypeFixtures.java</li>
<li>ParameterizedTypeFixtures.java.svn-base</li>
<li>ParameterizedTypeTest.java</li>
<li>ParameterizedTypeTest.java.svn-base</li>
<li>ParameterizedTypesTest.java</li>
<li>ParameterizedTypesTest.java.svn-base</li>
<li>PerformanceTest.java</li>
<li>PerformanceTest.java.svn-base</li>
<li>PrettyPrintingTest.java</li>
<li>PrettyPrintingTest.java.svn-base</li>
<li>PrimitiveCharacterTest.java</li>
<li>PrimitiveCharacterTest.java.svn-base</li>
<li>PrimitiveTest.java</li>
<li>PrimitiveTest.java.svn-base</li>
<li>PrimitiveTypeAdapter.java</li>
<li>PrimitiveTypeAdapter.java.svn-base</li>
<li>Primitives.java</li>
<li>Primitives.java.svn-base</li>
<li>PrintFormattingTest.java</li>
<li>PrintFormattingTest.java.svn-base</li>
<li>ReadersWritersTest.java</li>
<li>ReadersWritersTest.java.svn-base</li>
<li>SecurityTest.java</li>
<li>SecurityTest.java.svn-base</li>
<li>SerializedName.java</li>
<li>SerializedName.java.svn-base</li>
<li>Since.java</li>
<li>Since.java.svn-base</li>
<li>TestLogHandlerTest.java</li>
<li>TestTypes.java</li>
<li>TestTypes.java.svn-base</li>
<li>TypeToken.java</li>
<li>TypeToken.java.svn-base</li>
<li>UncategorizedTest.java</li>
<li>UncategorizedTest.java.svn-base</li>
<li>Until.java</li>
<li>Until.java.svn-base</li>
<li>VersionExclusionStrategyTest.java</li>
<li>VersionExclusionStrategyTest.java.svn-base</li>
<li>VersioningTest.java</li>
<li>VersioningTest.java.svn-base</li>
</ul>
<pre>/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>jackson-core-asl.jar</li>
</ul>
<pre>/* Jackson JSON-processor.
*
* Copyright (c) 2007- Tatu Saloranta, tatu.saloranta@iki.fi
*
* Licensed under the License specified in file LICENSE, included with
* the source code and binary code bundles.
* You may not use this file except in compliance with the License.
*
* 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.
*/
------- LICENSE --------
This copy of Jackson JSON processor is licensed under the
Apache (Software) License, version 2.0 ("the License").
See the License for details about distribution rights, and the
specific rights regarding derivate works.
You may obtain a copy of the License at:
http://www.apache.org/licenses/
A copy is also included with both the the downloadable source code package
and jar that contains class bytecodes, as file "ASL 2.0". In both cases,
that file should be located next to this file: in source distribution
the location should be "release-notes/asl"; and in jar "META-INF/"
</pre>
<h3>Notices for files:</h3><ul>
<li>IcsAbsSpinner.java</li>
<li>IcsAdapterView.java</li>
<li>IcsProgressBar.java</li>
<li>ListMenuItemView.java</li>
<li>Menu.java</li>
<li>MenuBuilder.java</li>
<li>MenuItemImpl.java</li>
<li>MenuView.java</li>
<li>SubMenuBuilder.java</li>
</ul>
<pre>/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>NullOutputStreamTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2002 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__bools.xml</li>
<li>abs__dialog_title_holo.xml</li>
<li>abs__screen_simple_overlay_action_mode.xml</li>
</ul>
<pre>/*
** Copyright 2011, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>sherlock_spinner_dropdown_item.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/any/layout/simple_spinner_item.xml
**
** Copyright 2008, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractAppEngineAuthorizationCodeCallbackServlet.java</li>
<li>AbstractAppEngineAuthorizationCodeServlet.java</li>
<li>AbstractAuthorizationCodeCallbackServlet.java</li>
<li>AbstractAuthorizationCodeServlet.java</li>
<li>AppEngineCredentialStore.java</li>
<li>AppIdentityCredential.java</li>
<li>AuthorizationCodeFlow.java</li>
<li>Base64.java</li>
<li>BatchCallback.java</li>
<li>BatchRequest.java</li>
<li>BatchUnparsedResponse.java</li>
<li>Clock.java</li>
<li>ClockTest.java</li>
<li>CredentialRefreshListener.java</li>
<li>CredentialStore.java</li>
<li>DelegateTypeAdapterTest.java</li>
<li>DelegateTypeAdapterTest.java.svn-base</li>
<li>FixedClock.java</li>
<li>FixedClockTest.java</li>
<li>GoogleAuthorizationCodeFlow.java</li>
<li>GoogleAuthorizationCodeFlowTest.java</li>
<li>GoogleIdToken.java</li>
<li>GoogleIdTokenVerifier.java</li>
<li>GoogleIdTokenVerifierTest.java</li>
<li>GoogleJsonErrorContainer.java</li>
<li>GoogleJsonErrorContainerTest.java</li>
<li>GoogleKeyInitializer.java</li>
<li>GoogleKeyInitializerTest.java</li>
<li>GoogleTokenResponse.java</li>
<li>HttpMediaType.java</li>
<li>HttpMediaTypeTest.java</li>
<li>IdTokenResponse.java</li>
<li>JdoCredentialStore.java</li>
<li>JsonBatchCallback.java</li>
<li>JsonHttpRequestTest.java</li>
<li>JsonObjectParser.java</li>
<li>JsonObjectParserTest.java</li>
<li>JsonParserTest.java</li>
<li>JsonWebSignature.java</li>
<li>JsonWebToken.java</li>
<li>JsonWebTokenTest.java</li>
<li>LoggingByteArrayOutputStream.java</li>
<li>LoggingInputStream.java</li>
<li>LoggingOutputStream.java</li>
<li>LongAdder.java</li>
<li>MediaHttpDownloader.java</li>
<li>MediaHttpDownloaderProgressListener.java</li>
<li>MediaHttpDownloaderTest.java</li>
<li>MemoryCredentialStore.java</li>
<li>MemoryPersistedCredential.java</li>
<li>MultipartMixedContent.java</li>
<li>MultipartMixedContentTest.java</li>
<li>NetHttpResponseTest.java</li>
<li>NetHttpTransportTest.java</li>
<li>OAuthHmacSignerTest.java</li>
<li>OAuthRsaSignerTest.java</li>
<li>ObjectParser.java</li>
<li>PrivateKeys.java</li>
<li>ProtoObjectParser.java</li>
<li>RsaSHA256Signer.java</li>
<li>RsaSHA256SignerTest.java</li>
<li>StringUtils.java</li>
<li>UrlFetchRequest.java</li>
<li>UrlFetchResponse.java</li>
<li>UrlFetchTransport.java</li>
<li>UrlFetchTransportTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (c) 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>abs__screen_simple.xml</li>
</ul>
<pre>/* //device/apps/common/assets/res/layout/screen_simple.xml
**
** Copyright 2006, The Android Open Source Project
**
** 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>protobuf-java-lite.jar</li>
</ul>
<pre>Protocol Buffer Java API
BSD License:
Copyright (c) 2007, Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
</pre>
<h3>Notices for files:</h3><ul>
<li>AbstractLinkedIterator.java</li>
<li>AbstractSequentialIterator.java</li>
<li>AbstractSequentialIteratorTest.java</li>
<li>Ascii.java</li>
<li>AsciiTest.java</li>
<li>Atomics.java</li>
<li>AtomicsTest.java</li>
<li>BaseComparable.java</li>
<li>Beta.java</li>
<li>ComputingConcurrentHashMap.java</li>
<li>ContiguousSet.java</li>
<li>DerivedComparable.java</li>
<li>DiscreteDomains.java</li>
<li>Equivalence.java</li>
<li>Equivalences.java</li>
<li>ForwardingBlockingQueue.java</li>
<li>ForwardingListMultimap.java</li>
<li>ForwardingListMultimapTest.java</li>
<li>ForwardingSetMultimap.java</li>
<li>ForwardingSetMultimapTest.java</li>
<li>ForwardingSortedSetMultimap.java</li>
<li>ForwardingSortedSetMultimapTest.java</li>
<li>ForwardingSortedSetTest.java</li>
<li>GenericMapMaker.java</li>
<li>ListeningExecutorService.java</li>
<li>LittleEndianDataOutputStreamTest.java</li>
<li>MinMaxPriorityQueue.java</li>
<li>Monitor.java</li>
<li>MultimapsTransformValuesAsMapTest.java</li>
<li>NavigableMapNavigationTester.java</li>
<li>NavigableMapTestSuiteBuilder.java</li>
<li>NavigableSetNavigationTester.java</li>
<li>NavigableSetTestSuiteBuilder.java</li>
<li>RegularImmutableAsList_CustomFieldSerializer.java</li>
<li>RowSortedTable.java</li>
<li>SafeTreeMap.java</li>
<li>SafeTreeSet.java</li>
<li>SortedLists.java</li>
<li>SortedListsTest.java</li>
<li>SortedMapDifference.java</li>
<li>SortedMapNavigationTester.java</li>
<li>SortedMapTestSuiteBuilder.java</li>
<li>SortedSetNavigationTester.java</li>
<li>SortedSetTestSuiteBuilder.java</li>
<li>Strings.java</li>
<li>StringsTest.java</li>
<li>TestModuleEntryPoint.java</li>
<li>ThreadFactoryBuilder.java</li>
<li>ThreadFactoryBuilderTest.java</li>
<li>TransformedImmutableList.java</li>
<li>TransformedImmutableListTest.java</li>
<li>UncaughtExceptionHandlers.java</li>
<li>UncaughtExceptionHandlersTest.java</li>
<li>UnmodifiableListIterator.java</li>
<li>UnmodifiableListIteratorTest.java</li>
<li>package-info.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>IcsSpinner.java</li>
<li>SubMenu.java</li>
</ul>
<pre>/*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*/</pre>
<h3>Notices for files:</h3><ul>
<li>EquivalenceTest.java</li>
<li>EquivalencesTest.java</li>
</ul>
<pre>/*
* Copyright (C) 2010 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* diOBJECTibuted under the License is diOBJECTibuted 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.
*/</pre>
</body></html>
|
1162584980-google-io
|
android/assets/licenses.html
|
HTML
|
asf20
| 97,984
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.android.plus;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Button;
/**
* Stub until the release of <a href="https://developers.google.com/android/google-play-services/">
* Google Play Services.</a>
*/
public final class PlusOneButton extends Button {
public PlusOneButton(Context context) {
super(context);
}
public PlusOneButton(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PlusOneButton(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
}
public void setUrl(String url) {
}
public void setSize(Size size) {
}
public enum Size {
SMALL, MEDIUM, TALL, STANDARD
}
}
|
1162584980-google-io
|
android/src/com/google/api/android/plus/PlusOneButton.java
|
Java
|
asf20
| 1,391
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.api.android.plus;
import android.content.Context;
/**
* Stub until the release of <a href="https://developers.google.com/android/google-play-services/">
* Google Play Services.</a>
*/
public final class GooglePlus {
public static GooglePlus initialize(Context context, String apiKey, String clientId) {
return new GooglePlus();
}
}
|
1162584980-google-io
|
android/src/com/google/api/android/plus/GooglePlus.java
|
Java
|
asf20
| 969
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Room;
import com.google.android.apps.iosched.io.model.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses room JSON data into a list of content provider operations.
*/
public class RoomsHandler extends JSONHandler {
private static final String TAG = makeLogTag(RoomsHandler.class);
public RoomsHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
Rooms roomsJson = new Gson().fromJson(json, Rooms.class);
int noOfRooms = roomsJson.rooms.length;
for (int i = 0; i < noOfRooms; i++) {
parseRoom(roomsJson.rooms[i], batch);
}
return batch;
}
private static void parseRoom(Room room, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Rooms.CONTENT_URI));
builder.withValue(ScheduleContract.Rooms.ROOM_ID, room.id);
builder.withValue(ScheduleContract.Rooms.ROOM_NAME, room.name);
builder.withValue(ScheduleContract.Rooms.ROOM_FLOOR, room.floor);
batch.add(builder.build());
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/RoomsHandler.java
|
Java
|
asf20
| 2,373
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Event {
public String room;
public String end_date;
public String level;
public String[] track;
public String start_time;
public String title;
@SerializedName("abstract")
public String _abstract;
public String start_date;
public String attending;
public String has_streaming;
public String end_time;
public String livestream_url;
public String[] youtube_url;
public String id;
public String tags;
public String[] speaker_id;
public String[] prereq;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Event.java
|
Java
|
asf20
| 1,237
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class MyScheduleItem {
public String date;
public String time;
public String role;
public Location[] locations;
public String title;
public String session_id;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/MyScheduleItem.java
|
Java
|
asf20
| 841
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SandboxCompany {
public String company_name;
public String company_description;
public String[] exhibitors;
public String logo_img;
public String product_description;
public String product_pod;
public String website;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/SandboxCompany.java
|
Java
|
asf20
| 908
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class AnnouncementsResponse extends GenericResponse {
public Announcement[] announcements;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/AnnouncementsResponse.java
|
Java
|
asf20
| 752
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SearchSuggestions {
public String[] words;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/SearchSuggestions.java
|
Java
|
asf20
| 710
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Tracks {
Track[] track;
public Track[] getTrack() {
return track;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Tracks.java
|
Java
|
asf20
| 752
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Errors {
public Error[] errors;
public String code;
public String message;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Errors.java
|
Java
|
asf20
| 751
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Speaker {
public String display_name;
public String bio;
public String plusone_url;
public String thumbnail_url;
public String user_id;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Speaker.java
|
Java
|
asf20
| 819
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class TimeSlot {
public String start;
public String end;
public String title;
public String type;
public String meta;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/TimeSlot.java
|
Java
|
asf20
| 795
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class EventSlots {
public Day[] day;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/EventSlots.java
|
Java
|
asf20
| 701
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Error {
public String domain;
public String reason;
public String message;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Error.java
|
Java
|
asf20
| 751
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Location {
public String location;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Location.java
|
Java
|
asf20
| 703
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Room {
public String id;
public String name;
public String floor;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Room.java
|
Java
|
asf20
| 742
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class Track {
public String name;
public String color;
@SerializedName("abstract")
public String _abstract;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Track.java
|
Java
|
asf20
| 833
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Announcement {
public String date;
public String[] tracks;
public String title;
public String link;
public String summary;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Announcement.java
|
Java
|
asf20
| 806
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SessionsResult {
public Event[] events;
public String event_type;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/SessionsResult.java
|
Java
|
asf20
| 737
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.JsonElement;
public class GenericResponse {
public JsonElement error;
//
// public void checkResponseForAuthErrorsAndThrow() throws IOException {
// if (error != null && error.isJsonObject()) {
// JsonObject errorObject = error.getAsJsonObject();
// int errorCode = errorObject.get("code").getAsInt();
// String errorMessage = errorObject.get("message").getAsString();
// if (400 <= errorCode && errorCode < 500) {
// // The API currently only returns 400 unfortunately.
// throw ...
// }
// }
// }
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/GenericResponse.java
|
Java
|
asf20
| 1,282
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
import com.google.gson.annotations.SerializedName;
public class SpeakersResponse extends GenericResponse {
@SerializedName("devsite_speakers")
public Speaker[] speakers;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/SpeakersResponse.java
|
Java
|
asf20
| 830
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Day {
public String date;
public TimeSlot[] slot;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Day.java
|
Java
|
asf20
| 721
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class Rooms {
public Room[] rooms;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/Rooms.java
|
Java
|
asf20
| 697
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class ErrorResponse {
public Errors error;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/ErrorResponse.java
|
Java
|
asf20
| 705
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class MyScheduleResponse extends GenericResponse {
public MyScheduleItem[] schedule_list;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/MyScheduleResponse.java
|
Java
|
asf20
| 753
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class EditMyScheduleResponse {
public String message;
public boolean success;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/EditMyScheduleResponse.java
|
Java
|
asf20
| 745
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io.model;
public class SessionsResponse extends GenericResponse {
public SessionsResult[] result;
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/model/SessionsResponse.java
|
Java
|
asf20
| 743
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.MyScheduleItem;
import com.google.android.apps.iosched.io.model.MyScheduleResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses "my schedule" JSON data into a list of content provider operations.
*/
public class MyScheduleHandler extends JSONHandler {
private static final String TAG = makeLogTag(MyScheduleHandler.class);
public MyScheduleHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
MyScheduleResponse response = new Gson().fromJson(json, MyScheduleResponse.class);
if (response.error == null) {
LOGI(TAG, "Updating user's schedule");
if (response.schedule_list != null) {
// Un-star all sessions first
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.withValue(Sessions.SESSION_STARRED, 0)
.build());
// Star only those sessions in the "my schedule" response
for (MyScheduleItem item : response.schedule_list) {
batch.add(ContentProviderOperation
.newUpdate(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildSessionUri(item.session_id)))
.withValue(Sessions.SESSION_STARRED, 1)
.build());
}
}
}
return batch;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/MyScheduleHandler.java
|
Java
|
asf20
| 2,876
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.SearchSuggestions;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.app.SearchManager;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses search suggestions JSON data into a list of content provider operations.
*/
public class SearchSuggestHandler extends JSONHandler {
public SearchSuggestHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SearchSuggestions suggestions = new Gson().fromJson(json, SearchSuggestions.class);
if (suggestions.words != null) {
// Clear out suggestions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.build());
// Rebuild suggestions
for (String word : suggestions.words) {
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.SearchSuggest.CONTENT_URI))
.withValue(SearchManager.SUGGEST_COLUMN_TEXT_1, word)
.build());
}
}
return batch;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/SearchSuggestHandler.java
|
Java
|
asf20
| 2,323
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import java.io.IOException;
/**
* General {@link IOException} that indicates a problem occurred while parsing or applying a {@link
* JSONHandler}.
*/
public class HandlerException extends IOException {
public HandlerException() {
super();
}
public HandlerException(String message) {
super(message);
}
public HandlerException(String message, Throwable cause) {
super(message);
initCause(cause);
}
@Override
public String toString() {
if (getCause() != null) {
return getLocalizedMessage() + ": " + getCause();
} else {
return getLocalizedMessage();
}
}
public static class UnauthorizedException extends HandlerException {
public UnauthorizedException() {
}
public UnauthorizedException(String message) {
super(message);
}
public UnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
}
public static class NoDevsiteProfileException extends HandlerException {
public NoDevsiteProfileException() {
}
public NoDevsiteProfileException(String message) {
super(message);
}
public NoDevsiteProfileException(String message, Throwable cause) {
super(message, cause);
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/HandlerException.java
|
Java
|
asf20
| 2,022
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.Event;
import com.google.android.apps.iosched.io.model.SessionsResponse;
import com.google.android.apps.iosched.io.model.SessionsResult;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.text.format.Time;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import static com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses session JSON data into a list of content provider operations.
*/
public class SessionsHandler extends JSONHandler {
private static final String TAG = makeLogTag(SessionsHandler.class);
private static final String BASE_SESSION_URL
= "https://developers.google.com/events/io/sessions/";
private static final String EVENT_TYPE_KEYNOTE = "keynote";
private static final String EVENT_TYPE_CODELAB = "codelab";
private static final int PARSE_FLAG_FORCE_SCHEDULE_REMOVE = 1;
private static final int PARSE_FLAG_FORCE_SCHEDULE_ADD = 2;
private static final Time sTime = new Time();
private static final Pattern sRemoveSpeakerIdPrefixPattern = Pattern.compile(".*//");
private boolean mLocal;
private boolean mThrowIfNoAuthToken;
public SessionsHandler(Context context, boolean local, boolean throwIfNoAuthToken) {
super(context);
mLocal = local;
mThrowIfNoAuthToken = throwIfNoAuthToken;
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SessionsResponse response = new Gson().fromJson(json, SessionsResponse.class);
int numEvents = 0;
if (response.result != null) {
numEvents = response.result[0].events.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating sessions data");
// by default retain locally starred if local sync
boolean retainLocallyStarredSessions = mLocal;
if (response.error != null && response.error.isJsonPrimitive()) {
String errorMessageLower = response.error.getAsString().toLowerCase();
if (!mLocal && (errorMessageLower.contains("no profile")
|| errorMessageLower.contains("no auth token"))) {
// There was some authentication issue; retain locally starred sessions.
retainLocallyStarredSessions = true;
LOGW(TAG, "The user has no developers.google.com profile or this call is "
+ "not authenticated. Retaining locally starred sessions.");
}
if (mThrowIfNoAuthToken && errorMessageLower.contains("no auth token")) {
throw new HandlerException.UnauthorizedException("No auth token but we tried "
+ "authenticating. Need to invalidate the auth token.");
}
}
Set<String> starredSessionIds = new HashSet<String>();
if (retainLocallyStarredSessions) {
// Collect the list of current starred sessions
Cursor starredSessionsCursor = mContext.getContentResolver().query(
Sessions.CONTENT_STARRED_URI,
new String[]{ScheduleContract.Sessions.SESSION_ID},
null, null, null);
while (starredSessionsCursor.moveToNext()) {
starredSessionIds.add(starredSessionsCursor.getString(0));
}
starredSessionsCursor.close();
}
// Clear out existing sessions
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.CONTENT_URI))
.build());
// Maintain a list of created block IDs
Set<String> blockIds = new HashSet<String>();
for (SessionsResult result : response.result) {
for (Event event : result.events) {
int flags = 0;
if (retainLocallyStarredSessions) {
flags = (starredSessionIds.contains(event.id)
? PARSE_FLAG_FORCE_SCHEDULE_ADD
: PARSE_FLAG_FORCE_SCHEDULE_REMOVE);
}
String sessionId = event.id;
if (TextUtils.isEmpty(sessionId)) {
LOGW(TAG, "Found session with empty ID in API response.");
continue;
}
// Session title
String sessionTitle = event.title;
if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
sessionTitle = mContext.getString(
R.string.codelab_title_template, sessionTitle);
}
// Whether or not it's in the schedule
boolean inSchedule = "Y".equals(event.attending);
if ((flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0
|| (flags & PARSE_FLAG_FORCE_SCHEDULE_REMOVE) != 0) {
inSchedule = (flags & PARSE_FLAG_FORCE_SCHEDULE_ADD) != 0;
}
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
// Keynotes are always in your schedule.
inSchedule = true;
}
// Re-order session tracks so that Code Lab is last
if (event.track != null) {
Arrays.sort(event.track, sTracksComparator);
}
// Hashtags
String hashtags = "";
if (event.track != null) {
StringBuilder hashtagsBuilder = new StringBuilder();
for (String trackName : event.track) {
if (trackName.trim().startsWith("Code Lab")) {
trackName = "Code Labs";
}
if (trackName.contains("Keynote")) {
continue;
}
hashtagsBuilder.append(" #");
hashtagsBuilder.append(
ScheduleContract.Tracks.generateTrackId(trackName));
}
hashtags = hashtagsBuilder.toString().trim();
}
// Pre-reqs
String prereqs = "";
if (event.prereq != null && event.prereq.length > 0) {
StringBuilder sb = new StringBuilder();
for (String prereq : event.prereq) {
sb.append(prereq);
sb.append(" ");
}
prereqs = sb.toString();
if (prereqs.startsWith("<br>")) {
prereqs = prereqs.substring(4);
}
}
String youtubeUrl = null;
if (event.youtube_url != null && event.youtube_url.length > 0) {
youtubeUrl = event.youtube_url[0];
}
// Insert session info
final ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Sessions.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Sessions.SESSION_ID, sessionId)
.withValue(Sessions.SESSION_TYPE, result.event_type)
.withValue(Sessions.SESSION_LEVEL, event.level)
.withValue(Sessions.SESSION_TITLE, sessionTitle)
.withValue(Sessions.SESSION_ABSTRACT, event._abstract)
.withValue(Sessions.SESSION_TAGS, event.tags)
.withValue(Sessions.SESSION_URL, makeSessionUrl(sessionId))
.withValue(Sessions.SESSION_LIVESTREAM_URL, event.livestream_url)
.withValue(Sessions.SESSION_REQUIREMENTS, prereqs)
.withValue(Sessions.SESSION_STARRED, inSchedule)
.withValue(Sessions.SESSION_HASHTAGS, hashtags)
.withValue(Sessions.SESSION_YOUTUBE_URL, youtubeUrl)
.withValue(Sessions.SESSION_PDF_URL, "")
.withValue(Sessions.SESSION_NOTES_URL, "")
.withValue(Sessions.ROOM_ID, sanitizeId(event.room));
long sessionStartTime = parseTime(event.start_date, event.start_time);
long sessionEndTime = parseTime(event.end_date, event.end_time);
String blockId = ScheduleContract.Blocks.generateBlockId(
sessionStartTime, sessionEndTime);
if (!blockIds.contains(blockId)) {
String blockType;
String blockTitle;
if (EVENT_TYPE_KEYNOTE.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_KEYNOTE;
blockTitle = mContext.getString(R.string.schedule_block_title_keynote);
} else if (EVENT_TYPE_CODELAB.equals(result.event_type)) {
blockType = ParserUtils.BLOCK_TYPE_CODE_LAB;
blockTitle = mContext
.getString(R.string.schedule_block_title_code_labs);
} else {
blockType = ParserUtils.BLOCK_TYPE_SESSION;
blockTitle = mContext.getString(R.string.schedule_block_title_sessions);
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract.Blocks.CONTENT_URI)
.withValue(ScheduleContract.Blocks.BLOCK_ID, blockId)
.withValue(ScheduleContract.Blocks.BLOCK_TYPE, blockType)
.withValue(ScheduleContract.Blocks.BLOCK_TITLE, blockTitle)
.withValue(ScheduleContract.Blocks.BLOCK_START, sessionStartTime)
.withValue(ScheduleContract.Blocks.BLOCK_END, sessionEndTime)
.build());
blockIds.add(blockId);
}
builder.withValue(Sessions.BLOCK_ID, blockId);
batch.add(builder.build());
// Replace all session speakers
final Uri sessionSpeakersUri = Sessions.buildSpeakersDirUri(sessionId);
batch.add(ContentProviderOperation
.newDelete(ScheduleContract
.addCallerIsSyncAdapterParameter(sessionSpeakersUri))
.build());
if (event.speaker_id != null) {
for (String speakerId : event.speaker_id) {
speakerId = sRemoveSpeakerIdPrefixPattern.matcher(speakerId).replaceAll(
"");
batch.add(ContentProviderOperation.newInsert(sessionSpeakersUri)
.withValue(SessionsSpeakers.SESSION_ID, sessionId)
.withValue(SessionsSpeakers.SPEAKER_ID, speakerId).build());
}
}
// Replace all session tracks
final Uri sessionTracksUri = ScheduleContract.addCallerIsSyncAdapterParameter(
Sessions.buildTracksDirUri(sessionId));
batch.add(ContentProviderOperation.newDelete(sessionTracksUri).build());
if (event.track != null) {
for (String trackName : event.track) {
if (trackName.contains("Code Lab")) {
trackName = "Code Labs";
}
String trackId = ScheduleContract.Tracks.generateTrackId(trackName);
batch.add(ContentProviderOperation.newInsert(sessionTracksUri)
.withValue(SessionsTracks.SESSION_ID, sessionId)
.withValue(SessionsTracks.TRACK_ID, trackId).build());
}
}
}
}
}
return batch;
}
private Comparator<String> sTracksComparator = new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
// TODO: improve performance of this comparator
return (s1.contains("Code Lab") ? "z" : s1).compareTo(
(s2.contains("Code Lab") ? "z" : s2));
}
};
private String makeSessionUrl(String sessionId) {
if (TextUtils.isEmpty(sessionId)) {
return null;
}
return BASE_SESSION_URL + sessionId;
}
private static long parseTime(String date, String time) {
//change to this format : 2011-05-10T07:00:00.000-07:00
int index = time.indexOf(":");
if (index == 1) {
time = "0" + time;
}
final String composed = String.format("%sT%s:00.000-07:00", date, time);
//return sTimeFormat.parse(composed).getTime();
sTime.parse3339(composed);
return sTime.toMillis(false);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/SessionsHandler.java
|
Java
|
asf20
| 15,809
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Speaker;
import com.google.android.apps.iosched.io.model.SpeakersResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses speaker JSON data into a list of content provider operations.
*/
public class SpeakersHandler extends JSONHandler {
private static final String TAG = makeLogTag(SpeakersHandler.class);
public SpeakersHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SpeakersResponse response = new Gson().fromJson(json, SpeakersResponse.class);
int numEvents = 0;
if (response.speakers != null) {
numEvents = response.speakers.length;
}
if (numEvents > 0) {
LOGI(TAG, "Updating speakers data");
// Clear out existing speakers
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Speakers.CONTENT_URI))
.build());
for (Speaker speaker : response.speakers) {
String speakerId = speaker.user_id;
// Insert speaker info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Speakers.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Speakers.SPEAKER_ID, speakerId)
.withValue(Speakers.SPEAKER_NAME, speaker.display_name)
.withValue(Speakers.SPEAKER_ABSTRACT, speaker.bio)
.withValue(Speakers.SPEAKER_IMAGE_URL, speaker.thumbnail_url)
.withValue(Speakers.SPEAKER_URL, speaker.plusone_url)
.build());
}
}
return batch;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/SpeakersHandler.java
|
Java
|
asf20
| 3,289
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
/**
* An abstract object that is in charge of parsing JSON data with a given, known structure, into
* a list of content provider operations (inserts, updates, etc.) representing the data.
*/
public abstract class JSONHandler {
protected static Context mContext;
protected JSONHandler(Context context) {
mContext = context;
}
public abstract ArrayList<ContentProviderOperation> parse(String json) throws IOException;
/**
* Loads the JSON text resource with the given ID and returns the JSON content.
*/
public static String loadResourceJson(Context context, int resource) throws IOException {
InputStream is = context.getResources().openRawResource(resource);
Writer writer = new StringWriter();
char[] buffer = new char[1024];
try {
Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} finally {
is.close();
}
return writer.toString();
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/JSONHandler.java
|
Java
|
asf20
| 2,074
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.model.SandboxCompany;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.text.TextUtils;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Handler that parses developer sandbox JSON data into a list of content provider operations.
*/
public class SandboxHandler extends JSONHandler {
private static final String TAG = makeLogTag(SandboxHandler.class);
private static final String BASE_LOGO_URL
= "http://commondatastorage.googleapis.com/io2012/sandbox%20logos/";
public SandboxHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
SandboxCompany[] companies = new Gson().fromJson(json, SandboxCompany[].class);
if (companies.length > 0) {
LOGI(TAG, "Updating developer sandbox data");
// Clear out existing sandbox companies
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Vendors.CONTENT_URI))
.build());
StringBuilder companyDescription = new StringBuilder();
String exhibitorsPrefix = mContext.getString(R.string.vendor_exhibitors_prefix);
for (SandboxCompany company : companies) {
// Insert sandbox company info
String website = company.website;
if (!TextUtils.isEmpty(website) && !website.startsWith("http")) {
website = "http://" + website;
}
companyDescription.setLength(0);
if (company.exhibitors != null && company.exhibitors.length > 0) {
companyDescription.append(exhibitorsPrefix);
companyDescription.append(" ");
for (int i = 0; i < company.exhibitors.length; i++) {
companyDescription.append(company.exhibitors[i]);
if (i >= company.exhibitors.length - 1) {
break;
}
companyDescription.append(", ");
}
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.company_description)) {
companyDescription.append(company.company_description);
companyDescription.append("\n\n");
}
if (!TextUtils.isEmpty(company.product_description)) {
companyDescription.append(company.product_description);
}
// Clean up logo URL
String logoUrl = null;
if (!TextUtils.isEmpty(company.logo_img)) {
logoUrl = company.logo_img.replaceAll(" ", "%20");
if (!logoUrl.startsWith("http")) {
logoUrl = BASE_LOGO_URL + logoUrl;
}
}
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Vendors.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
.withValue(Vendors.VENDOR_ID,
Vendors.generateVendorId(company.company_name))
.withValue(Vendors.VENDOR_NAME, company.company_name)
.withValue(Vendors.VENDOR_DESC, companyDescription.toString())
.withValue(Vendors.VENDOR_PRODUCT_DESC, null) // merged into company desc
.withValue(Vendors.VENDOR_LOGO_URL, logoUrl)
.withValue(Vendors.VENDOR_URL, website)
.withValue(Vendors.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(company.product_pod))
.build());
}
}
return batch;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/SandboxHandler.java
|
Java
|
asf20
| 5,369
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import com.google.android.apps.iosched.io.model.Announcement;
import com.google.android.apps.iosched.io.model.AnnouncementsResponse;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
/**
* Handler that parses announcements JSON data into a list of content provider operations.
*/
public class AnnouncementsHandler extends JSONHandler {
private static final String TAG = makeLogTag(AnnouncementsHandler.class);
public AnnouncementsHandler(Context context, boolean local) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
AnnouncementsResponse response = new Gson().fromJson(json, AnnouncementsResponse.class);
int numAnnouncements = 0;
if (response.announcements != null) {
numAnnouncements = response.announcements.length;
}
if (numAnnouncements > 0) {
LOGI(TAG, "Updating announcements data");
// Clear out existing announcements
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.addCallerIsSyncAdapterParameter(
Announcements.CONTENT_URI))
.build());
for (Announcement announcement : response.announcements) {
// Save tracks as a json array
final String tracks =
(announcement.tracks != null && announcement.tracks.length > 0)
? new Gson().toJson(announcement.tracks)
: null;
// Insert announcement info
batch.add(ContentProviderOperation
.newInsert(ScheduleContract
.addCallerIsSyncAdapterParameter(Announcements.CONTENT_URI))
.withValue(SyncColumns.UPDATED, System.currentTimeMillis())
// TODO: better announcements ID heuristic
.withValue(Announcements.ANNOUNCEMENT_ID,
(announcement.date + announcement.title).hashCode())
.withValue(Announcements.ANNOUNCEMENT_DATE, announcement.date)
.withValue(Announcements.ANNOUNCEMENT_TITLE, announcement.title)
.withValue(Announcements.ANNOUNCEMENT_SUMMARY, announcement.summary)
.withValue(Announcements.ANNOUNCEMENT_URL, announcement.link)
.withValue(Announcements.ANNOUNCEMENT_TRACKS, tracks)
.build());
}
}
return batch;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/AnnouncementsHandler.java
|
Java
|
asf20
| 4,016
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Day;
import com.google.android.apps.iosched.io.model.EventSlots;
import com.google.android.apps.iosched.io.model.TimeSlot;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.util.Lists;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class BlocksHandler extends JSONHandler {
private static final String TAG = makeLogTag(BlocksHandler.class);
public BlocksHandler(Context context) {
super(context);
}
public ArrayList<ContentProviderOperation> parse(String json) throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
try {
Gson gson = new Gson();
EventSlots eventSlots = gson.fromJson(json, EventSlots.class);
int numDays = eventSlots.day.length;
//2011-05-10T07:00:00.000-07:00
for (int i = 0; i < numDays; i++) {
Day day = eventSlots.day[i];
String date = day.date;
TimeSlot[] timeSlots = day.slot;
for (TimeSlot timeSlot : timeSlots) {
parseSlot(date, timeSlot, batch);
}
}
} catch (Throwable e) {
LOGE(TAG, e.toString());
}
return batch;
}
private static void parseSlot(String date, TimeSlot slot,
ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation
.newInsert(ScheduleContract.addCallerIsSyncAdapterParameter(Blocks.CONTENT_URI));
//LOGD(TAG, "Inside parseSlot:" + date + ", " + slot);
String start = slot.start;
String end = slot.end;
String type = "N_D";
if (slot.type != null) {
type = slot.type;
}
String title = "N_D";
if (slot.title != null) {
title = slot.title;
}
String startTime = date + "T" + start + ":00.000-07:00";
String endTime = date + "T" + end + ":00.000-07:00";
LOGV(TAG, "startTime:" + startTime);
long startTimeL = ParserUtils.parseTime(startTime);
long endTimeL = ParserUtils.parseTime(endTime);
final String blockId = Blocks.generateBlockId(startTimeL, endTimeL);
LOGV(TAG, "blockId:" + blockId);
LOGV(TAG, "title:" + title);
LOGV(TAG, "start:" + startTimeL);
builder.withValue(Blocks.BLOCK_ID, blockId);
builder.withValue(Blocks.BLOCK_TITLE, title);
builder.withValue(Blocks.BLOCK_START, startTimeL);
builder.withValue(Blocks.BLOCK_END, endTimeL);
builder.withValue(Blocks.BLOCK_TYPE, type);
builder.withValue(Blocks.BLOCK_META, slot.meta);
batch.add(builder.build());
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/BlocksHandler.java
|
Java
|
asf20
| 3,937
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.io;
import com.google.android.apps.iosched.io.model.Track;
import com.google.android.apps.iosched.io.model.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.Lists;
import com.google.gson.Gson;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.graphics.Color;
import java.io.IOException;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
import static com.google.android.apps.iosched.util.ParserUtils.sanitizeId;
/**
* Handler that parses track JSON data into a list of content provider operations.
*/
public class TracksHandler extends JSONHandler {
private static final String TAG = makeLogTag(TracksHandler.class);
public TracksHandler(Context context) {
super(context);
}
@Override
public ArrayList<ContentProviderOperation> parse(String json)
throws IOException {
final ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
batch.add(ContentProviderOperation.newDelete(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI)).build());
Tracks tracksJson = new Gson().fromJson(json, Tracks.class);
int noOfTracks = tracksJson.getTrack().length;
for (int i = 0; i < noOfTracks; i++) {
parseTrack(tracksJson.getTrack()[i], batch);
}
return batch;
}
private static void parseTrack(Track track, ArrayList<ContentProviderOperation> batch) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
ScheduleContract.addCallerIsSyncAdapterParameter(
ScheduleContract.Tracks.CONTENT_URI));
builder.withValue(ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.generateTrackId(track.name));
builder.withValue(ScheduleContract.Tracks.TRACK_NAME, track.name);
builder.withValue(ScheduleContract.Tracks.TRACK_COLOR, Color.parseColor(track.color));
builder.withValue(ScheduleContract.Tracks.TRACK_ABSTRACT, track._abstract);
batch.add(builder.build());
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/io/TracksHandler.java
|
Java
|
asf20
| 2,895
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.AnnouncementsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.BlocksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.RoomsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.SessionsColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.SpeakersColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.SyncColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.TracksColumns;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleContract.VendorsColumns;
import android.app.SearchManager;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for managing {@link SQLiteDatabase} that stores data for
* {@link ScheduleProvider}.
*/
public class ScheduleDatabase extends SQLiteOpenHelper {
private static final String TAG = makeLogTag(ScheduleDatabase.class);
private static final String DATABASE_NAME = "schedule.db";
// NOTE: carefully update onUpgrade() when bumping database versions to make
// sure user data is saved.
private static final int VER_LAUNCH = 25;
private static final int VER_SESSION_TYPE = 26;
private static final int DATABASE_VERSION = VER_SESSION_TYPE;
interface Tables {
String BLOCKS = "blocks";
String TRACKS = "tracks";
String ROOMS = "rooms";
String SESSIONS = "sessions";
String SPEAKERS = "speakers";
String SESSIONS_SPEAKERS = "sessions_speakers";
String SESSIONS_TRACKS = "sessions_tracks";
String VENDORS = "vendors";
String ANNOUNCEMENTS = "announcements";
String SESSIONS_SEARCH = "sessions_search";
String SEARCH_SUGGEST = "search_suggest";
String SESSIONS_JOIN_BLOCKS_ROOMS = "sessions "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_ROOMS = "sessions "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String VENDORS_JOIN_TRACKS = "vendors "
+ "LEFT OUTER JOIN tracks ON vendors.track_id=tracks.track_id";
String SESSIONS_SPEAKERS_JOIN_SPEAKERS = "sessions_speakers "
+ "LEFT OUTER JOIN speakers ON sessions_speakers.speaker_id=speakers.speaker_id";
String SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_speakers "
+ "LEFT OUTER JOIN sessions ON sessions_speakers.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_TRACKS_JOIN_TRACKS = "sessions_tracks "
+ "LEFT OUTER JOIN tracks ON sessions_tracks.track_id=tracks.track_id";
String SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_tracks "
+ "LEFT OUTER JOIN sessions ON sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS = "sessions_search "
+ "LEFT OUTER JOIN sessions ON sessions_search.session_id=sessions.session_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id "
+ "LEFT OUTER JOIN rooms ON sessions.room_id=rooms.room_id";
String SESSIONS_JOIN_TRACKS_JOIN_BLOCKS = "sessions "
+ "LEFT OUTER JOIN sessions_tracks ON "
+ "sessions_tracks.session_id=sessions.session_id "
+ "LEFT OUTER JOIN tracks ON tracks.track_id=sessions_tracks.track_id "
+ "LEFT OUTER JOIN blocks ON sessions.block_id=blocks.block_id";
String BLOCKS_JOIN_SESSIONS = "blocks "
+ "LEFT OUTER JOIN sessions ON blocks.block_id=sessions.block_id";
}
private interface Triggers {
String SESSIONS_SEARCH_INSERT = "sessions_search_insert";
String SESSIONS_SEARCH_DELETE = "sessions_search_delete";
String SESSIONS_SEARCH_UPDATE = "sessions_search_update";
// Deletes from session_tracks when corresponding sessions are deleted.
String SESSIONS_TRACKS_DELETE = "sessions_tracks_delete";
}
public interface SessionsSpeakers {
String SESSION_ID = "session_id";
String SPEAKER_ID = "speaker_id";
}
public interface SessionsTracks {
String SESSION_ID = "session_id";
String TRACK_ID = "track_id";
}
interface SessionsSearchColumns {
String SESSION_ID = "session_id";
String BODY = "body";
}
/** Fully-qualified field names. */
private interface Qualified {
String SESSIONS_SEARCH_SESSION_ID = Tables.SESSIONS_SEARCH + "."
+ SessionsSearchColumns.SESSION_ID;
String SESSIONS_SEARCH = Tables.SESSIONS_SEARCH + "(" + SessionsSearchColumns.SESSION_ID
+ "," + SessionsSearchColumns.BODY + ")";
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
}
/** {@code REFERENCES} clauses. */
private interface References {
String BLOCK_ID = "REFERENCES " + Tables.BLOCKS + "(" + Blocks.BLOCK_ID + ")";
String TRACK_ID = "REFERENCES " + Tables.TRACKS + "(" + Tracks.TRACK_ID + ")";
String ROOM_ID = "REFERENCES " + Tables.ROOMS + "(" + Rooms.ROOM_ID + ")";
String SESSION_ID = "REFERENCES " + Tables.SESSIONS + "(" + Sessions.SESSION_ID + ")";
String SPEAKER_ID = "REFERENCES " + Tables.SPEAKERS + "(" + Speakers.SPEAKER_ID + ")";
String VENDOR_ID = "REFERENCES " + Tables.VENDORS + "(" + Vendors.VENDOR_ID + ")";
}
private interface Subquery {
/**
* Subquery used to build the {@link SessionsSearchColumns#BODY} string
* used for indexing {@link Sessions} content.
*/
String SESSIONS_BODY = "(new." + Sessions.SESSION_TITLE
+ "||'; '||new." + Sessions.SESSION_ABSTRACT
+ "||'; '||" + "coalesce(new." + Sessions.SESSION_TAGS + ", '')"
+ ")";
}
public ScheduleDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + Tables.BLOCKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ BlocksColumns.BLOCK_ID + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_TITLE + " TEXT NOT NULL,"
+ BlocksColumns.BLOCK_START + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_END + " INTEGER NOT NULL,"
+ BlocksColumns.BLOCK_TYPE + " TEXT,"
+ BlocksColumns.BLOCK_META + " TEXT,"
+ "UNIQUE (" + BlocksColumns.BLOCK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ TracksColumns.TRACK_ID + " TEXT NOT NULL,"
+ TracksColumns.TRACK_NAME + " TEXT,"
+ TracksColumns.TRACK_COLOR + " INTEGER,"
+ TracksColumns.TRACK_ABSTRACT + " TEXT,"
+ "UNIQUE (" + TracksColumns.TRACK_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ROOMS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ RoomsColumns.ROOM_ID + " TEXT NOT NULL,"
+ RoomsColumns.ROOM_NAME + " TEXT,"
+ RoomsColumns.ROOM_FLOOR + " TEXT,"
+ "UNIQUE (" + RoomsColumns.ROOM_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SessionsColumns.SESSION_ID + " TEXT NOT NULL,"
+ Sessions.BLOCK_ID + " TEXT " + References.BLOCK_ID + ","
+ Sessions.ROOM_ID + " TEXT " + References.ROOM_ID + ","
+ SessionsColumns.SESSION_TYPE + " TEXT,"
+ SessionsColumns.SESSION_LEVEL + " TEXT,"
+ SessionsColumns.SESSION_TITLE + " TEXT,"
+ SessionsColumns.SESSION_ABSTRACT + " TEXT,"
+ SessionsColumns.SESSION_REQUIREMENTS + " TEXT,"
+ SessionsColumns.SESSION_TAGS + " TEXT,"
+ SessionsColumns.SESSION_HASHTAGS + " TEXT,"
+ SessionsColumns.SESSION_URL + " TEXT,"
+ SessionsColumns.SESSION_YOUTUBE_URL + " TEXT,"
+ SessionsColumns.SESSION_PDF_URL + " TEXT,"
+ SessionsColumns.SESSION_NOTES_URL + " TEXT,"
+ SessionsColumns.SESSION_STARRED + " INTEGER NOT NULL DEFAULT 0,"
+ SessionsColumns.SESSION_CAL_EVENT_ID + " INTEGER,"
+ SessionsColumns.SESSION_LIVESTREAM_URL + " TEXT,"
+ "UNIQUE (" + SessionsColumns.SESSION_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ SpeakersColumns.SPEAKER_ID + " TEXT NOT NULL,"
+ SpeakersColumns.SPEAKER_NAME + " TEXT,"
+ SpeakersColumns.SPEAKER_IMAGE_URL + " TEXT,"
+ SpeakersColumns.SPEAKER_COMPANY + " TEXT,"
+ SpeakersColumns.SPEAKER_ABSTRACT + " TEXT,"
+ SpeakersColumns.SPEAKER_URL + " TEXT,"
+ "UNIQUE (" + SpeakersColumns.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_SPEAKERS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSpeakers.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + " TEXT NOT NULL " + References.SPEAKER_ID + ","
+ "UNIQUE (" + SessionsSpeakers.SESSION_ID + ","
+ SessionsSpeakers.SPEAKER_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.SESSIONS_TRACKS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsTracks.SESSION_ID + " TEXT NOT NULL " + References.SESSION_ID + ","
+ SessionsTracks.TRACK_ID + " TEXT NOT NULL " + References.TRACK_ID
+ ")");
db.execSQL("CREATE TABLE " + Tables.VENDORS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ VendorsColumns.VENDOR_ID + " TEXT NOT NULL,"
+ Vendors.TRACK_ID + " TEXT " + References.TRACK_ID + ","
+ VendorsColumns.VENDOR_NAME + " TEXT,"
+ VendorsColumns.VENDOR_LOCATION + " TEXT,"
+ VendorsColumns.VENDOR_DESC + " TEXT,"
+ VendorsColumns.VENDOR_URL + " TEXT,"
+ VendorsColumns.VENDOR_PRODUCT_DESC + " TEXT,"
+ VendorsColumns.VENDOR_LOGO_URL + " TEXT,"
+ VendorsColumns.VENDOR_STARRED + " INTEGER,"
+ "UNIQUE (" + VendorsColumns.VENDOR_ID + ") ON CONFLICT REPLACE)");
db.execSQL("CREATE TABLE " + Tables.ANNOUNCEMENTS + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SyncColumns.UPDATED + " INTEGER NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_ID + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TITLE + " TEXT NOT NULL,"
+ AnnouncementsColumns.ANNOUNCEMENT_SUMMARY + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_TRACKS + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_URL + " TEXT,"
+ AnnouncementsColumns.ANNOUNCEMENT_DATE + " INTEGER NOT NULL)");
createSessionsSearch(db);
createSessionsDeleteTriggers(db);
db.execSQL("CREATE TABLE " + Tables.SEARCH_SUGGEST + " ("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SearchManager.SUGGEST_COLUMN_TEXT_1 + " TEXT NOT NULL)");
}
/**
* Create triggers that automatically build {@link Tables#SESSIONS_SEARCH}
* as values are changed in {@link Tables#SESSIONS}.
*/
private static void createSessionsSearch(SQLiteDatabase db) {
// Using the "porter" tokenizer for simple stemming, so that
// "frustration" matches "frustrated."
db.execSQL("CREATE VIRTUAL TABLE " + Tables.SESSIONS_SEARCH + " USING fts3("
+ BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ SessionsSearchColumns.BODY + " TEXT NOT NULL,"
+ SessionsSearchColumns.SESSION_ID
+ " TEXT NOT NULL " + References.SESSION_ID + ","
+ "UNIQUE (" + SessionsSearchColumns.SESSION_ID + ") ON CONFLICT REPLACE,"
+ "tokenize=porter)");
// TODO: handle null fields in body, which cause trigger to fail
// TODO: implement update trigger, not currently exercised
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_INSERT + " AFTER INSERT ON "
+ Tables.SESSIONS + " BEGIN INSERT INTO " + Qualified.SESSIONS_SEARCH + " "
+ " VALUES(new." + Sessions.SESSION_ID + ", " + Subquery.SESSIONS_BODY + ");"
+ " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_SEARCH + " "
+ " WHERE " + Qualified.SESSIONS_SEARCH_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_SEARCH_UPDATE
+ " AFTER UPDATE ON " + Tables.SESSIONS
+ " BEGIN UPDATE sessions_search SET " + SessionsSearchColumns.BODY + " = "
+ Subquery.SESSIONS_BODY + " WHERE session_id = old.session_id"
+ "; END;");
}
private void createSessionsDeleteTriggers(SQLiteDatabase db) {
db.execSQL("CREATE TRIGGER " + Triggers.SESSIONS_TRACKS_DELETE + " AFTER DELETE ON "
+ Tables.SESSIONS + " BEGIN DELETE FROM " + Tables.SESSIONS_TRACKS + " "
+ " WHERE " + Qualified.SESSIONS_TRACKS_SESSION_ID + "=old." + Sessions.SESSION_ID
+ ";" + " END;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
LOGD(TAG, "onUpgrade() from " + oldVersion + " to " + newVersion);
// NOTE: This switch statement is designed to handle cascading database
// updates, starting at the current version and falling through to all
// future upgrade cases. Only use "break;" when you want to drop and
// recreate the entire database.
int version = oldVersion;
switch (version) {
case VER_LAUNCH:
// VER_SESSION_TYPE added column for session feedback URL.
db.execSQL("ALTER TABLE " + Tables.SESSIONS + " ADD COLUMN "
+ SessionsColumns.SESSION_TYPE + " TEXT");
version = VER_SESSION_TYPE;
}
LOGD(TAG, "after upgrade logic, at version " + version);
if (version != DATABASE_VERSION) {
LOGW(TAG, "Destroying old data during upgrade");
db.execSQL("DROP TABLE IF EXISTS " + Tables.BLOCKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ROOMS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SPEAKERS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_TRACKS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.VENDORS);
db.execSQL("DROP TABLE IF EXISTS " + Tables.ANNOUNCEMENTS);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_INSERT);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_DELETE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_SEARCH_UPDATE);
db.execSQL("DROP TRIGGER IF EXISTS " + Triggers.SESSIONS_TRACKS_DELETE);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SESSIONS_SEARCH);
db.execSQL("DROP TABLE IF EXISTS " + Tables.SEARCH_SUGGEST);
onCreate(db);
}
}
public static void deleteDatabase(Context context) {
context.deleteDatabase(DATABASE_NAME);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/provider/ScheduleDatabase.java
|
Java
|
asf20
| 18,575
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.provider.ScheduleContract.Announcements;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.provider.ScheduleContract.SearchSuggest;
import com.google.android.apps.iosched.provider.ScheduleContract.Sessions;
import com.google.android.apps.iosched.provider.ScheduleContract.Speakers;
import com.google.android.apps.iosched.provider.ScheduleContract.Tracks;
import com.google.android.apps.iosched.provider.ScheduleContract.Vendors;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSearchColumns;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsSpeakers;
import com.google.android.apps.iosched.provider.ScheduleDatabase.SessionsTracks;
import com.google.android.apps.iosched.provider.ScheduleDatabase.Tables;
import com.google.android.apps.iosched.util.SelectionBuilder;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link com.google.android.apps.iosched.sync.SyncHelper}, and queried by various
* {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = makeLogTag(ScheduleProvider.class);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int BLOCKS_ID_SESSIONS_STARRED = 104;
private static final int TRACKS = 200;
private static final int TRACKS_ID = 201;
private static final int TRACKS_ID_SESSIONS = 202;
private static final int TRACKS_ID_VENDORS = 203;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_WITH_TRACK = 402;
private static final int SESSIONS_SEARCH = 403;
private static final int SESSIONS_AT = 404;
private static final int SESSIONS_ID = 405;
private static final int SESSIONS_ID_SPEAKERS = 406;
private static final int SESSIONS_ID_TRACKS = 407;
private static final int SESSIONS_ID_WITH_TRACK = 408;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_ID_SESSIONS = 502;
private static final int VENDORS = 600;
private static final int VENDORS_STARRED = 601;
private static final int VENDORS_SEARCH = 603;
private static final int VENDORS_ID = 604;
private static final int ANNOUNCEMENTS = 700;
private static final int ANNOUNCEMENTS_ID = 701;
private static final int SEARCH_SUGGEST = 800;
private static final String MIME_XML = "text/xml";
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "blocks/*/sessions/starred", BLOCKS_ID_SESSIONS_STARRED);
matcher.addURI(authority, "tracks", TRACKS);
matcher.addURI(authority, "tracks/*", TRACKS_ID);
matcher.addURI(authority, "tracks/*/sessions", TRACKS_ID_SESSIONS);
matcher.addURI(authority, "tracks/*/vendors", TRACKS_ID_VENDORS);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/with_track", SESSIONS_WITH_TRACK);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "sessions/*/speakers", SESSIONS_ID_SPEAKERS);
matcher.addURI(authority, "sessions/*/tracks", SESSIONS_ID_TRACKS);
matcher.addURI(authority, "sessions/*/with_track", SESSIONS_ID_WITH_TRACK);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "speakers/*/sessions", SPEAKERS_ID_SESSIONS);
matcher.addURI(authority, "vendors", VENDORS);
matcher.addURI(authority, "vendors/starred", VENDORS_STARRED);
matcher.addURI(authority, "vendors/search/*", VENDORS_SEARCH);
matcher.addURI(authority, "vendors/*", VENDORS_ID);
matcher.addURI(authority, "announcements", ANNOUNCEMENTS);
matcher.addURI(authority, "announcements/*", ANNOUNCEMENTS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
return matcher;
}
@Override
public boolean onCreate() {
mOpenHelper = new ScheduleDatabase(getContext());
return true;
}
private void deleteDatabase() {
// TODO: wait for content provider operations to finish, then tear down
mOpenHelper.close();
Context context = getContext();
ScheduleDatabase.deleteDatabase(context);
mOpenHelper = new ScheduleDatabase(getContext());
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case BLOCKS_ID_SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case TRACKS:
return Tracks.CONTENT_TYPE;
case TRACKS_ID:
return Tracks.CONTENT_ITEM_TYPE;
case TRACKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TRACKS_ID_VENDORS:
return Vendors.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SESSIONS_ID_SPEAKERS:
return Speakers.CONTENT_TYPE;
case SESSIONS_ID_TRACKS:
return Tracks.CONTENT_TYPE;
case SESSIONS_ID_WITH_TRACK:
return Sessions.CONTENT_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case VENDORS:
return Vendors.CONTENT_TYPE;
case VENDORS_STARRED:
return Vendors.CONTENT_TYPE;
case VENDORS_SEARCH:
return Vendors.CONTENT_TYPE;
case VENDORS_ID:
return Vendors.CONTENT_ITEM_TYPE;
case ANNOUNCEMENTS:
return Announcements.CONTENT_TYPE;
case ANNOUNCEMENTS_ID:
return Announcements.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
LOGV(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
case SEARCH_SUGGEST: {
final SelectionBuilder builder = new SelectionBuilder();
// Adjust incoming query to become SQL text match
selectionArgs[0] = selectionArgs[0] + "%";
builder.table(Tables.SEARCH_SUGGEST);
builder.where(selection, selectionArgs);
builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
SearchManager.SUGGEST_COLUMN_TEXT_1);
projection = new String[] {
BaseColumns._ID,
SearchManager.SUGGEST_COLUMN_TEXT_1,
SearchManager.SUGGEST_COLUMN_QUERY
};
final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
}
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
LOGV(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TRACKS: {
db.insertOrThrow(Tables.TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(Tracks.TRACK_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SESSIONS_ID_SPEAKERS: {
db.insertOrThrow(Tables.SESSIONS_SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(SessionsSpeakers.SPEAKER_ID));
}
case SESSIONS_ID_TRACKS: {
db.insertOrThrow(Tables.SESSIONS_TRACKS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Tracks.buildTrackUri(values.getAsString(SessionsTracks.TRACK_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
case VENDORS: {
db.insertOrThrow(Tables.VENDORS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Vendors.buildVendorUri(values.getAsString(Vendors.VENDOR_ID));
}
case ANNOUNCEMENTS: {
db.insertOrThrow(Tables.ANNOUNCEMENTS, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return Announcements.buildAnnouncementUri(values
.getAsString(Announcements.ANNOUNCEMENT_ID));
}
case SEARCH_SUGGEST: {
db.insertOrThrow(Tables.SEARCH_SUGGEST, null, values);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return SearchSuggest.CONTENT_URI;
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
LOGV(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
boolean syncToNetwork = !ScheduleContract.hasCallerIsSyncAdapterParameter(uri);
getContext().getContentResolver().notifyChange(uri, null, syncToNetwork);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
LOGV(TAG, "delete(uri=" + uri + ")");
if (uri == ScheduleContract.BASE_CONTENT_URI) {
// Handle whole database deletes (e.g. when signing out)
deleteDatabase();
getContext().getContentResolver().notifyChange(uri, null, false);
return 1;
}
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
getContext().getContentResolver().notifyChange(uri, null,
!ScheduleContract.hasCallerIsSyncAdapterParameter(uri));
return retVal;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TRACKS: {
return builder.table(Tables.TRACKS);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS);
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
case SEARCH_SUGGEST: {
return builder.table(Tables.SEARCH_SUGGEST);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder
.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.map(Blocks.STARRED_SESSION_ID, Subquery.BLOCK_STARRED_SESSION_ID)
.map(Blocks.STARRED_SESSION_TITLE, Subquery.BLOCK_STARRED_SESSION_TITLE)
.map(Blocks.STARRED_SESSION_HASHTAGS,
Subquery.BLOCK_STARRED_SESSION_HASHTAGS)
.map(Blocks.STARRED_SESSION_URL, Subquery.BLOCK_STARRED_SESSION_URL)
.map(Blocks.STARRED_SESSION_LIVESTREAM_URL,
Subquery.BLOCK_STARRED_SESSION_LIVESTREAM_URL)
.map(Blocks.STARRED_SESSION_ROOM_NAME,
Subquery.BLOCK_STARRED_SESSION_ROOM_NAME)
.map(Blocks.STARRED_SESSION_ROOM_ID, Subquery.BLOCK_STARRED_SESSION_ROOM_ID);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS_STARRED: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.NUM_STARRED_SESSIONS, Subquery.BLOCK_NUM_STARRED_SESSIONS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId)
.where(Qualified.SESSIONS_STARRED + "=1");
}
case TRACKS: {
return builder.table(Tables.TRACKS)
.map(Tracks.SESSIONS_COUNT, Subquery.TRACK_SESSIONS_COUNT)
.map(Tracks.VENDORS_COUNT, Subquery.TRACK_VENDORS_COUNT);
}
case TRACKS_ID: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.TRACKS)
.where(Tracks.TRACK_ID + "=?", trackId);
}
case TRACKS_ID_SESSIONS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_TRACKS_TRACK_ID + "=?", trackId);
}
case TRACKS_ID_VENDORS: {
final String trackId = Tracks.getTrackId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Qualified.VENDORS_TRACK_ID + "=?", trackId);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_WITH_TRACK: {
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS);
}
case SESSIONS_ID_WITH_TRACK: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_TRACKS_JOIN_BLOCKS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_NAME, Tables.TRACKS)
.mapToTable(Blocks.BLOCK_ID, Tables.BLOCKS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_SPEAKERS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SPEAKERS)
.mapToTable(Speakers._ID, Tables.SPEAKERS)
.mapToTable(Speakers.SPEAKER_ID, Tables.SPEAKERS)
.where(Qualified.SESSIONS_SPEAKERS_SESSION_ID + "=?", sessionId);
}
case SESSIONS_ID_TRACKS: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_TRACKS_JOIN_TRACKS)
.mapToTable(Tracks._ID, Tables.TRACKS)
.mapToTable(Tracks.TRACK_ID, Tables.TRACKS)
.where(Qualified.SESSIONS_TRACKS_SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_ID_SESSIONS: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SESSIONS_SPEAKERS_JOIN_SESSIONS_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SPEAKERS_SPEAKER_ID + "=?", speakerId);
}
case VENDORS: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS);
}
case VENDORS_STARRED: {
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_STARRED + "=1");
}
case VENDORS_ID: {
final String vendorId = Vendors.getVendorId(uri);
return builder.table(Tables.VENDORS_JOIN_TRACKS)
.mapToTable(Vendors._ID, Tables.VENDORS)
.mapToTable(Vendors.TRACK_ID, Tables.VENDORS)
.where(Vendors.VENDOR_ID + "=?", vendorId);
}
case ANNOUNCEMENTS: {
return builder.table(Tables.ANNOUNCEMENTS);
}
case ANNOUNCEMENTS_ID: {
final String announcementId = Announcements.getAnnouncementId(uri);
return builder.table(Tables.ANNOUNCEMENTS)
.where(Announcements.ANNOUNCEMENT_ID + "=?", announcementId);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_NUM_STARRED_SESSIONS = "(SELECT COUNT(1) FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_STARRED_SESSION_ID = "(SELECT " + Qualified.SESSIONS_SESSION_ID + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_TITLE = "(SELECT " + Qualified.SESSIONS_TITLE + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_HASHTAGS = "(SELECT " + Qualified.SESSIONS_HASHTAGS + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_URL = "(SELECT " + Qualified.SESSIONS_URL + " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_LIVESTREAM_URL = "(SELECT "
+ Qualified.SESSIONS_LIVESTREAM_URL
+ " FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_NAME = "(SELECT " + Qualified.ROOMS_ROOM_NAME + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String BLOCK_STARRED_SESSION_ROOM_ID = "(SELECT " + Qualified.ROOMS_ROOM_ID + " FROM "
+ Tables.SESSIONS_JOIN_ROOMS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1 "
+ "ORDER BY " + Qualified.SESSIONS_TITLE + ")";
String TRACK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_TRACKS_SESSION_ID
+ ") FROM " + Tables.SESSIONS_TRACKS + " WHERE "
+ Qualified.SESSIONS_TRACKS_TRACK_ID + "=" + Qualified.TRACKS_TRACK_ID + ")";
String TRACK_VENDORS_COUNT = "(SELECT COUNT(" + Qualified.VENDORS_VENDOR_ID + ") FROM "
+ Tables.VENDORS + " WHERE " + Qualified.VENDORS_TRACK_ID + "="
+ Qualified.TRACKS_TRACK_ID + ")";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_TRACKS_SESSION_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.SESSION_ID;
String SESSIONS_TRACKS_TRACK_ID = Tables.SESSIONS_TRACKS + "."
+ SessionsTracks.TRACK_ID;
String SESSIONS_SPEAKERS_SESSION_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SESSION_ID;
String SESSIONS_SPEAKERS_SPEAKER_ID = Tables.SESSIONS_SPEAKERS + "."
+ SessionsSpeakers.SPEAKER_ID;
String VENDORS_VENDOR_ID = Tables.VENDORS + "." + Vendors.VENDOR_ID;
String VENDORS_TRACK_ID = Tables.VENDORS + "." + Vendors.TRACK_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String SESSIONS_HASHTAGS = Tables.SESSIONS + "." + Sessions.SESSION_HASHTAGS;
String SESSIONS_URL = Tables.SESSIONS + "." + Sessions.SESSION_URL;
String SESSIONS_LIVESTREAM_URL = Tables.SESSIONS + "." + Sessions.SESSION_LIVESTREAM_URL;
String ROOMS_ROOM_NAME = Tables.ROOMS + "." + Rooms.ROOM_NAME;
String ROOMS_ROOM_ID = Tables.ROOMS + "." + Rooms.ROOM_ID;
String TRACKS_TRACK_ID = Tables.TRACKS + "." + Tracks.TRACK_ID;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/provider/ScheduleProvider.java
|
Java
|
asf20
| 39,629
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.provider;
import com.google.android.apps.iosched.util.ParserUtils;
import android.app.SearchManager;
import android.graphics.Color;
import android.net.Uri;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.text.format.DateUtils;
import java.util.List;
/**
* Contract class for interacting with {@link ScheduleProvider}. Unless
* otherwise noted, all time-based fields are milliseconds since epoch and can
* be compared against {@link System#currentTimeMillis()}.
* <p>
* The backing {@link android.content.ContentProvider} assumes that {@link Uri}
* are generated using stronger {@link String} identifiers, instead of
* {@code int} {@link BaseColumns#_ID} values, which are prone to shuffle during
* sync.
*/
public class ScheduleContract {
/**
* Special value for {@link SyncColumns#UPDATED} indicating that an entry
* has never been updated, or doesn't exist yet.
*/
public static final long UPDATED_NEVER = -2;
/**
* Special value for {@link SyncColumns#UPDATED} indicating that the last
* update time is unknown, usually when inserted from a local file source.
*/
public static final long UPDATED_UNKNOWN = -1;
public interface SyncColumns {
/** Last time this entry was updated or synchronized. */
String UPDATED = "updated";
}
interface BlocksColumns {
/** Unique string identifying this block of time. */
String BLOCK_ID = "block_id";
/** Title describing this block of time. */
String BLOCK_TITLE = "block_title";
/** Time when this block starts. */
String BLOCK_START = "block_start";
/** Time when this block ends. */
String BLOCK_END = "block_end";
/** Type describing this block. */
String BLOCK_TYPE = "block_type";
/** Extra string metadata for the block. */
String BLOCK_META = "block_meta";
}
interface TracksColumns {
/** Unique string identifying this track. */
String TRACK_ID = "track_id";
/** Name describing this track. */
String TRACK_NAME = "track_name";
/** Color used to identify this track, in {@link Color#argb} format. */
String TRACK_COLOR = "track_color";
/** Body of text explaining this track in detail. */
String TRACK_ABSTRACT = "track_abstract";
}
interface RoomsColumns {
/** Unique string identifying this room. */
String ROOM_ID = "room_id";
/** Name describing this room. */
String ROOM_NAME = "room_name";
/** Building floor this room exists on. */
String ROOM_FLOOR = "room_floor";
}
interface SessionsColumns {
/** Unique string identifying this session. */
String SESSION_ID = "session_id";
/** The type of session (session, keynote, codelab, etc). */
String SESSION_TYPE = "session_type";
/** Difficulty level of the session. */
String SESSION_LEVEL = "session_level";
/** Title describing this track. */
String SESSION_TITLE = "session_title";
/** Body of text explaining this session in detail. */
String SESSION_ABSTRACT = "session_abstract";
/** Requirements that attendees should meet. */
String SESSION_REQUIREMENTS = "session_requirements";
/** Keywords/tags for this session. */
String SESSION_TAGS = "session_keywords";
/** Hashtag for this session. */
String SESSION_HASHTAGS = "session_hashtag";
/** Full URL to session online. */
String SESSION_URL = "session_url";
/** Full URL to YouTube. */
String SESSION_YOUTUBE_URL = "session_youtube_url";
/** Full URL to PDF. */
String SESSION_PDF_URL = "session_pdf_url";
/** Full URL to official session notes. */
String SESSION_NOTES_URL = "session_notes_url";
/** User-specific flag indicating starred status. */
String SESSION_STARRED = "session_starred";
/** Key for session Calendar event. (Used in ICS or above) */
String SESSION_CAL_EVENT_ID = "session_cal_event_id";
/** The YouTube live stream URL. */
String SESSION_LIVESTREAM_URL = "session_livestream_url";
}
interface SpeakersColumns {
/** Unique string identifying this speaker. */
String SPEAKER_ID = "speaker_id";
/** Name of this speaker. */
String SPEAKER_NAME = "speaker_name";
/** Profile photo of this speaker. */
String SPEAKER_IMAGE_URL = "speaker_image_url";
/** Company this speaker works for. */
String SPEAKER_COMPANY = "speaker_company";
/** Body of text describing this speaker in detail. */
String SPEAKER_ABSTRACT = "speaker_abstract";
/** Full URL to the speaker's profile. */
String SPEAKER_URL = "speaker_url";
}
interface VendorsColumns {
/** Unique string identifying this vendor. */
String VENDOR_ID = "vendor_id";
/** Name of this vendor. */
String VENDOR_NAME = "vendor_name";
/** Location or city this vendor is based in. */
String VENDOR_LOCATION = "vendor_location";
/** Body of text describing this vendor. */
String VENDOR_DESC = "vendor_desc";
/** Link to vendor online. */
String VENDOR_URL = "vendor_url";
/** Body of text describing the product of this vendor. */
String VENDOR_PRODUCT_DESC = "vendor_product_desc";
/** Link to vendor logo. */
String VENDOR_LOGO_URL = "vendor_logo_url";
/** User-specific flag indicating starred status. */
String VENDOR_STARRED = "vendor_starred";
}
interface AnnouncementsColumns {
/** Unique string identifying this announcment. */
String ANNOUNCEMENT_ID = "announcement_id";
/** Title of the announcement. */
String ANNOUNCEMENT_TITLE = "announcement_title";
/** Summary of the announcement. */
String ANNOUNCEMENT_SUMMARY = "announcement_summary";
/** Track announcement belongs to. */
String ANNOUNCEMENT_TRACKS = "announcement_tracks";
/** Full URL for the announcement. */
String ANNOUNCEMENT_URL = "announcement_url";
/** Date of the announcement. */
String ANNOUNCEMENT_DATE = "announcement_date";
}
public static final String CONTENT_AUTHORITY = "com.google.android.apps.iosched";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);
private static final String PATH_BLOCKS = "blocks";
private static final String PATH_AT = "at";
private static final String PATH_BETWEEN = "between";
private static final String PATH_TRACKS = "tracks";
private static final String PATH_ROOMS = "rooms";
private static final String PATH_SESSIONS = "sessions";
private static final String PATH_WITH_TRACK = "with_track";
private static final String PATH_STARRED = "starred";
private static final String PATH_SPEAKERS = "speakers";
private static final String PATH_VENDORS = "vendors";
private static final String PATH_ANNOUNCEMENTS = "announcements";
private static final String PATH_SEARCH = "search";
private static final String PATH_SEARCH_SUGGEST = "search_suggest_query";
/**
* Blocks are generic timeslots that {@link Sessions} and other related
* events fall into.
*/
public static class Blocks implements BlocksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_BLOCKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.block";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.block";
/** Count of {@link Sessions} inside given block. */
public static final String SESSIONS_COUNT = "sessions_count";
/**
* Flag indicating the number of sessions inside this block that have
* {@link Sessions#SESSION_STARRED} set.
*/
public static final String NUM_STARRED_SESSIONS = "num_starred_sessions";
/**
* The {@link Sessions#SESSION_ID} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ID = "starred_session_id";
/**
* The {@link Sessions#SESSION_TITLE} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_TITLE = "starred_session_title";
/**
* The {@link Sessions#SESSION_LIVESTREAM_URL} of the first starred
* session in this block.
*/
public static final String STARRED_SESSION_LIVESTREAM_URL =
"starred_session_livestream_url";
/**
* The {@link Rooms#ROOM_NAME} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_ROOM_NAME = "starred_session_room_name";
/**
* The {@link Rooms#ROOM_ID} of the first starred session in this block.
*/
public static final String STARRED_SESSION_ROOM_ID = "starred_session_room_id";
/**
* The {@link Sessions#SESSION_HASHTAGS} of the first starred session in
* this block.
*/
public static final String STARRED_SESSION_HASHTAGS = "starred_session_hashtags";
/**
* The {@link Sessions#SESSION_URL} of the first starred session in this
* block.
*/
public static final String STARRED_SESSION_URL = "starred_session_url";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC, "
+ BlocksColumns.BLOCK_END + " ASC";
public static final String EMPTY_SESSIONS_SELECTION = "(" + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_SESSION + "' OR " + BLOCK_TYPE
+ " = '" + ParserUtils.BLOCK_TYPE_CODE_LAB + "') AND "
+ SESSIONS_COUNT + " = 0";
/** Build {@link Uri} for requested {@link #BLOCK_ID}. */
public static Uri buildBlockUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references starred {@link Sessions} associated
* with the requested {@link #BLOCK_ID}.
*/
public static Uri buildStarredSessionsUri(String blockId) {
return CONTENT_URI.buildUpon().appendPath(blockId).appendPath(PATH_SESSIONS)
.appendPath(PATH_STARRED).build();
}
/**
* Build {@link Uri} that references any {@link Blocks} that occur
* between the requested time boundaries.
*/
public static Uri buildBlocksBetweenDirUri(long startTime, long endTime) {
return CONTENT_URI.buildUpon().appendPath(PATH_BETWEEN).appendPath(
String.valueOf(startTime)).appendPath(String.valueOf(endTime)).build();
}
/** Read {@link #BLOCK_ID} from {@link Blocks} {@link Uri}. */
public static String getBlockId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #BLOCK_ID} that will always match the requested
* {@link Blocks} details.
*/
public static String generateBlockId(long startTime, long endTime) {
startTime /= DateUtils.SECOND_IN_MILLIS;
endTime /= DateUtils.SECOND_IN_MILLIS;
return ParserUtils.sanitizeId(startTime + "-" + endTime);
}
}
/**
* Tracks are overall categories for {@link Sessions} and {@link Vendors},
* such as "Android" or "Enterprise."
*/
public static class Tracks implements TracksColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_TRACKS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.track";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.track";
/** "All tracks" ID. */
public static final String ALL_TRACK_ID = "all";
public static final String CODELABS_TRACK_ID = generateTrackId("Code Labs");
public static final String TECH_TALK_TRACK_ID = generateTrackId("Tech Talk");
/** Count of {@link Sessions} inside given track. */
public static final String SESSIONS_COUNT = "sessions_count";
/** Count of {@link Vendors} inside given track. */
public static final String VENDORS_COUNT = "vendors_count";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = TracksColumns.TRACK_NAME + " ASC";
/** Build {@link Uri} for requested {@link #TRACK_ID}. */
public static Uri buildTrackUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #TRACK_ID}.
*/
public static Uri buildSessionsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_SESSIONS).build();
}
/**
* Build {@link Uri} that references any {@link Vendors} associated with
* the requested {@link #TRACK_ID}.
*/
public static Uri buildVendorsUri(String trackId) {
return CONTENT_URI.buildUpon().appendPath(trackId).appendPath(PATH_VENDORS).build();
}
/** Read {@link #TRACK_ID} from {@link Tracks} {@link Uri}. */
public static String getTrackId(Uri uri) {
return uri.getPathSegments().get(1);
}
/**
* Generate a {@link #TRACK_ID} that will always match the requested
* {@link Tracks} details.
*/
public static String generateTrackId(String name) {
return ParserUtils.sanitizeId(name);
}
}
/**
* Rooms are physical locations at the conference venue.
*/
public static class Rooms implements RoomsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ROOMS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.room";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.room";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = RoomsColumns.ROOM_FLOOR + " ASC, "
+ RoomsColumns.ROOM_NAME + " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ROOM_ID}. */
public static Uri buildRoomUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #ROOM_ID}.
*/
public static Uri buildSessionsDirUri(String roomId) {
return CONTENT_URI.buildUpon().appendPath(roomId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #ROOM_ID} from {@link Rooms} {@link Uri}. */
public static String getRoomId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each session is a block of time that has a {@link Tracks}, a
* {@link Rooms}, and zero or more {@link Speakers}.
*/
public static class Sessions implements SessionsColumns, BlocksColumns, RoomsColumns,
SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SESSIONS).build();
public static final Uri CONTENT_STARRED_URI =
CONTENT_URI.buildUpon().appendPath(PATH_STARRED).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.session";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.session";
public static final String BLOCK_ID = "block_id";
public static final String ROOM_ID = "room_id";
public static final String SEARCH_SNIPPET = "search_snippet";
// TODO: shortcut primary track to offer sub-sorting here
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = BlocksColumns.BLOCK_START + " ASC,"
+ SessionsColumns.SESSION_TITLE + " COLLATE NOCASE ASC";
public static final String LIVESTREAM_SELECTION =
SESSION_LIVESTREAM_URL + " is not null AND " + SESSION_LIVESTREAM_URL + "!=''";
// Used to fetch sessions for a particular time
public static final String AT_TIME_SELECTION =
BLOCK_START + " < ? and " + BLOCK_END + " " + "> ?";
// Builds selectionArgs for {@link AT_TIME_SELECTION}
public static String[] buildAtTimeSelectionArgs(long time) {
final String timeString = String.valueOf(time);
return new String[] { timeString, timeString };
}
// Used to fetch upcoming sessions
public static final String UPCOMING_SELECTION =
BLOCK_START + " = (select min(" + BLOCK_START + ") from " +
ScheduleDatabase.Tables.BLOCKS_JOIN_SESSIONS + " where " + LIVESTREAM_SELECTION +
" and " + BLOCK_START + " >" + " ?)";
// Builds selectionArgs for {@link UPCOMING_SELECTION}
public static String[] buildUpcomingSelectionArgs(long minTime) {
return new String[] { String.valueOf(minTime) };
}
/** Build {@link Uri} for requested {@link #SESSION_ID}. */
public static Uri buildSessionUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).build();
}
/**
* Build {@link Uri} that references any {@link Speakers} associated
* with the requested {@link #SESSION_ID}.
*/
public static Uri buildSpeakersDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_SPEAKERS).build();
}
/**
* Build {@link Uri} that includes track detail with list of sessions.
*/
public static Uri buildWithTracksUri() {
return CONTENT_URI.buildUpon().appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that includes track detail for a specific session.
*/
public static Uri buildWithTracksUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId)
.appendPath(PATH_WITH_TRACK).build();
}
/**
* Build {@link Uri} that references any {@link Tracks} associated with
* the requested {@link #SESSION_ID}.
*/
public static Uri buildTracksDirUri(String sessionId) {
return CONTENT_URI.buildUpon().appendPath(sessionId).appendPath(PATH_TRACKS).build();
}
public static Uri buildSessionsAtDirUri(long time) {
return CONTENT_URI.buildUpon().appendPath(PATH_AT).appendPath(String.valueOf(time))
.build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #SESSION_ID} from {@link Sessions} {@link Uri}. */
public static String getSessionId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
}
/**
* Speakers are individual people that lead {@link Sessions}.
*/
public static class Speakers implements SpeakersColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SPEAKERS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.speaker";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.speaker";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = SpeakersColumns.SPEAKER_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #SPEAKER_ID}. */
public static Uri buildSpeakerUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).build();
}
/**
* Build {@link Uri} that references any {@link Sessions} associated
* with the requested {@link #SPEAKER_ID}.
*/
public static Uri buildSessionsDirUri(String speakerId) {
return CONTENT_URI.buildUpon().appendPath(speakerId).appendPath(PATH_SESSIONS).build();
}
/** Read {@link #SPEAKER_ID} from {@link Speakers} {@link Uri}. */
public static String getSpeakerId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
/**
* Each vendor is a company appearing at the conference that may be
* associated with a specific {@link Tracks}.
*/
public static class Vendors implements VendorsColumns, SyncColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_VENDORS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.vendor";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.vendor";
/** {@link Tracks#TRACK_ID} that this vendor belongs to. */
public static final String TRACK_ID = "track_id";
public static final String SEARCH_SNIPPET = "search_snippet";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = VendorsColumns.VENDOR_NAME
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #VENDOR_ID}. */
public static Uri buildVendorUri(String vendorId) {
return CONTENT_URI.buildUpon().appendPath(vendorId).build();
}
public static Uri buildSearchUri(String query) {
return CONTENT_URI.buildUpon().appendPath(PATH_SEARCH).appendPath(query).build();
}
public static boolean isSearchUri(Uri uri) {
List<String> pathSegments = uri.getPathSegments();
return pathSegments.size() >= 2 && PATH_SEARCH.equals(pathSegments.get(1));
}
/** Read {@link #VENDOR_ID} from {@link Vendors} {@link Uri}. */
public static String getVendorId(Uri uri) {
return uri.getPathSegments().get(1);
}
public static String getSearchQuery(Uri uri) {
return uri.getPathSegments().get(2);
}
/**
* Generate a {@link #VENDOR_ID} that will always match the requested
* {@link Vendors} details.
*/
public static String generateVendorId(String companyName) {
return ParserUtils.sanitizeId(companyName);
}
}
/**
* Announcements of breaking news
*/
public static class Announcements implements AnnouncementsColumns, BaseColumns {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_ANNOUNCEMENTS).build();
public static final String CONTENT_TYPE =
"vnd.android.cursor.dir/vnd.iosched.announcement";
public static final String CONTENT_ITEM_TYPE =
"vnd.android.cursor.item/vnd.iosched.announcement";
/** Default "ORDER BY" clause. */
public static final String DEFAULT_SORT = AnnouncementsColumns.ANNOUNCEMENT_DATE
+ " COLLATE NOCASE ASC";
/** Build {@link Uri} for requested {@link #ANNOUNCEMENT_ID}. */
public static Uri buildAnnouncementUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId).build();
}
/**
* Build {@link Uri} that references any {@link Announcements}
* associated with the requested {@link #ANNOUNCEMENT_ID}.
*/
public static Uri buildAnnouncementsDirUri(String announcementId) {
return CONTENT_URI.buildUpon().appendPath(announcementId)
.appendPath(PATH_ANNOUNCEMENTS).build();
}
/**
* Read {@link #ANNOUNCEMENT_ID} from {@link Announcements} {@link Uri}.
*/
public static String getAnnouncementId(Uri uri) {
return uri.getPathSegments().get(1);
}
}
public static class SearchSuggest {
public static final Uri CONTENT_URI =
BASE_CONTENT_URI.buildUpon().appendPath(PATH_SEARCH_SUGGEST).build();
public static final String DEFAULT_SORT = SearchManager.SUGGEST_COLUMN_TEXT_1
+ " COLLATE NOCASE ASC";
}
public static Uri addCallerIsSyncAdapterParameter(Uri uri) {
return uri.buildUpon().appendQueryParameter(
ContactsContract.CALLER_IS_SYNCADAPTER, "true").build();
}
public static boolean hasCallerIsSyncAdapterParameter(Uri uri) {
return TextUtils.equals("true",
uri.getQueryParameter(ContactsContract.CALLER_IS_SYNCADAPTER));
}
private ScheduleContract() {
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/provider/ScheduleContract.java
|
Java
|
asf20
| 27,130
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.provider.CalendarContract;
import android.text.TextUtils;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGW;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background {@link android.app.Service} that adds or removes session Calendar events through
* the {@link CalendarContract} API available in Android 4.0 or above.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class SessionCalendarService extends IntentService {
private static final String TAG = makeLogTag(SessionCalendarService.class);
public static final String ACTION_ADD_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.ADD_SESSION_CALENDAR";
public static final String ACTION_REMOVE_SESSION_CALENDAR =
"com.google.android.apps.iosched.action.REMOVE_SESSION_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.UPDATE_ALL_SESSIONS_CALENDAR";
public static final String ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED =
"com.google.android.apps.iosched.action.UPDATE_CALENDAR_COMPLETED";
public static final String ACTION_CLEAR_ALL_SESSIONS_CALENDAR =
"com.google.android.apps.iosched.action.CLEAR_ALL_SESSIONS_CALENDAR";
public static final String EXTRA_ACCOUNT_NAME =
"com.google.android.apps.iosched.extra.ACCOUNT_NAME";
public static final String EXTRA_SESSION_BLOCK_START =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_START";
public static final String EXTRA_SESSION_BLOCK_END =
"com.google.android.apps.iosched.extra.SESSION_BLOCK_END";
public static final String EXTRA_SESSION_TITLE =
"com.google.android.apps.iosched.extra.SESSION_TITLE";
public static final String EXTRA_SESSION_ROOM =
"com.google.android.apps.iosched.extra.SESSION_ROOM";
private static final long INVALID_CALENDAR_ID = -1;
// TODO: localize
private static final String CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION =
"%added by Google I/O 2012%";
public SessionCalendarService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
final ContentResolver resolver = getContentResolver();
boolean isAddEvent = false;
if (ACTION_ADD_SESSION_CALENDAR.equals(action)) {
isAddEvent = true;
} else if (ACTION_REMOVE_SESSION_CALENDAR.equals(action)) {
isAddEvent = false;
} else if (ACTION_UPDATE_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processAllSessionsCalendar(resolver, getCalendarId(intent)));
sendBroadcast(new Intent(
SessionCalendarService.ACTION_UPDATE_ALL_SESSIONS_CALENDAR_COMPLETED));
} catch (RemoteException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding all sessions to Google Calendar", e);
}
} else if (ACTION_CLEAR_ALL_SESSIONS_CALENDAR.equals(action)) {
try {
getContentResolver().applyBatch(CalendarContract.AUTHORITY,
processClearAllSessions(resolver, getCalendarId(intent)));
} catch (RemoteException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error clearing all sessions from Google Calendar", e);
}
} else {
return;
}
final Uri uri = intent.getData();
final Bundle extras = intent.getExtras();
if (uri == null || extras == null) {
return;
}
try {
resolver.applyBatch(CalendarContract.AUTHORITY,
processSessionCalendar(resolver, getCalendarId(intent), isAddEvent, uri,
extras.getLong(EXTRA_SESSION_BLOCK_START),
extras.getLong(EXTRA_SESSION_BLOCK_END),
extras.getString(EXTRA_SESSION_TITLE),
extras.getString(EXTRA_SESSION_ROOM)));
} catch (RemoteException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
} catch (OperationApplicationException e) {
LOGE(TAG, "Error adding session to Google Calendar", e);
}
}
/**
* Gets the currently-logged in user's Google Calendar, or the Google Calendar for the user
* specified in the given intent's {@link #EXTRA_ACCOUNT_NAME}.
*/
private long getCalendarId(Intent intent) {
final String accountName;
if (intent != null && intent.hasExtra(EXTRA_ACCOUNT_NAME)) {
accountName = intent.getStringExtra(EXTRA_ACCOUNT_NAME);
} else {
accountName = AccountUtils.getChosenAccountName(this);
}
if (TextUtils.isEmpty(accountName)) {
return INVALID_CALENDAR_ID;
}
// TODO: The calendar ID should be stored in shared preferences upon choosing an account.
Cursor calendarsCursor = getContentResolver().query(
CalendarContract.Calendars.CONTENT_URI,
new String[]{"_id"},
// TODO: Handle case where the calendar is not displayed or not sync'd
"account_name = ownerAccount and account_name = ?",
new String[]{accountName},
null);
long calendarId = INVALID_CALENDAR_ID;
if (calendarsCursor != null && calendarsCursor.moveToFirst()) {
calendarId = calendarsCursor.getLong(0);
calendarsCursor.close();
}
return calendarId;
}
private String makeCalendarEventTitle(String sessionTitle) {
return sessionTitle + getResources().getString(R.string.session_calendar_suffix);
}
/**
* Processes all sessions in the
* {@link com.google.android.apps.iosched.provider.ScheduleProvider}, adding or removing
* calendar events to/from the specified Google Calendar depending on whether a session is
* in the user's schedule or not.
*/
private ArrayList<ContentProviderOperation> processAllSessionsCalendar(ContentResolver resolver,
final long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Retrieves all sessions. For each session, add to Calendar if starred and attempt to
// remove from Calendar if unstarred.
Cursor cursor = resolver.query(
ScheduleContract.Sessions.CONTENT_URI,
SessionsQuery.PROJECTION,
null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
Uri uri = ScheduleContract.Sessions.buildSessionUri(
Long.valueOf(cursor.getLong(0)).toString());
boolean isAddEvent = (cursor.getInt(SessionsQuery.SESSION_STARRED) == 1);
if (isAddEvent) {
batch.addAll(processSessionCalendar(resolver,
calendarId, isAddEvent, uri,
cursor.getLong(SessionsQuery.BLOCK_START),
cursor.getLong(SessionsQuery.BLOCK_END),
cursor.getString(SessionsQuery.SESSION_TITLE),
cursor.getString(SessionsQuery.ROOM_NAME)));
}
}
cursor.close();
}
return batch;
}
/**
* Adds or removes a single session to/from the specified Google Calendar.
*/
private ArrayList<ContentProviderOperation> processSessionCalendar(
final ContentResolver resolver,
final long calendarId, final boolean isAddEvent,
final Uri sessionUri, final long sessionBlockStart, final long sessionBlockEnd,
final String sessionTitle, final String sessionRoom) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);
Cursor cursor;
ContentValues values = new ContentValues();
// Add Calendar event.
if (isAddEvent) {
if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
return batch;
}
// Check if the calendar event exists first. If it does, we don't want to add a
// duplicate one.
cursor = resolver.query(
CalendarContract.Events.CONTENT_URI, // URI
new String[] {CalendarContract.Events._ID}, // Projection
CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
+ CalendarContract.Events.TITLE + "=? and "
+ CalendarContract.Events.DTSTART + ">=? and "
+ CalendarContract.Events.DTEND + "<=?",
new String[]{ // Selection args
Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
},
null);
long newEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
// Calendar event already exists for this session.
newEventId = cursor.getLong(0);
cursor.close();
} else {
// Calendar event doesn't exist, create it.
// NOTE: we can't use batch processing here because we need the result of
// the insert.
values.clear();
values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
values.put(CalendarContract.Events.TITLE, calendarEventTitle);
values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
values.put(CalendarContract.Events.EVENT_TIMEZONE,
UIUtils.CONFERENCE_TIME_ZONE.getID());
Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
String eventId = eventUri.getLastPathSegment();
if (eventId == null) {
return batch; // Should be empty at this point
}
newEventId = Long.valueOf(eventId);
// Since we're adding session reminder to system notification, we're not creating
// Calendar event reminders. If we were to create Calendar event reminders, this
// is how we would do it.
//values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
//values.put(CalendarContract.Reminders.MINUTES, 10);
//values.put(CalendarContract.Reminders.METHOD,
// CalendarContract.Reminders.METHOD_ALERT); // Or default?
//cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
//values.clear();
}
// Update the session in our own provider with the newly created calendar event ID.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
resolver.update(sessionUri, values, null, null);
} else {
// Remove Calendar event, if exists.
// Get the event calendar id.
cursor = resolver.query(sessionUri,
new String[] {ScheduleContract.Sessions.SESSION_CAL_EVENT_ID},
null, null, null);
long calendarEventId = -1;
if (cursor != null && cursor.moveToFirst()) {
calendarEventId = cursor.getLong(0);
cursor.close();
}
// Try to remove the Calendar Event based on key. If successful, move on;
// otherwise, remove the event based on Event title.
int affectedRows = 0;
if (calendarEventId != -1) {
affectedRows = resolver.delete(
CalendarContract.Events.CONTENT_URI,
CalendarContract.Events._ID + "=?",
new String[]{Long.valueOf(calendarEventId).toString()});
}
if (affectedRows == 0) {
resolver.delete(CalendarContract.Events.CONTENT_URI,
String.format("%s=? and %s=? and %s=? and %s=?",
CalendarContract.Events.CALENDAR_ID,
CalendarContract.Events.TITLE,
CalendarContract.Events.DTSTART,
CalendarContract.Events.DTEND),
new String[]{Long.valueOf(calendarId).toString(),
calendarEventTitle,
Long.valueOf(sessionBlockStart).toString(),
Long.valueOf(sessionBlockEnd).toString()});
}
// Remove the session and calendar event association.
values.clear();
values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
resolver.update(sessionUri, values, null, null);
}
return batch;
}
/**
* Removes all calendar entries associated with Google I/O 2012.
*/
private ArrayList<ContentProviderOperation> processClearAllSessions(
ContentResolver resolver, long calendarId) {
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
// Unable to find the Calendar associated with the user. Stop here.
if (calendarId == INVALID_CALENDAR_ID) {
return batch;
}
// Delete all calendar entries matching the given title within the given time period
batch.add(ContentProviderOperation
.newDelete(CalendarContract.Events.CONTENT_URI)
.withSelection(
CalendarContract.Events.CALENDAR_ID + " = ? and "
+ CalendarContract.Events.TITLE + " LIKE ? and "
+ CalendarContract.Events.DTSTART + ">= ? and "
+ CalendarContract.Events.DTEND + "<= ?",
new String[]{
Long.toString(calendarId),
CALENDAR_CLEAR_SEARCH_LIKE_EXPRESSION,
Long.toString(UIUtils.CONFERENCE_START_MILLIS),
Long.toString(UIUtils.CONFERENCE_END_MILLIS)
})
.build());
return batch;
}
private interface SessionsQuery {
String[] PROJECTION = {
ScheduleContract.Sessions._ID,
ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.ROOM_NAME,
ScheduleContract.Sessions.SESSION_STARRED,
};
int _ID = 0;
int BLOCK_START = 1;
int BLOCK_END = 2;
int SESSION_TITLE = 3;
int ROOM_NAME = 4;
int SESSION_STARRED = 5;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/calendar/SessionCalendarService.java
|
Java
|
asf20
| 17,856
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/calendar/SessionAlarmReceiver.java
|
Java
|
asf20
| 1,391
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.calendar;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background service to handle scheduling of starred session notification via
* {@link android.app.AlarmManager}.
*/
public class SessionAlarmService extends IntentService {
private static final String TAG = makeLogTag(SessionAlarmService.class);
public static final String ACTION_NOTIFY_SESSION =
"com.google.android.apps.iosched.action.NOTIFY_SESSION";
public static final String ACTION_SCHEDULE_STARRED_BLOCK =
"com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK";
public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS =
"com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS";
public static final String EXTRA_SESSION_START =
"com.google.android.apps.iosched.extra.SESSION_START";
public static final String EXTRA_SESSION_END =
"com.google.android.apps.iosched.extra.SESSION_END";
public static final String EXTRA_SESSION_ALARM_OFFSET =
"com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET";
private static final int NOTIFICATION_ID = 100;
// pulsate every 1 second, indicating a relatively high degree of urgency
private static final int NOTIFICATION_LED_ON_MS = 100;
private static final int NOTIFICATION_LED_OFF_MS = 1000;
private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan
private static final long ONE_MINUTE_MILLIS = 1 * 60 * 1000;
private static final long TEN_MINUTES_MILLIS = 10 * ONE_MINUTE_MILLIS;
private static final long UNDEFINED_ALARM_OFFSET = -1;
public SessionAlarmService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) {
scheduleAllStarredBlocks();
return;
}
final long sessionStart = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, -1);
if (sessionStart == -1) {
return;
}
final long sessionEnd = intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, -1);
if (sessionEnd == -1) {
return;
}
final long sessionAlarmOffset =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
UNDEFINED_ALARM_OFFSET);
if (ACTION_NOTIFY_SESSION.equals(action)) {
notifySession(sessionStart, sessionEnd, sessionAlarmOffset);
} else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) {
scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset);
}
}
private void scheduleAlarm(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
final long currentTime = System.currentTimeMillis();
// If the session is already started, do not schedule system notification.
if (currentTime > sessionStart) {
return;
}
// By default, sets alarm to go off at 10 minutes before session start time. If alarm
// offset is provided, alarm is set to go off by that much time from now.
long alarmTime;
if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
alarmTime = sessionStart - TEN_MINUTES_MILLIS;
} else {
alarmTime = currentTime + alarmOffset;
}
final Intent alarmIntent = new Intent(
ACTION_NOTIFY_SESSION,
null,
this,
SessionAlarmService.class);
// Setting data to ensure intent's uniqueness for different session start times.
alarmIntent.setData(
new Uri.Builder()
.authority(ScheduleContract.CONTENT_AUTHORITY)
.path(String.valueOf(sessionStart))
.build());
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
alarmIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Schedule an alarm to be fired to notify user of added sessions are about to begin.
am.set(AlarmManager.RTC_WAKEUP, alarmTime,
PendingIntent.getService(this, 0, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}
/**
* Constructs and triggers system notification for when starred sessions are about to begin.
*/
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void notifySession(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
long currentTime = System.currentTimeMillis();
if (sessionStart < currentTime) {
return;
}
// Avoid repeated notifications.
if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(
this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
return;
}
final ContentResolver resolver = getContentResolver();
final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri(
ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd));
Cursor cursor = resolver.query(starredBlockUri,
new String[]{
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Sessions.SESSION_TITLE
},
null, null, null);
int starredCount = 0;
ArrayList<String> starredSessionTitles = new ArrayList<String>();
while (cursor.moveToNext()) {
starredSessionTitles.add(cursor.getString(1));
starredCount = cursor.getInt(0);
}
if (starredCount < 1) {
return;
}
// Generates the pending intent which gets fired when the user touches on the notification.
Intent sessionIntent = new Intent(Intent.ACTION_VIEW, starredBlockUri);
sessionIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, sessionIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
final Resources res = getResources();
String contentText;
int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
if (minutesLeft < 1) {
minutesLeft = 1;
}
if (starredCount == 1) {
contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
} else {
contentText = res.getQuantityString(R.plurals.session_notification_text,
starredCount - 1,
minutesLeft,
starredCount - 1);
}
// Construct a notification. Use Jelly Bean (API 16) rich notifications if possible.
Notification notification;
if (UIUtils.hasJellyBean()) {
// Rich notifications
Notification.Builder builder = new Notification.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
if (minutesLeft > 5) {
builder.addAction(R.drawable.ic_alarm_holo_dark,
String.format(res.getString(R.string.snooze_x_min), 5),
createSnoozeIntent(sessionStart, sessionEnd, 5));
}
Notification.InboxStyle richNotification = new Notification.InboxStyle(
builder)
.setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title,
starredCount,
minutesLeft,
starredCount));
// Adds starred sessions starting at this time block to the notification.
for (int i = 0; i < starredCount; i++) {
richNotification.addLine(starredSessionTitles.get(i));
}
notification = richNotification.build();
} else {
// Pre-Jelly Bean non-rich notifications
notification = new NotificationCompat.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.getNotification();
}
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, notification);
}
private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
final int snoozeMinutes) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, this, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
snoozeMinutes * ONE_MINUTE_MILLIS);
return PendingIntent.getService(this, 0, scheduleIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private void scheduleAllStarredBlocks() {
final Cursor cursor = getContentResolver().query(
ScheduleContract.Sessions.CONTENT_STARRED_URI,
new String[] {
"distinct " + ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END
},
null, null, null);
if (cursor == null) {
return;
}
while (cursor.moveToNext()) {
final long sessionStart = cursor.getLong(0);
final long sessionEnd = cursor.getLong(1);
scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/calendar/SessionAlarmService.java
|
Java
|
asf20
| 12,996
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.TouchDelegate;
import android.view.View;
/**
* {@link TouchDelegate} that gates {@link MotionEvent} instances by comparing
* then against fractional dimensions of the source view.
* <p>
* This is particularly useful when you want to define a rectangle in terms of
* the source dimensions, but when those dimensions might change due to pending
* or future layout passes.
* <p>
* One example is catching touches that occur in the top-right quadrant of
* {@code sourceParent}, and relaying them to {@code targetChild}. This could be
* done with: <code>
* FractionalTouchDelegate.setupDelegate(sourceParent, targetChild, new RectF(0.5f, 0f, 1f, 0.5f));
* </code>
*/
public class FractionalTouchDelegate extends TouchDelegate {
private View mSource;
private View mTarget;
private RectF mSourceFraction;
private Rect mScrap = new Rect();
/** Cached full dimensions of {@link #mSource}. */
private Rect mSourceFull = new Rect();
/** Cached projection of {@link #mSourceFraction} onto {@link #mSource}. */
private Rect mSourcePartial = new Rect();
private boolean mDelegateTargeted;
public FractionalTouchDelegate(View source, View target, RectF sourceFraction) {
super(new Rect(0, 0, 0, 0), target);
mSource = source;
mTarget = target;
mSourceFraction = sourceFraction;
}
/**
* Helper to create and setup a {@link FractionalTouchDelegate} between the
* given {@link View}.
*
* @param source Larger source {@link View}, usually a parent, that will be
* assigned {@link View#setTouchDelegate(TouchDelegate)}.
* @param target Smaller target {@link View} which will receive
* {@link MotionEvent} that land in requested fractional area.
* @param sourceFraction Fractional area projected onto source {@link View}
* which determines when {@link MotionEvent} will be passed to
* target {@link View}.
*/
public static void setupDelegate(View source, View target, RectF sourceFraction) {
source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
/**
* Consider updating {@link #mSourcePartial} when {@link #mSource}
* dimensions have changed.
*/
private void updateSourcePartial() {
mSource.getHitRect(mScrap);
if (!mScrap.equals(mSourceFull)) {
// Copy over and calculate fractional rectangle
mSourceFull.set(mScrap);
final int width = mSourceFull.width();
final int height = mSourceFull.height();
mSourcePartial.left = (int) (mSourceFraction.left * width);
mSourcePartial.top = (int) (mSourceFraction.top * height);
mSourcePartial.right = (int) (mSourceFraction.right * width);
mSourcePartial.bottom = (int) (mSourceFraction.bottom * height);
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
updateSourcePartial();
// The logic below is mostly copied from the parent class, since we
// can't update private mBounds variable.
// http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
// f=core/java/android/view/TouchDelegate.java;hb=eclair#l98
final Rect sourcePartial = mSourcePartial;
final View target = mTarget;
int x = (int)event.getX();
int y = (int)event.getY();
boolean sendToDelegate = false;
boolean hit = true;
boolean handled = false;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (sourcePartial.contains(x, y)) {
mDelegateTargeted = true;
sendToDelegate = true;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_MOVE:
sendToDelegate = mDelegateTargeted;
if (sendToDelegate) {
if (!sourcePartial.contains(x, y)) {
hit = false;
}
}
break;
case MotionEvent.ACTION_CANCEL:
sendToDelegate = mDelegateTargeted;
mDelegateTargeted = false;
break;
}
if (sendToDelegate) {
if (hit) {
event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
} else {
event.setLocation(-1, -1);
}
handled = target.dispatchTouchEvent(event);
}
return handled;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/FractionalTouchDelegate.java
|
Java
|
asf20
| 5,324
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.appwidget.MyScheduleWidgetProvider;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.ScheduleUpdaterService;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SocialStreamActivity;
import com.google.android.apps.iosched.ui.SocialStreamFragment;
import com.actionbarsherlock.view.MenuItem;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ShareCompat;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper class for dealing with common actions to take on a session.
*/
public final class SessionsHelper {
private static final String TAG = makeLogTag(SessionsHelper.class);
private final Activity mActivity;
public SessionsHelper(Activity activity) {
mActivity = activity;
}
public void startMapActivity(String roomId) {
Intent intent = new Intent(mActivity.getApplicationContext(),
UIUtils.getMapActivityClass(mActivity));
intent.putExtra(MapFragment.EXTRA_ROOM, roomId);
mActivity.startActivity(intent);
}
public Intent createShareIntent(int messageTemplateResId, String title, String hashtags,
String url) {
ShareCompat.IntentBuilder builder = ShareCompat.IntentBuilder.from(mActivity)
.setType("text/plain")
.setText(mActivity.getString(messageTemplateResId,
title, UIUtils.getSessionHashtagsString(hashtags), url));
return builder.getIntent();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public void tryConfigureShareMenuItem(MenuItem menuItem, int messageTemplateResId,
final String title, String hashtags, String url) {
// TODO: uncomment pending ShareActionProvider fixes for split AB
// if (UIUtils.hasICS()) {
// ActionProvider itemProvider = menuItem.getActionProvider();
// ShareActionProvider provider;
// if (!(itemProvider instanceof ShareActionProvider)) {
// provider = new ShareActionProvider(mActivity);
// } else {
// provider = (ShareActionProvider) itemProvider;
// }
// provider.setShareIntent(createShareIntent(messageTemplateResId, title, hashtags, url));
// provider.setOnShareTargetSelectedListener(new OnShareTargetSelectedListener() {
// @Override
// public boolean onShareTargetSelected(ShareActionProvider source, Intent intent) {
// EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
// LOGD("Tracker", "Shared: " + title);
// return false;
// }
// });
//
// menuItem.setActionProvider(provider);
// }
}
public void shareSession(Context context, int messageTemplateResId, String title,
String hashtags, String url) {
EasyTracker.getTracker().trackEvent("Session", "Shared", title, 0L);
LOGD("Tracker", "Shared: " + title);
context.startActivity(Intent.createChooser(
createShareIntent(messageTemplateResId, title, hashtags, url),
context.getString(R.string.title_share)));
}
public void setSessionStarred(Uri sessionUri, boolean starred, String title) {
LOGD(TAG, "setSessionStarred uri=" + sessionUri + " starred=" +
starred + " title=" + title);
sessionUri = ScheduleContract.addCallerIsSyncAdapterParameter(sessionUri);
final ContentValues values = new ContentValues();
values.put(ScheduleContract.Sessions.SESSION_STARRED, starred);
AsyncQueryHandler handler =
new AsyncQueryHandler(mActivity.getContentResolver()) {
};
handler.startUpdate(-1, null, sessionUri, values, null, null);
EasyTracker.getTracker().trackEvent(
"Session", starred ? "Starred" : "Unstarred", title, 0L);
// Because change listener is set to null during initialization, these
// won't fire on pageview.
final Intent refreshIntent = new Intent(mActivity, MyScheduleWidgetProvider.class);
refreshIntent.setAction(MyScheduleWidgetProvider.REFRESH_ACTION);
mActivity.sendBroadcast(refreshIntent);
// Sync to the cloud.
final Intent updateServerIntent = new Intent(mActivity, ScheduleUpdaterService.class);
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_SESSION_ID,
ScheduleContract.Sessions.getSessionId(sessionUri));
updateServerIntent.putExtra(ScheduleUpdaterService.EXTRA_IN_SCHEDULE, starred);
mActivity.startService(updateServerIntent);
}
public void startSocialStream(String hashtags) {
Intent intent = new Intent(mActivity, SocialStreamActivity.class);
intent.putExtra(SocialStreamFragment.EXTRA_QUERY, hashtags);
mActivity.startActivity(intent);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/SessionsHelper.java
|
Java
|
asf20
| 6,116
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
*
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
*
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
*
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/Lists.java
|
Java
|
asf20
| 2,170
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
/**
* A set of helper methods for showing contextual help information in the app.
*/
public class HelpUtils {
public static boolean hasSeenTutorial(final Context context, String id) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean("seen_tutorial_" + id, false);
}
private static void setSeenTutorial(final Context context, final String id) {
//noinspection unchecked
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... voids) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putBoolean("seen_tutorial_" + id, true).commit();
return null;
}
}.execute();
}
public static void maybeShowAddToScheduleTutorial(FragmentActivity activity) {
if (hasSeenTutorial(activity, "add_to_schedule")) {
return;
}
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_add_to_schedule");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AddToScheduleTutorialDialog().show(ft, "dialog_add_to_schedule");
setSeenTutorial(activity, "add_to_schedule");
}
public static class AddToScheduleTutorialDialog extends DialogFragment implements
Html.ImageGetter {
public AddToScheduleTutorialDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView tutorialBodyView = (TextView) layoutInflater.inflate(
R.layout.dialog_tutorial_message, null);
tutorialBodyView.setText(
Html.fromHtml(getString(R.string.help_add_to_schedule), this, null));
tutorialBodyView.setContentDescription(
Html.fromHtml(getString(R.string.help_add_to_schedule_alt)));
return new AlertDialog.Builder(getActivity())
.setView(tutorialBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
@Override
public Drawable getDrawable(String url) {
if ("add_to_schedule".equals(url)) {
Resources res = getActivity().getResources();
Drawable d = res.getDrawable(R.drawable.help_add_to_schedule);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
return null;
}
}
public static void showAbout(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_about");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new AboutDialog().show(ft, "dialog_about");
}
public static class AboutDialog extends DialogFragment {
private static final String VERSION_UNAVAILABLE = "N/A";
public AboutDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get app version
PackageManager pm = getActivity().getPackageManager();
String packageName = getActivity().getPackageName();
String versionName;
try {
PackageInfo info = pm.getPackageInfo(packageName, 0);
versionName = info.versionName;
} catch (PackageManager.NameNotFoundException e) {
versionName = VERSION_UNAVAILABLE;
}
// Build the about body view and append the link to see OSS licenses
SpannableStringBuilder aboutBody = new SpannableStringBuilder();
aboutBody.append(Html.fromHtml(getString(R.string.about_body, versionName)));
SpannableString licensesLink = new SpannableString(getString(R.string.about_licenses));
licensesLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showOpenSourceLicenses(getActivity());
}
}, 0, licensesLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(licensesLink);
SpannableString eulaLink = new SpannableString(getString(R.string.about_eula));
eulaLink.setSpan(new ClickableSpan() {
@Override
public void onClick(View view) {
HelpUtils.showEula(getActivity());
}
}, 0, eulaLink.length(), 0);
aboutBody.append("\n\n");
aboutBody.append(eulaLink);
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
TextView aboutBodyView = (TextView) layoutInflater.inflate(R.layout.dialog_about, null);
aboutBodyView.setText(aboutBody);
aboutBodyView.setMovementMethod(new LinkMovementMethod());
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.title_about)
.setView(aboutBodyView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showOpenSourceLicenses(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_licenses");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new OpenSourceLicensesDialog().show(ft, "dialog_licenses");
}
public static class OpenSourceLicensesDialog extends DialogFragment {
public OpenSourceLicensesDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
WebView webView = new WebView(getActivity());
webView.loadUrl("file:///android_asset/licenses.html");
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_licenses)
.setView(webView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
public static void showEula(FragmentActivity activity) {
FragmentManager fm = activity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("dialog_eula");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
new EulaDialog().show(ft, "dialog_eula");
}
public static class EulaDialog extends DialogFragment {
public EulaDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int padding = getResources().getDimensionPixelSize(R.dimen.content_padding_normal);
TextView eulaTextView = new TextView(getActivity());
eulaTextView.setText(Html.fromHtml(getString(R.string.eula_text)));
eulaTextView.setMovementMethod(LinkMovementMethod.getInstance());
eulaTextView.setPadding(padding, padding, padding, padding);
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.about_eula)
.setView(eulaTextView)
.setPositiveButton(R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
}
)
.create();
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/HelpUtils.java
|
Java
|
asf20
| 11,150
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Modifications:
* -Imported from AOSP frameworks/base/core/java/com/android/internal/content
* -Changed package name
*/
package com.google.android.apps.iosched.util;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Helper for building selection clauses for {@link SQLiteDatabase}. Each
* appended clause is combined using {@code AND}. This class is <em>not</em>
* thread safe.
*/
public class SelectionBuilder {
private static final String TAG = makeLogTag(SelectionBuilder.class);
private String mTable = null;
private Map<String, String> mProjectionMap = Maps.newHashMap();
private StringBuilder mSelection = new StringBuilder();
private ArrayList<String> mSelectionArgs = Lists.newArrayList();
/**
* Reset any internal state, allowing this builder to be recycled.
*/
public SelectionBuilder reset() {
mTable = null;
mSelection.setLength(0);
mSelectionArgs.clear();
return this;
}
/**
* Append the given selection clause to the internal state. Each clause is
* surrounded with parenthesis and combined using {@code AND}.
*/
public SelectionBuilder where(String selection, String... selectionArgs) {
if (TextUtils.isEmpty(selection)) {
if (selectionArgs != null && selectionArgs.length > 0) {
throw new IllegalArgumentException(
"Valid selection required when including arguments=");
}
// Shortcut when clause is empty
return this;
}
if (mSelection.length() > 0) {
mSelection.append(" AND ");
}
mSelection.append("(").append(selection).append(")");
if (selectionArgs != null) {
Collections.addAll(mSelectionArgs, selectionArgs);
}
return this;
}
public SelectionBuilder table(String table) {
mTable = table;
return this;
}
private void assertTable() {
if (mTable == null) {
throw new IllegalStateException("Table not specified");
}
}
public SelectionBuilder mapToTable(String column, String table) {
mProjectionMap.put(column, table + "." + column);
return this;
}
public SelectionBuilder map(String fromColumn, String toClause) {
mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn);
return this;
}
/**
* Return selection string for current internal state.
*
* @see #getSelectionArgs()
*/
public String getSelection() {
return mSelection.toString();
}
/**
* Return selection arguments for current internal state.
*
* @see #getSelection()
*/
public String[] getSelectionArgs() {
return mSelectionArgs.toArray(new String[mSelectionArgs.size()]);
}
private void mapColumns(String[] columns) {
for (int i = 0; i < columns.length; i++) {
final String target = mProjectionMap.get(columns[i]);
if (target != null) {
columns[i] = target;
}
}
}
@Override
public String toString() {
return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection()
+ ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]";
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) {
return query(db, columns, null, null, orderBy, null);
}
/**
* Execute query using the current internal state as {@code WHERE} clause.
*/
public Cursor query(SQLiteDatabase db, String[] columns, String groupBy,
String having, String orderBy, String limit) {
assertTable();
if (columns != null) mapColumns(columns);
LOGV(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this);
return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having,
orderBy, limit);
}
/**
* Execute update using the current internal state as {@code WHERE} clause.
*/
public int update(SQLiteDatabase db, ContentValues values) {
assertTable();
LOGV(TAG, "update() " + this);
return db.update(mTable, values, getSelection(), getSelectionArgs());
}
/**
* Execute delete using the current internal state as {@code WHERE} clause.
*/
public int delete(SQLiteDatabase db) {
assertTable();
LOGV(TAG, "delete() " + this);
return db.delete(mTable, getSelection(), getSelectionArgs());
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/SelectionBuilder.java
|
Java
|
asf20
| 5,630
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import java.io.BufferedInputStream;
import java.io.BufferedWriter;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Array;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
******************************************************************************
* Taken from the JB source code, can be found in:
* libcore/luni/src/main/java/libcore/io/DiskLruCache.java
* or direct link:
* https://android.googlesource.com/platform/libcore/+/android-4.1.1_r1/luni/src/main/java/libcore/io/DiskLruCache.java
******************************************************************************
*
* A cache that uses a bounded amount of space on a filesystem. Each cache
* entry has a string key and a fixed number of values. Values are byte
* sequences, accessible as streams or files. Each value must be between {@code
* 0} and {@code Integer.MAX_VALUE} bytes in length.
*
* <p>The cache stores its data in a directory on the filesystem. This
* directory must be exclusive to the cache; the cache may delete or overwrite
* files from its directory. It is an error for multiple processes to use the
* same cache directory at the same time.
*
* <p>This cache limits the number of bytes that it will store on the
* filesystem. When the number of stored bytes exceeds the limit, the cache will
* remove entries in the background until the limit is satisfied. The limit is
* not strict: the cache may temporarily exceed it while waiting for files to be
* deleted. The limit does not include filesystem overhead or the cache
* journal so space-sensitive applications should set a conservative limit.
*
* <p>Clients call {@link #edit} to create or update the values of an entry. An
* entry may have only one editor at one time; if a value is not available to be
* edited then {@link #edit} will return null.
* <ul>
* <li>When an entry is being <strong>created</strong> it is necessary to
* supply a full set of values; the empty value should be used as a
* placeholder if necessary.
* <li>When an entry is being <strong>edited</strong>, it is not necessary
* to supply data for every value; values default to their previous
* value.
* </ul>
* Every {@link #edit} call must be matched by a call to {@link Editor#commit}
* or {@link Editor#abort}. Committing is atomic: a read observes the full set
* of values as they were before or after the commit, but never a mix of values.
*
* <p>Clients call {@link #get} to read a snapshot of an entry. The read will
* observe the value at the time that {@link #get} was called. Updates and
* removals after the call do not impact ongoing reads.
*
* <p>This class is tolerant of some I/O errors. If files are missing from the
* filesystem, the corresponding entries will be dropped from the cache. If
* an error occurs while writing a cache value, the edit will fail silently.
* Callers should handle other problems by catching {@code IOException} and
* responding appropriately.
*/
public final class DiskLruCache implements Closeable {
static final String JOURNAL_FILE = "journal";
static final String JOURNAL_FILE_TMP = "journal.tmp";
static final String MAGIC = "libcore.io.DiskLruCache";
static final String VERSION_1 = "1";
static final long ANY_SEQUENCE_NUMBER = -1;
private static final String CLEAN = "CLEAN";
private static final String DIRTY = "DIRTY";
private static final String REMOVE = "REMOVE";
private static final String READ = "READ";
private static final Charset UTF_8 = Charset.forName("UTF-8");
private static final int IO_BUFFER_SIZE = 8 * 1024;
/*
* This cache uses a journal file named "journal". A typical journal file
* looks like this:
* libcore.io.DiskLruCache
* 1
* 100
* 2
*
* CLEAN 3400330d1dfc7f3f7f4b8d4d803dfcf6 832 21054
* DIRTY 335c4c6028171cfddfbaae1a9c313c52
* CLEAN 335c4c6028171cfddfbaae1a9c313c52 3934 2342
* REMOVE 335c4c6028171cfddfbaae1a9c313c52
* DIRTY 1ab96a171faeeee38496d8b330771a7a
* CLEAN 1ab96a171faeeee38496d8b330771a7a 1600 234
* READ 335c4c6028171cfddfbaae1a9c313c52
* READ 3400330d1dfc7f3f7f4b8d4d803dfcf6
*
* The first five lines of the journal form its header. They are the
* constant string "libcore.io.DiskLruCache", the disk cache's version,
* the application's version, the value count, and a blank line.
*
* Each of the subsequent lines in the file is a record of the state of a
* cache entry. Each line contains space-separated values: a state, a key,
* and optional state-specific values.
* o DIRTY lines track that an entry is actively being created or updated.
* Every successful DIRTY action should be followed by a CLEAN or REMOVE
* action. DIRTY lines without a matching CLEAN or REMOVE indicate that
* temporary files may need to be deleted.
* o CLEAN lines track a cache entry that has been successfully published
* and may be read. A publish line is followed by the lengths of each of
* its values.
* o READ lines track accesses for LRU.
* o REMOVE lines track entries that have been deleted.
*
* The journal file is appended to as cache operations occur. The journal may
* occasionally be compacted by dropping redundant lines. A temporary file named
* "journal.tmp" will be used during compaction; that file should be deleted if
* it exists when the cache is opened.
*/
private final File directory;
private final File journalFile;
private final File journalFileTmp;
private final int appVersion;
private final long maxSize;
private final int valueCount;
private long size = 0;
private Writer journalWriter;
private final LinkedHashMap<String, Entry> lruEntries
= new LinkedHashMap<String, Entry>(0, 0.75f, true);
private int redundantOpCount;
/**
* To differentiate between old and current snapshots, each entry is given
* a sequence number each time an edit is committed. A snapshot is stale if
* its sequence number is not equal to its entry's sequence number.
*/
private long nextSequenceNumber = 0;
/* From java.util.Arrays */
@SuppressWarnings("unchecked")
private static <T> T[] copyOfRange(T[] original, int start, int end) {
final int originalLength = original.length; // For exception priority compatibility.
if (start > end) {
throw new IllegalArgumentException();
}
if (start < 0 || start > originalLength) {
throw new ArrayIndexOutOfBoundsException();
}
final int resultLength = end - start;
final int copyLength = Math.min(resultLength, originalLength - start);
final T[] result = (T[]) Array
.newInstance(original.getClass().getComponentType(), resultLength);
System.arraycopy(original, start, result, 0, copyLength);
return result;
}
/**
* Returns the remainder of 'reader' as a string, closing it when done.
*/
public static String readFully(Reader reader) throws IOException {
try {
StringWriter writer = new StringWriter();
char[] buffer = new char[1024];
int count;
while ((count = reader.read(buffer)) != -1) {
writer.write(buffer, 0, count);
}
return writer.toString();
} finally {
reader.close();
}
}
/**
* Returns the ASCII characters up to but not including the next "\r\n", or
* "\n".
*
* @throws java.io.EOFException if the stream is exhausted before the next newline
* character.
*/
public static String readAsciiLine(InputStream in) throws IOException {
// TODO: support UTF-8 here instead
StringBuilder result = new StringBuilder(80);
while (true) {
int c = in.read();
if (c == -1) {
throw new EOFException();
} else if (c == '\n') {
break;
}
result.append((char) c);
}
int length = result.length();
if (length > 0 && result.charAt(length - 1) == '\r') {
result.setLength(length - 1);
}
return result.toString();
}
/**
* Closes 'closeable', ignoring any checked exceptions. Does nothing if 'closeable' is null.
*/
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (RuntimeException rethrown) {
throw rethrown;
} catch (Exception ignored) {
}
}
}
/**
* Recursively delete everything in {@code dir}.
*/
// TODO: this should specify paths as Strings rather than as Files
public static void deleteContents(File dir) throws IOException {
File[] files = dir.listFiles();
if (files == null) {
throw new IllegalArgumentException("not a directory: " + dir);
}
for (File file : files) {
if (file.isDirectory()) {
deleteContents(file);
}
if (!file.delete()) {
throw new IOException("failed to delete file: " + file);
}
}
}
/** This cache uses a single background thread to evict entries. */
private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
private final Callable<Void> cleanupCallable = new Callable<Void>() {
@Override public Void call() throws Exception {
synchronized (DiskLruCache.this) {
if (journalWriter == null) {
return null; // closed
}
trimToSize();
if (journalRebuildRequired()) {
rebuildJournal();
redundantOpCount = 0;
}
}
return null;
}
};
private DiskLruCache(File directory, int appVersion, int valueCount, long maxSize) {
this.directory = directory;
this.appVersion = appVersion;
this.journalFile = new File(directory, JOURNAL_FILE);
this.journalFileTmp = new File(directory, JOURNAL_FILE_TMP);
this.valueCount = valueCount;
this.maxSize = maxSize;
}
/**
* Opens the cache in {@code directory}, creating a cache if none exists
* there.
*
* @param directory a writable directory
* @param appVersion
* @param valueCount the number of values per cache entry. Must be positive.
* @param maxSize the maximum number of bytes this cache should use to store
* @throws IOException if reading or writing the cache directory fails
*/
public static DiskLruCache open(File directory, int appVersion, int valueCount, long maxSize)
throws IOException {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
if (valueCount <= 0) {
throw new IllegalArgumentException("valueCount <= 0");
}
// prefer to pick up where we left off
DiskLruCache cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
if (cache.journalFile.exists()) {
try {
cache.readJournal();
cache.processJournal();
cache.journalWriter = new BufferedWriter(new FileWriter(cache.journalFile, true),
IO_BUFFER_SIZE);
return cache;
} catch (IOException journalIsCorrupt) {
// System.logW("DiskLruCache " + directory + " is corrupt: "
// + journalIsCorrupt.getMessage() + ", removing");
cache.delete();
}
}
// create a new empty cache
directory.mkdirs();
cache = new DiskLruCache(directory, appVersion, valueCount, maxSize);
cache.rebuildJournal();
return cache;
}
private void readJournal() throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(journalFile), IO_BUFFER_SIZE);
try {
String magic = readAsciiLine(in);
String version = readAsciiLine(in);
String appVersionString = readAsciiLine(in);
String valueCountString = readAsciiLine(in);
String blank = readAsciiLine(in);
if (!MAGIC.equals(magic)
|| !VERSION_1.equals(version)
|| !Integer.toString(appVersion).equals(appVersionString)
|| !Integer.toString(valueCount).equals(valueCountString)
|| !"".equals(blank)) {
throw new IOException("unexpected journal header: ["
+ magic + ", " + version + ", " + valueCountString + ", " + blank + "]");
}
while (true) {
try {
readJournalLine(readAsciiLine(in));
} catch (EOFException endOfJournal) {
break;
}
}
} finally {
closeQuietly(in);
}
}
private void readJournalLine(String line) throws IOException {
String[] parts = line.split(" ");
if (parts.length < 2) {
throw new IOException("unexpected journal line: " + line);
}
String key = parts[1];
if (parts[0].equals(REMOVE) && parts.length == 2) {
lruEntries.remove(key);
return;
}
Entry entry = lruEntries.get(key);
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
}
if (parts[0].equals(CLEAN) && parts.length == 2 + valueCount) {
entry.readable = true;
entry.currentEditor = null;
entry.setLengths(copyOfRange(parts, 2, parts.length));
} else if (parts[0].equals(DIRTY) && parts.length == 2) {
entry.currentEditor = new Editor(entry);
} else if (parts[0].equals(READ) && parts.length == 2) {
// this work was already done by calling lruEntries.get()
} else {
throw new IOException("unexpected journal line: " + line);
}
}
/**
* Computes the initial size and collects garbage as a part of opening the
* cache. Dirty entries are assumed to be inconsistent and will be deleted.
*/
private void processJournal() throws IOException {
deleteIfExists(journalFileTmp);
for (Iterator<Entry> i = lruEntries.values().iterator(); i.hasNext(); ) {
Entry entry = i.next();
if (entry.currentEditor == null) {
for (int t = 0; t < valueCount; t++) {
size += entry.lengths[t];
}
} else {
entry.currentEditor = null;
for (int t = 0; t < valueCount; t++) {
deleteIfExists(entry.getCleanFile(t));
deleteIfExists(entry.getDirtyFile(t));
}
i.remove();
}
}
}
/**
* Creates a new journal that omits redundant information. This replaces the
* current journal if it exists.
*/
private synchronized void rebuildJournal() throws IOException {
if (journalWriter != null) {
journalWriter.close();
}
Writer writer = new BufferedWriter(new FileWriter(journalFileTmp), IO_BUFFER_SIZE);
writer.write(MAGIC);
writer.write("\n");
writer.write(VERSION_1);
writer.write("\n");
writer.write(Integer.toString(appVersion));
writer.write("\n");
writer.write(Integer.toString(valueCount));
writer.write("\n");
writer.write("\n");
for (Entry entry : lruEntries.values()) {
if (entry.currentEditor != null) {
writer.write(DIRTY + ' ' + entry.key + '\n');
} else {
writer.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
}
}
writer.close();
journalFileTmp.renameTo(journalFile);
journalWriter = new BufferedWriter(new FileWriter(journalFile, true), IO_BUFFER_SIZE);
}
private static void deleteIfExists(File file) throws IOException {
// try {
// Libcore.os.remove(file.getPath());
// } catch (ErrnoException errnoException) {
// if (errnoException.errno != OsConstants.ENOENT) {
// throw errnoException.rethrowAsIOException();
// }
// }
if (file.exists() && !file.delete()) {
throw new IOException();
}
}
/**
* Returns a snapshot of the entry named {@code key}, or null if it doesn't
* exist is not currently readable. If a value is returned, it is moved to
* the head of the LRU queue.
*/
public synchronized Snapshot get(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null) {
return null;
}
if (!entry.readable) {
return null;
}
/*
* Open all streams eagerly to guarantee that we see a single published
* snapshot. If we opened streams lazily then the streams could come
* from different edits.
*/
InputStream[] ins = new InputStream[valueCount];
try {
for (int i = 0; i < valueCount; i++) {
ins[i] = new FileInputStream(entry.getCleanFile(i));
}
} catch (FileNotFoundException e) {
// a file must have been deleted manually!
return null;
}
redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return new Snapshot(key, entry.sequenceNumber, ins);
}
/**
* Returns an editor for the entry named {@code key}, or null if another
* edit is in progress.
*/
public Editor edit(String key) throws IOException {
return edit(key, ANY_SEQUENCE_NUMBER);
}
private synchronized Editor edit(String key, long expectedSequenceNumber) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (expectedSequenceNumber != ANY_SEQUENCE_NUMBER
&& (entry == null || entry.sequenceNumber != expectedSequenceNumber)) {
return null; // snapshot is stale
}
if (entry == null) {
entry = new Entry(key);
lruEntries.put(key, entry);
} else if (entry.currentEditor != null) {
return null; // another edit is in progress
}
Editor editor = new Editor(entry);
entry.currentEditor = editor;
// flush the journal before creating files to prevent file leaks
journalWriter.write(DIRTY + ' ' + key + '\n');
journalWriter.flush();
return editor;
}
/**
* Returns the directory where this cache stores its data.
*/
public File getDirectory() {
return directory;
}
/**
* Returns the maximum number of bytes that this cache should use to store
* its data.
*/
public long maxSize() {
return maxSize;
}
/**
* Returns the number of bytes currently being used to store the values in
* this cache. This may be greater than the max size if a background
* deletion is pending.
*/
public synchronized long size() {
return size;
}
private synchronized void completeEdit(Editor editor, boolean success) throws IOException {
Entry entry = editor.entry;
if (entry.currentEditor != editor) {
throw new IllegalStateException();
}
// if this edit is creating the entry for the first time, every index must have a value
if (success && !entry.readable) {
for (int i = 0; i < valueCount; i++) {
if (!entry.getDirtyFile(i).exists()) {
editor.abort();
throw new IllegalStateException("edit didn't create file " + i);
}
}
}
for (int i = 0; i < valueCount; i++) {
File dirty = entry.getDirtyFile(i);
if (success) {
if (dirty.exists()) {
File clean = entry.getCleanFile(i);
dirty.renameTo(clean);
long oldLength = entry.lengths[i];
long newLength = clean.length();
entry.lengths[i] = newLength;
size = size - oldLength + newLength;
}
} else {
deleteIfExists(dirty);
}
}
redundantOpCount++;
entry.currentEditor = null;
if (entry.readable | success) {
entry.readable = true;
journalWriter.write(CLEAN + ' ' + entry.key + entry.getLengths() + '\n');
if (success) {
entry.sequenceNumber = nextSequenceNumber++;
}
} else {
lruEntries.remove(entry.key);
journalWriter.write(REMOVE + ' ' + entry.key + '\n');
}
if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
}
/**
* We only rebuild the journal when it will halve the size of the journal
* and eliminate at least 2000 ops.
*/
private boolean journalRebuildRequired() {
final int REDUNDANT_OP_COMPACT_THRESHOLD = 2000;
return redundantOpCount >= REDUNDANT_OP_COMPACT_THRESHOLD
&& redundantOpCount >= lruEntries.size();
}
/**
* Drops the entry for {@code key} if it exists and can be removed. Entries
* actively being edited cannot be removed.
*
* @return true if an entry was removed.
*/
public synchronized boolean remove(String key) throws IOException {
checkNotClosed();
validateKey(key);
Entry entry = lruEntries.get(key);
if (entry == null || entry.currentEditor != null) {
return false;
}
for (int i = 0; i < valueCount; i++) {
File file = entry.getCleanFile(i);
if (!file.delete()) {
throw new IOException("failed to delete " + file);
}
size -= entry.lengths[i];
entry.lengths[i] = 0;
}
redundantOpCount++;
journalWriter.append(REMOVE + ' ' + key + '\n');
lruEntries.remove(key);
if (journalRebuildRequired()) {
executorService.submit(cleanupCallable);
}
return true;
}
/**
* Returns true if this cache has been closed.
*/
public boolean isClosed() {
return journalWriter == null;
}
private void checkNotClosed() {
if (journalWriter == null) {
throw new IllegalStateException("cache is closed");
}
}
/**
* Force buffered operations to the filesystem.
*/
public synchronized void flush() throws IOException {
checkNotClosed();
trimToSize();
journalWriter.flush();
}
/**
* Closes this cache. Stored values will remain on the filesystem.
*/
public synchronized void close() throws IOException {
if (journalWriter == null) {
return; // already closed
}
for (Entry entry : new ArrayList<Entry>(lruEntries.values())) {
if (entry.currentEditor != null) {
entry.currentEditor.abort();
}
}
trimToSize();
journalWriter.close();
journalWriter = null;
}
private void trimToSize() throws IOException {
while (size > maxSize) {
// Map.Entry<String, Entry> toEvict = lruEntries.eldest();
final Map.Entry<String, Entry> toEvict = lruEntries.entrySet().iterator().next();
remove(toEvict.getKey());
}
}
/**
* Closes the cache and deletes all of its stored values. This will delete
* all files in the cache directory including files that weren't created by
* the cache.
*/
public void delete() throws IOException {
close();
deleteContents(directory);
}
private void validateKey(String key) {
if (key.contains(" ") || key.contains("\n") || key.contains("\r")) {
throw new IllegalArgumentException(
"keys must not contain spaces or newlines: \"" + key + "\"");
}
}
private static String inputStreamToString(InputStream in) throws IOException {
return readFully(new InputStreamReader(in, UTF_8));
}
/**
* A snapshot of the values for an entry.
*/
public final class Snapshot implements Closeable {
private final String key;
private final long sequenceNumber;
private final InputStream[] ins;
private Snapshot(String key, long sequenceNumber, InputStream[] ins) {
this.key = key;
this.sequenceNumber = sequenceNumber;
this.ins = ins;
}
/**
* Returns an editor for this snapshot's entry, or null if either the
* entry has changed since this snapshot was created or if another edit
* is in progress.
*/
public Editor edit() throws IOException {
return DiskLruCache.this.edit(key, sequenceNumber);
}
/**
* Returns the unbuffered stream with the value for {@code index}.
*/
public InputStream getInputStream(int index) {
return ins[index];
}
/**
* Returns the string value for {@code index}.
*/
public String getString(int index) throws IOException {
return inputStreamToString(getInputStream(index));
}
@Override public void close() {
for (InputStream in : ins) {
closeQuietly(in);
}
}
}
/**
* Edits the values for an entry.
*/
public final class Editor {
private final Entry entry;
private boolean hasErrors;
private Editor(Entry entry) {
this.entry = entry;
}
/**
* Returns an unbuffered input stream to read the last committed value,
* or null if no value has been committed.
*/
public InputStream newInputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
if (!entry.readable) {
return null;
}
return new FileInputStream(entry.getCleanFile(index));
}
}
/**
* Returns the last committed value as a string, or null if no value
* has been committed.
*/
public String getString(int index) throws IOException {
InputStream in = newInputStream(index);
return in != null ? inputStreamToString(in) : null;
}
/**
* Returns a new unbuffered output stream to write the value at
* {@code index}. If the underlying output stream encounters errors
* when writing to the filesystem, this edit will be aborted when
* {@link #commit} is called. The returned output stream does not throw
* IOExceptions.
*/
public OutputStream newOutputStream(int index) throws IOException {
synchronized (DiskLruCache.this) {
if (entry.currentEditor != this) {
throw new IllegalStateException();
}
return new FaultHidingOutputStream(new FileOutputStream(entry.getDirtyFile(index)));
}
}
/**
* Sets the value at {@code index} to {@code value}.
*/
public void set(int index, String value) throws IOException {
Writer writer = null;
try {
writer = new OutputStreamWriter(newOutputStream(index), UTF_8);
writer.write(value);
} finally {
closeQuietly(writer);
}
}
/**
* Commits this edit so it is visible to readers. This releases the
* edit lock so another edit may be started on the same key.
*/
public void commit() throws IOException {
if (hasErrors) {
completeEdit(this, false);
remove(entry.key); // the previous entry is stale
} else {
completeEdit(this, true);
}
}
/**
* Aborts this edit. This releases the edit lock so another edit may be
* started on the same key.
*/
public void abort() throws IOException {
completeEdit(this, false);
}
private class FaultHidingOutputStream extends FilterOutputStream {
private FaultHidingOutputStream(OutputStream out) {
super(out);
}
@Override public void write(int oneByte) {
try {
out.write(oneByte);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void write(byte[] buffer, int offset, int length) {
try {
out.write(buffer, offset, length);
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void close() {
try {
out.close();
} catch (IOException e) {
hasErrors = true;
}
}
@Override public void flush() {
try {
out.flush();
} catch (IOException e) {
hasErrors = true;
}
}
}
}
private final class Entry {
private final String key;
/** Lengths of this entry's files. */
private final long[] lengths;
/** True if this entry has ever been published */
private boolean readable;
/** The ongoing edit or null if this entry is not being edited. */
private Editor currentEditor;
/** The sequence number of the most recently committed edit to this entry. */
private long sequenceNumber;
private Entry(String key) {
this.key = key;
this.lengths = new long[valueCount];
}
public String getLengths() throws IOException {
StringBuilder result = new StringBuilder();
for (long size : lengths) {
result.append(' ').append(size);
}
return result.toString();
}
/**
* Set lengths using decimal numbers like "10123".
*/
private void setLengths(String[] strings) throws IOException {
if (strings.length != valueCount) {
throw invalidLengths(strings);
}
try {
for (int i = 0; i < strings.length; i++) {
lengths[i] = Long.parseLong(strings[i]);
}
} catch (NumberFormatException e) {
throw invalidLengths(strings);
}
}
private IOException invalidLengths(String[] strings) throws IOException {
throw new IOException("unexpected journal line: " + Arrays.toString(strings));
}
public File getCleanFile(int i) {
return new File(directory, key + "." + i);
}
public File getDirtyFile(int i) {
return new File(directory, key + "." + i + ".tmp");
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/DiskLruCache.java
|
Java
|
asf20
| 33,892
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.util.Log;
/**
* Helper methods that make logging more consistent throughout the app.
*/
public class LogUtils {
private static final String LOG_PREFIX = "iosched_";
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
private static final int MAX_LOG_TAG_LENGTH = 23;
public static String makeLogTag(String str) {
if (str.length() > MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH) {
return LOG_PREFIX + str.substring(0, MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 1);
}
return LOG_PREFIX + str;
}
/**
* WARNING: Don't use this when obfuscating class names with Proguard!
*/
public static String makeLogTag(Class cls) {
return makeLogTag(cls.getSimpleName());
}
public static void LOGD(final String tag, String message) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message);
}
}
public static void LOGD(final String tag, String message, Throwable cause) {
if (Log.isLoggable(tag, Log.DEBUG)) {
Log.d(tag, message, cause);
}
}
public static void LOGV(final String tag, String message) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message);
}
}
public static void LOGV(final String tag, String message, Throwable cause) {
//noinspection PointlessBooleanExpression,ConstantConditions
if (BuildConfig.DEBUG && Log.isLoggable(tag, Log.VERBOSE)) {
Log.v(tag, message, cause);
}
}
public static void LOGI(final String tag, String message) {
Log.i(tag, message);
}
public static void LOGI(final String tag, String message, Throwable cause) {
Log.i(tag, message, cause);
}
public static void LOGW(final String tag, String message) {
Log.w(tag, message);
}
public static void LOGW(final String tag, String message, Throwable cause) {
Log.w(tag, message, cause);
}
public static void LOGE(final String tag, String message) {
Log.e(tag, message);
}
public static void LOGE(final String tag, String message, Throwable cause) {
Log.e(tag, message, cause);
}
private LogUtils() {
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/LogUtils.java
|
Java
|
asf20
| 3,045
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import java.util.HashMap;
/**
* Provides static methods for creating mutable {@code Maps} instances easily.
*/
public class Maps {
/**
* Creates a {@code HashMap} instance.
*
* @return a newly-created, initially-empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/Maps.java
|
Java
|
asf20
| 1,006
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract.Blocks;
import com.google.android.apps.iosched.provider.ScheduleContract.Rooms;
import com.google.android.apps.iosched.ui.phone.MapActivity;
import com.google.android.apps.iosched.ui.phone.SessionDetailActivity;
import com.google.android.apps.iosched.ui.phone.SessionsActivity;
import com.google.android.apps.iosched.ui.phone.TrackDetailActivity;
import com.google.android.apps.iosched.ui.phone.VendorDetailActivity;
import com.google.android.apps.iosched.ui.tablet.MapMultiPaneActivity;
import com.google.android.apps.iosched.ui.tablet.SessionsVendorsMultiPaneActivity;
import android.annotation.TargetApi;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import java.util.Formatter;
import java.util.Locale;
import java.util.TimeZone;
/**
* An assortment of UI helpers.
*/
public class UIUtils {
/**
* Time zone to use when formatting all session times. To always use the
* phone local time, use {@link TimeZone#getDefault()}.
*/
public static final TimeZone CONFERENCE_TIME_ZONE = TimeZone.getTimeZone("America/Los_Angeles");
public static final long CONFERENCE_START_MILLIS = ParserUtils.parseTime(
"2012-06-27T09:30:00.000-07:00");
public static final long CONFERENCE_END_MILLIS = ParserUtils.parseTime(
"2012-06-29T18:00:00.000-07:00");
public static final String CONFERENCE_HASHTAG = "#io12";
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
/** Flags used with {@link DateUtils#formatDateRange}. */
private static final int TIME_FLAGS = DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY;
/** {@link StringBuilder} used for formatting time block. */
private static StringBuilder sBuilder = new StringBuilder(50);
/** {@link Formatter} used for formatting time block. */
private static Formatter sFormatter = new Formatter(sBuilder, Locale.getDefault());
private static StyleSpan sBoldSpan = new StyleSpan(Typeface.BOLD);
private static CharSequence sEmptyRoomText;
private static CharSequence sCodeLabRoomText;
private static CharSequence sNowPlayingText;
private static CharSequence sLivestreamNowText;
private static CharSequence sLivestreamAvailableText;
public static final String GOOGLE_PLUS_PACKAGE_NAME = "com.google.android.apps.plus";
/**
* Format and return the given {@link Blocks} and {@link Rooms} values using
* {@link #CONFERENCE_TIME_ZONE}.
*/
public static String formatSessionSubtitle(String sessionTitle,
long blockStart, long blockEnd, String roomName, Context context) {
if (sEmptyRoomText == null || sCodeLabRoomText == null) {
sEmptyRoomText = context.getText(R.string.unknown_room);
sCodeLabRoomText = context.getText(R.string.codelab_room);
}
if (roomName == null) {
// TODO: remove the WAR for API not returning rooms for code labs
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, context),
sessionTitle.contains("Code Lab")
? sCodeLabRoomText
: sEmptyRoomText);
}
return context.getString(R.string.session_subtitle,
formatBlockTimeString(blockStart, blockEnd, context), roomName);
}
/**
* Format and return the given {@link Blocks} values using
* {@link #CONFERENCE_TIME_ZONE}.
*/
public static String formatBlockTimeString(long blockStart, long blockEnd, Context context) {
TimeZone.setDefault(CONFERENCE_TIME_ZONE);
// NOTE: There is an efficient version of formatDateRange in Eclair and
// beyond that allows you to recycle a StringBuilder.
return DateUtils.formatDateRange(context, blockStart, blockEnd, TIME_FLAGS);
}
public static boolean isSameDay(long time1, long time2) {
TimeZone.setDefault(CONFERENCE_TIME_ZONE);
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTimeInMillis(time1);
cal2.setTimeInMillis(time2);
return cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);
}
public static String getTimeAgo(long time, Context ctx) {
if (time < 1000000000000L) {
// if timestamp given in seconds, convert to millis
time *= 1000;
}
long now = getCurrentTime(ctx);
if (time > now || time <= 0) {
return null;
}
// TODO: localize
final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "just now";
} else if (diff < 2 * MINUTE_MILLIS) {
return "a minute ago";
} else if (diff < 50 * MINUTE_MILLIS) {
return diff / MINUTE_MILLIS + " minutes ago";
} else if (diff < 90 * MINUTE_MILLIS) {
return "an hour ago";
} else if (diff < 24 * HOUR_MILLIS) {
return diff / HOUR_MILLIS + " hours ago";
} else if (diff < 48 * HOUR_MILLIS) {
return "yesterday";
} else {
return diff / DAY_MILLIS + " days ago";
}
}
/**
* Populate the given {@link TextView} with the requested text, formatting
* through {@link Html#fromHtml(String)} when applicable. Also sets
* {@link TextView#setMovementMethod} so inline links are handled.
*/
public static void setTextMaybeHtml(TextView view, String text) {
if (TextUtils.isEmpty(text)) {
view.setText("");
return;
}
if (text.contains("<") && text.contains(">")) {
view.setText(Html.fromHtml(text));
view.setMovementMethod(LinkMovementMethod.getInstance());
} else {
view.setText(text);
}
}
public static void updateTimeAndLivestreamBlockUI(final Context context,
long blockStart, long blockEnd, boolean hasLivestream,
View backgroundView, TextView titleView, TextView subtitleView,
CharSequence subtitle) {
long currentTimeMillis = getCurrentTime(context);
boolean past = (currentTimeMillis > blockEnd && currentTimeMillis < CONFERENCE_END_MILLIS);
boolean present = (blockStart <= currentTimeMillis && currentTimeMillis <= blockEnd);
final Resources res = context.getResources();
if (backgroundView != null) {
backgroundView.setBackgroundColor(past
? res.getColor(R.color.past_background_color)
: 0);
}
if (titleView != null) {
titleView.setTypeface(Typeface.SANS_SERIF, past ? Typeface.NORMAL : Typeface.BOLD);
}
if (subtitleView != null) {
boolean empty = true;
SpannableStringBuilder sb = new SpannableStringBuilder(); // TODO: recycle
if (subtitle != null) {
sb.append(subtitle);
empty = false;
}
if (present) {
if (sNowPlayingText == null) {
sNowPlayingText = Html.fromHtml(context.getString(R.string.now_playing_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sNowPlayingText);
if (hasLivestream) {
if (sLivestreamNowText == null) {
sLivestreamNowText = Html.fromHtml(" " +
context.getString(R.string.live_now_badge));
}
sb.append(sLivestreamNowText);
}
} else if (hasLivestream) {
if (sLivestreamAvailableText == null) {
sLivestreamAvailableText = Html.fromHtml(
context.getString(R.string.live_available_badge));
}
if (!empty) {
sb.append(" ");
}
sb.append(sLivestreamAvailableText);
}
subtitleView.setText(sb);
}
}
/**
* Given a snippet string with matching segments surrounded by curly
* braces, turn those areas into bold spans, removing the curly braces.
*/
public static Spannable buildStyledSnippet(String snippet) {
final SpannableStringBuilder builder = new SpannableStringBuilder(snippet);
// Walk through string, inserting bold snippet spans
int startIndex = -1, endIndex = -1, delta = 0;
while ((startIndex = snippet.indexOf('{', endIndex)) != -1) {
endIndex = snippet.indexOf('}', startIndex);
// Remove braces from both sides
builder.delete(startIndex - delta, startIndex - delta + 1);
builder.delete(endIndex - delta - 1, endIndex - delta);
// Insert bold style
builder.setSpan(sBoldSpan, startIndex - delta, endIndex - delta - 1,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
delta += 2;
}
return builder;
}
public static void preferPackageForIntent(Context context, Intent intent, String packageName) {
PackageManager pm = context.getPackageManager();
for (ResolveInfo resolveInfo : pm.queryIntentActivities(intent, 0)) {
if (resolveInfo.activityInfo.packageName.equals(packageName)) {
intent.setPackage(packageName);
break;
}
}
}
public static ImageFetcher getImageFetcher(final FragmentActivity activity) {
// The ImageFetcher takes care of loading remote images into our ImageView
ImageFetcher fetcher = new ImageFetcher(activity);
fetcher.addImageCache(activity);
return fetcher;
}
public static String getSessionHashtagsString(String hashtags) {
if (!TextUtils.isEmpty(hashtags)) {
if (!hashtags.startsWith("#")) {
hashtags = "#" + hashtags;
}
if (hashtags.contains(CONFERENCE_HASHTAG)) {
return hashtags;
}
return CONFERENCE_HASHTAG + " " + hashtags;
} else {
return CONFERENCE_HASHTAG;
}
}
private static final int BRIGHTNESS_THRESHOLD = 130;
/**
* Calculate whether a color is light or dark, based on a commonly known
* brightness formula.
*
* @see {@literal http://en.wikipedia.org/wiki/HSV_color_space%23Lightness}
*/
public static boolean isColorDark(int color) {
return ((30 * Color.red(color) +
59 * Color.green(color) +
11 * Color.blue(color)) / 100) <= BRIGHTNESS_THRESHOLD;
}
// Shows whether a notification was fired for a particular session time block. In the
// event that notification has not been fired yet, return false and set the bit.
public static boolean isNotificationFiredForBlock(Context context, String blockId) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
final String key = String.format("notification_fired_%s", blockId);
boolean fired = sp.getBoolean(key, false);
sp.edit().putBoolean(key, true).commit();
return fired;
}
private static final long sAppLoadTime = System.currentTimeMillis();
public static long getCurrentTime(final Context context) {
if (BuildConfig.DEBUG) {
return context.getSharedPreferences("mock_data", Context.MODE_PRIVATE)
.getLong("mock_current_time", System.currentTimeMillis())
+ System.currentTimeMillis() - sAppLoadTime;
} else {
return System.currentTimeMillis();
}
}
public static void safeOpenLink(Context context, Intent linkIntent) {
try {
context.startActivity(linkIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(context, "Couldn't open link", Toast.LENGTH_SHORT) .show();
}
}
// TODO: use <meta-data> element instead
private static final Class[] sPhoneActivities = new Class[]{
MapActivity.class,
SessionDetailActivity.class,
SessionsActivity.class,
TrackDetailActivity.class,
VendorDetailActivity.class,
};
// TODO: use <meta-data> element instead
private static final Class[] sTabletActivities = new Class[]{
MapMultiPaneActivity.class,
SessionsVendorsMultiPaneActivity.class,
};
public static void enableDisableActivities(final Context context) {
boolean isHoneycombTablet = isHoneycombTablet(context);
PackageManager pm = context.getPackageManager();
// Enable/disable phone activities
for (Class a : sPhoneActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
: PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
// Enable/disable tablet activities
for (Class a : sTabletActivities) {
pm.setComponentEnabledSetting(new ComponentName(context, a),
isHoneycombTablet
? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
: PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
}
public static Class getMapActivityClass(Context context) {
if (UIUtils.isHoneycombTablet(context)) {
return MapMultiPaneActivity.class;
}
return MapActivity.class;
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void setActivatedCompat(View view, boolean activated) {
if (hasHoneycomb()) {
view.setActivated(activated);
}
}
public static boolean isGoogleTV(Context context) {
return context.getPackageManager().hasSystemFeature("com.google.android.tv");
}
public static boolean hasFroyo() {
// Can use static final constants like FROYO, declared in later versions
// of the OS since they are inlined at compile time. This is guaranteed behavior.
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
}
public static boolean hasGingerbread() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
}
public static boolean hasHoneycomb() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
}
public static boolean hasHoneycombMR1() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
}
public static boolean hasICS() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
}
public static boolean hasJellyBean() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
}
public static boolean isTablet(Context context) {
return (context.getResources().getConfiguration().screenLayout
& Configuration.SCREENLAYOUT_SIZE_MASK)
>= Configuration.SCREENLAYOUT_SIZE_LARGE;
}
public static boolean isHoneycombTablet(Context context) {
return hasHoneycomb() && isTablet(context);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/UIUtils.java
|
Java
|
asf20
| 17,426
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* A subclass of {@link ImageWorker} that fetches images from a URL.
*/
public class ImageFetcher extends ImageWorker {
private static final String TAG = makeLogTag(ImageFetcher.class);
public static final int IO_BUFFER_SIZE_BYTES = 4 * 1024; // 4KB
// Default fetcher params
private static final int MAX_THUMBNAIL_BYTES = 70 * 1024; // 70KB
private static final int HTTP_CACHE_SIZE = 5 * 1024 * 1024; // 5MB
private static final String HTTP_CACHE_DIR = "http";
private static final int DEFAULT_IMAGE_HEIGHT = 1024;
private static final int DEFAULT_IMAGE_WIDTH = 1024;
protected int mImageWidth;
protected int mImageHeight;
private DiskLruCache mHttpDiskCache;
private File mHttpCacheDir;
private boolean mHttpDiskCacheStarting = true;
private final Object mHttpDiskCacheLock = new Object();
private static final int DISK_CACHE_INDEX = 0;
/**
* Create an ImageFetcher specifying max image loading width/height.
*/
public ImageFetcher(Context context, int imageWidth, int imageHeight) {
super(context);
init(context, imageWidth, imageHeight);
}
/**
* Create an ImageFetcher using defaults.
*/
public ImageFetcher(Context context) {
super(context);
init(context, DEFAULT_IMAGE_WIDTH, DEFAULT_IMAGE_HEIGHT);
}
private void init(Context context, int imageWidth, int imageHeight) {
mImageWidth = imageWidth;
mImageHeight = imageHeight;
mHttpCacheDir = ImageCache.getDiskCacheDir(context, HTTP_CACHE_DIR);
if (!mHttpCacheDir.exists()) {
mHttpCacheDir.mkdirs();
}
}
public void loadThumbnailImage(String key, ImageView imageView, Bitmap loadingBitmap) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, loadingBitmap);
}
public void loadThumbnailImage(String key, ImageView imageView, int resId) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, resId);
}
public void loadThumbnailImage(String key, ImageView imageView) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_THUMBNAIL), imageView, mLoadingBitmap);
}
public void loadImage(String key, ImageView imageView, Bitmap loadingBitmap) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, loadingBitmap);
}
public void loadImage(String key, ImageView imageView, int resId) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, resId);
}
public void loadImage(String key, ImageView imageView) {
loadImage(new ImageData(key, ImageData.IMAGE_TYPE_NORMAL), imageView, mLoadingBitmap);
}
/**
* Set the target image width and height.
*/
public void setImageSize(int width, int height) {
mImageWidth = width;
mImageHeight = height;
}
/**
* Set the target image size (width and height will be the same).
*/
public void setImageSize(int size) {
setImageSize(size, size);
}
/**
* The main process method, which will be called by the ImageWorker in the AsyncTask background
* thread.
*
* @param key The key to load the bitmap, in this case, a regular http URL
* @return The downloaded and resized bitmap
*/
private Bitmap processBitmap(String key, int type) {
LOGD(TAG, "processBitmap - " + key);
if (type == ImageData.IMAGE_TYPE_NORMAL) {
return processNormalBitmap(key); // Process a regular, full sized bitmap
} else if (type == ImageData.IMAGE_TYPE_THUMBNAIL) {
return processThumbnailBitmap(key); // Process a smaller, thumbnail bitmap
}
return null;
}
@Override
protected Bitmap processBitmap(Object key) {
final ImageData imageData = (ImageData) key;
return processBitmap(imageData.mKey, imageData.mType);
}
/**
* Download and resize a normal sized remote bitmap from a HTTP URL using a HTTP cache.
* @param urlString The URL of the image to download
* @return The scaled bitmap
*/
private Bitmap processNormalBitmap(String urlString) {
final String key = ImageCache.hashKeyForDisk(urlString);
FileDescriptor fileDescriptor = null;
FileInputStream fileInputStream = null;
DiskLruCache.Snapshot snapshot;
synchronized (mHttpDiskCacheLock) {
// Wait for disk cache to initialize
while (mHttpDiskCacheStarting) {
try {
mHttpDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mHttpDiskCache != null) {
try {
snapshot = mHttpDiskCache.get(key);
if (snapshot == null) {
LOGD(TAG, "processBitmap, not found in http cache, downloading...");
DiskLruCache.Editor editor = mHttpDiskCache.edit(key);
if (editor != null) {
if (downloadUrlToStream(urlString,
editor.newOutputStream(DISK_CACHE_INDEX))) {
editor.commit();
} else {
editor.abort();
}
}
snapshot = mHttpDiskCache.get(key);
}
if (snapshot != null) {
fileInputStream =
(FileInputStream) snapshot.getInputStream(DISK_CACHE_INDEX);
fileDescriptor = fileInputStream.getFD();
}
} catch (IOException e) {
LOGE(TAG, "processBitmap - " + e);
} catch (IllegalStateException e) {
LOGE(TAG, "processBitmap - " + e);
} finally {
if (fileDescriptor == null && fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
}
}
}
Bitmap bitmap = null;
if (fileDescriptor != null) {
bitmap = decodeSampledBitmapFromDescriptor(fileDescriptor, mImageWidth, mImageHeight);
}
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {}
}
return bitmap;
}
/**
* Download a thumbnail sized remote bitmap from a HTTP URL. No HTTP caching is done (the
* {@link ImageCache} that this eventually gets passed to will do it's own disk caching.
* @param urlString The URL of the image to download
* @return The bitmap
*/
private Bitmap processThumbnailBitmap(String urlString) {
final byte[] bitmapBytes =
downloadBitmapToMemory(urlString, MAX_THUMBNAIL_BYTES);
if (bitmapBytes != null) {
// Caution: we don't check the size of the bitmap here, we are relying on the output
// of downloadBitmapToMemory to not exceed our memory limits and load a huge bitmap
// into memory.
return BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
}
return null;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param urlString The URL to fetch
* @param maxBytes The maximum number of bytes to read before returning null to protect against
* OutOfMemory exceptions.
* @return A File pointing to the fetched bitmap
*/
public static byte[] downloadBitmapToMemory(String urlString, int maxBytes) {
LOGD(TAG, "downloadBitmapToMemory - downloading - " + urlString);
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
ByteArrayOutputStream out = null;
InputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new ByteArrayOutputStream(IO_BUFFER_SIZE_BYTES);
final byte[] buffer = new byte[128];
int total = 0;
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
total += bytesRead;
if (total > maxBytes) {
return null;
}
out.write(buffer, 0, bytesRead);
}
return out.toByteArray();
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmapToMemory - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (final IOException e) {}
}
return null;
}
/**
* Download a bitmap from a URL and write the content to an output stream.
*
* @param urlString The URL to fetch
* @param outputStream The outputStream to write to
* @return true if successful, false otherwise
*/
public boolean downloadUrlToStream(String urlString, OutputStream outputStream) {
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new BufferedOutputStream(outputStream, IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return true;
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (final IOException e) {}
}
return false;
}
/**
* Download a bitmap from a URL, write it to a disk and return the File pointer. This
* implementation uses a simple disk cache.
*
* @param urlString The URL to fetch
* @param cacheDir The directory to store the downloaded file
* @return A File pointing to the fetched bitmap
*/
public static File downloadBitmapToFile(String urlString, File cacheDir) {
LOGD(TAG, "downloadBitmap - downloading - " + urlString);
disableConnectionReuseIfNecessary();
HttpURLConnection urlConnection = null;
BufferedOutputStream out = null;
BufferedInputStream in = null;
try {
final File tempFile = File.createTempFile("bitmap", null, cacheDir);
final URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return null;
}
in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
return tempFile;
} catch (final IOException e) {
LOGE(TAG, "Error in downloadBitmap - " + e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
try {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
} catch (final IOException e) {}
}
return null;
}
/**
* Decode and sample down a bitmap from a file to the requested width and
* height.
*
* @param filename The full path of the file to decode
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect
* ratio and dimensions that are equal to or greater than the
* requested width and height
*/
public static Bitmap decodeSampledBitmapFromFile(String filename,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filename, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filename, options);
}
/**
* Decode and sample down a bitmap from a file input stream to the requested width and height.
*
* @param fileDescriptor The file descriptor to read from
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return A bitmap sampled down from the original with the same aspect ratio and dimensions
* that are equal to or greater than the requested width and height
*/
public static Bitmap decodeSampledBitmapFromDescriptor(
FileDescriptor fileDescriptor, int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFileDescriptor(fileDescriptor, null, options);
}
/**
* Calculate an inSampleSize for use in a
* {@link android.graphics.BitmapFactory.Options} object when decoding
* bitmaps using the decode* methods from {@link BitmapFactory}. This
* implementation calculates the closest inSampleSize that will result in
* the final decoded bitmap having a width and height equal to or larger
* than the requested width and height. This implementation does not ensure
* a power of 2 is returned for inSampleSize which can be faster when
* decoding but results in a larger bitmap which isn't as useful for caching
* purposes.
*
* @param options An options object with out* params already populated (run
* through a decode* method with inJustDecodeBounds==true
* @param reqWidth The requested width of the resulting bitmap
* @param reqHeight The requested height of the resulting bitmap
* @return The value to be used for inSampleSize
*/
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
// Calculate ratios of height and width to requested height and width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
// This offers some additional logic in case the image has a strange
// aspect ratio. For example, a panorama may have a much larger
// width than height. In these cases the total pixels might still
// end up being too large to fit comfortably in memory, so we should
// be more aggressive with sample down the image (=larger
// inSampleSize).
final float totalPixels = width * height;
// Anything more than 2x the requested pixels we'll sample down
// further.
final float totalReqPixelsCap = reqWidth * reqHeight * 2;
while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
inSampleSize++;
}
}
return inSampleSize;
}
/**
* Workaround for bug pre-Froyo, see here for more info:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*/
public static void disableConnectionReuseIfNecessary() {
// HTTP connection reuse which was buggy pre-froyo
if (hasHttpConnectionBug()) {
System.setProperty("http.keepAlive", "false");
}
}
/**
* Check if OS version has a http URLConnection bug. See here for more
* information:
* http://android-developers.blogspot.com/2011/09/androids-http-clients.html
*
* @return true if this OS version is affected, false otherwise
*/
public static boolean hasHttpConnectionBug() {
return !UIUtils.hasFroyo();
}
@Override
protected void initDiskCacheInternal() {
super.initDiskCacheInternal();
initHttpDiskCache();
}
private void initHttpDiskCache() {
if (!mHttpCacheDir.exists()) {
mHttpCacheDir.mkdirs();
}
synchronized (mHttpDiskCacheLock) {
if (ImageCache.getUsableSpace(mHttpCacheDir) > HTTP_CACHE_SIZE) {
try {
mHttpDiskCache = DiskLruCache.open(mHttpCacheDir, 1, 1, HTTP_CACHE_SIZE);
LOGD(TAG, "HTTP cache initialized");
} catch (IOException e) {
mHttpDiskCache = null;
}
}
mHttpDiskCacheStarting = false;
mHttpDiskCacheLock.notifyAll();
}
}
@Override
protected void clearCacheInternal() {
super.clearCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null && !mHttpDiskCache.isClosed()) {
try {
mHttpDiskCache.delete();
LOGD(TAG, "HTTP cache cleared");
} catch (IOException e) {
LOGE(TAG, "clearCacheInternal - " + e);
}
mHttpDiskCache = null;
mHttpDiskCacheStarting = true;
initHttpDiskCache();
}
}
}
@Override
protected void flushCacheInternal() {
super.flushCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
mHttpDiskCache.flush();
LOGD(TAG, "HTTP cache flushed");
} catch (IOException e) {
LOGE(TAG, "flush - " + e);
}
}
}
}
@Override
protected void closeCacheInternal() {
super.closeCacheInternal();
synchronized (mHttpDiskCacheLock) {
if (mHttpDiskCache != null) {
try {
if (!mHttpDiskCache.isClosed()) {
mHttpDiskCache.close();
mHttpDiskCache = null;
LOGD(TAG, "HTTP cache closed");
}
} catch (IOException e) {
LOGE(TAG, "closeCacheInternal - " + e);
}
}
}
}
private static class ImageData {
public static final int IMAGE_TYPE_THUMBNAIL = 0;
public static final int IMAGE_TYPE_NORMAL = 1;
public String mKey;
public int mType;
public ImageData(String key, int type) {
mKey = key;
mType = type;
}
@Override
public String toString() {
return mKey;
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/ImageFetcher.java
|
Java
|
asf20
| 22,614
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.calendar.SessionCalendarService;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.AccountActivity;
import com.google.android.gcm.GCMRegistrar;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.widget.Toast;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An assortment of authentication and login helper utilities.
*/
public class AccountUtils {
private static final String TAG = makeLogTag(AccountUtils.class);
private static final String PREF_CHOSEN_ACCOUNT = "chosen_account";
private static final String PREF_AUTH_TOKEN = "auth_token";
// The auth scope required for the app. In our case we use the "conference API"
// (not currently open source) which requires the developerssite (and readonly variant) scope.
private static final String AUTH_TOKEN_TYPE =
"oauth2:"
+ "https://www.googleapis.com/auth/developerssite "
+ "https://www.googleapis.com/auth/developerssite.readonly ";
public static boolean isAuthenticated(final Context context) {
return !TextUtils.isEmpty(getChosenAccountName(context));
}
public static String getChosenAccountName(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_CHOSEN_ACCOUNT, null);
}
private static void setChosenAccountName(final Context context, final String accountName) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_CHOSEN_ACCOUNT, accountName).commit();
}
public static String getAuthToken(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getString(PREF_AUTH_TOKEN, null);
}
private static void setAuthToken(final Context context, final String authToken) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().putString(PREF_AUTH_TOKEN, authToken).commit();
}
public static void invalidateAuthToken(final Context context) {
AccountManager am = AccountManager.get(context);
am.invalidateAuthToken(GoogleAccountManager.ACCOUNT_TYPE, getAuthToken(context));
setAuthToken(context, null);
}
public static interface AuthenticateCallback {
public boolean shouldCancelAuthentication();
public void onAuthTokenAvailable(String authToken);
}
public static void tryAuthenticate(Activity activity, AuthenticateCallback callback,
int activityRequestCode, Account account) {
//noinspection deprecation
AccountManager.get(activity).getAuthToken(
account,
AUTH_TOKEN_TYPE,
false,
getAccountManagerCallback(callback, account, activity, activity,
activityRequestCode),
null);
}
public static void tryAuthenticateWithErrorNotification(Context context,
AuthenticateCallback callback, Account account) {
//noinspection deprecation
AccountManager.get(context).getAuthToken(
account,
AUTH_TOKEN_TYPE,
true,
getAccountManagerCallback(callback, account, context, null, 0),
null);
}
private static AccountManagerCallback<Bundle> getAccountManagerCallback(
final AuthenticateCallback callback, final Account account,
final Context context, final Activity activity, final int activityRequestCode) {
return new AccountManagerCallback<Bundle>() {
public void run(AccountManagerFuture<Bundle> future) {
if (callback != null && callback.shouldCancelAuthentication()) {
return;
}
try {
Bundle bundle = future.getResult();
if (activity != null && bundle.containsKey(AccountManager.KEY_INTENT)) {
Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivityForResult(intent, activityRequestCode);
} else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
final String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
setAuthToken(context, token);
setChosenAccountName(context, account.name);
if (callback != null) {
callback.onAuthTokenAvailable(token);
}
}
} catch (Exception e) {
LOGE(TAG, "Authentication error", e);
}
}
};
}
public static void signOut(final Context context) {
// Clear out all Google I/O-created sessions from Calendar
if (UIUtils.hasICS()) {
LOGI(TAG, "Clearing all sessions from Google Calendar using SessionCalendarService.");
Toast.makeText(context, R.string.toast_deleting_sessions_from_calendar,
Toast.LENGTH_LONG).show();
context.startService(
new Intent(SessionCalendarService.ACTION_CLEAR_ALL_SESSIONS_CALENDAR)
.setClass(context, SessionCalendarService.class)
.putExtra(SessionCalendarService.EXTRA_ACCOUNT_NAME,
getChosenAccountName(context)));
}
invalidateAuthToken(context);
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
sp.edit().clear().commit();
context.getContentResolver().delete(ScheduleContract.BASE_CONTENT_URI, null, null);
GCMRegistrar.unregister(context);
}
public static void startAuthenticationFlow(final Context context, final Intent finishIntent) {
Intent loginFlowIntent = new Intent(context, AccountActivity.class);
loginFlowIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
loginFlowIntent.putExtra(AccountActivity.EXTRA_FINISH_INTENT, finishIntent);
context.startActivity(loginFlowIntent);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/AccountUtils.java
|
Java
|
asf20
| 7,748
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.provider.ScheduleContract;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Parcelable;
import android.preference.PreferenceManager;
/**
* Android Beam helper methods.
*/
public class BeamUtils {
private static final byte[] DEFAULT_BEAM_MIME =
"application/vnd.google.iosched.default".getBytes();
private static final String PREF_BEAM_STATE = "beam_state";
private static final int BEAM_STATE_UNLOCKED = 0x1481;
private static final int BEAM_STATE_LOCKED = 0x0;
/**
* Sets this activity's Android Beam message to one representing the given session.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamSessionUri(Activity activity, Uri sessionUri) {
if (UIUtils.hasICS()) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) {
// No NFC :-(
return;
}
nfcAdapter.setNdefPushMessage(new NdefMessage(
new NdefRecord[]{
new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
ScheduleContract.Sessions.CONTENT_ITEM_TYPE.getBytes(),
new byte[0],
sessionUri.toString().getBytes())
}), activity);
}
}
/**
* Sets this activity's Android Beam message to the default.
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setDefaultBeamUri(Activity activity) {
if (UIUtils.hasICS()) {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(activity);
if (nfcAdapter == null) {
// No NFC :-(
return;
}
nfcAdapter.setNdefPushMessage(new NdefMessage(
new NdefRecord[]{
new NdefRecord(NdefRecord.TNF_MIME_MEDIA,
DEFAULT_BEAM_MIME,
new byte[0],
new byte[0])
}), activity);
}
}
public static boolean isBeamUnlocked(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return (prefs.getInt(PREF_BEAM_STATE, BEAM_STATE_LOCKED) == BEAM_STATE_UNLOCKED);
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamUnlocked(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.edit().putInt(PREF_BEAM_STATE, BEAM_STATE_UNLOCKED).commit();
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static boolean wasLaunchedThroughBeamFirstTime(Context context, Intent intent) {
return intent != null
&& UIUtils.hasICS()
&& NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())
&& !isBeamUnlocked(context);
}
/**
* Checks to see if the activity's intent ({@link android.app.Activity#getIntent()}) is
* an NFC intent that the app recognizes. If it is, then parse the NFC message and set the
* activity's intent (using {@link Activity#setIntent(android.content.Intent)}) to something
* the app can recognize (i.e. a normal {@link Intent#ACTION_VIEW} intent).
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void tryUpdateIntentFromBeam(Activity activity) {
if (UIUtils.hasICS()) {
Intent originalIntent = activity.getIntent();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(originalIntent.getAction())) {
Parcelable[] rawMsgs = originalIntent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage msg = (NdefMessage) rawMsgs[0];
// Record 0 contains the MIME type, record 1 is the AAR, if present.
// In iosched, AARs are not present.
NdefRecord mimeRecord = msg.getRecords()[0];
if (ScheduleContract.Sessions.CONTENT_ITEM_TYPE.equals(
new String(mimeRecord.getType()))) {
// Re-set the activity's intent to one that represents session details.
Intent sessionDetailIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse(new String(mimeRecord.getPayload())));
activity.setIntent(sessionDetailIntent);
}
}
}
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static void setBeamCompleteCallback(Activity activity,
NfcAdapter.OnNdefPushCompleteCallback callback) {
if (UIUtils.hasICS()) {
NfcAdapter adapter = NfcAdapter.getDefaultAdapter(activity);
if (adapter == null) {
return;
}
adapter.setOnNdefPushCompleteCallback(callback, activity);
}
}
public static void launchBeamSession(Context context) {
context.startActivity(new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri("gooio2012/125/")));
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/BeamUtils.java
|
Java
|
asf20
| 6,235
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import com.google.android.apps.iosched.BuildConfig;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.os.AsyncTask;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
import java.util.Hashtable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This class wraps up completing some arbitrary long running work when loading a bitmap to an
* ImageView. It handles things like using a memory and disk cache, running the work in a background
* thread and setting a placeholder image.
*/
public abstract class ImageWorker {
private static final String TAG = makeLogTag(ImageWorker.class);
private static final int FADE_IN_TIME = 200;
protected ImageCache mImageCache;
protected ImageCache.ImageCacheParams mImageCacheParams;
protected Bitmap mLoadingBitmap;
protected boolean mFadeInBitmap = true;
private boolean mExitTasksEarly = false;
protected boolean mPauseWork = false;
private final Object mPauseWorkLock = new Object();
private final Hashtable<Integer, Bitmap> loadingBitmaps = new Hashtable<Integer, Bitmap>(2);
protected Resources mResources;
private static final int MESSAGE_CLEAR = 0;
private static final int MESSAGE_INIT_DISK_CACHE = 1;
private static final int MESSAGE_FLUSH = 2;
private static final int MESSAGE_CLOSE = 3;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
// Dual thread executor for main AsyncTask
public static final Executor DUAL_THREAD_EXECUTOR =
Executors.newFixedThreadPool(2, sThreadFactory);
protected ImageWorker(Context context) {
mResources = context.getResources();
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing
* logic). A memory and disk cache will be used if an {@link ImageCache} has
* been set using {@link ImageWorker#addImageCache}. If the
* image is found in the memory cache, it is set immediately, otherwise an
* {@link AsyncTask} will be created to asynchronously load the bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
*/
protected void loadImage(Object data, ImageView imageView) {
loadImage(data, imageView, mLoadingBitmap);
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing
* logic). A memory and disk cache will be used if an {@link ImageCache} has
* been set using {@link ImageWorker#addImageCache}. If the
* image is found in the memory cache, it is set immediately, otherwise an
* {@link AsyncTask} will be created to asynchronously load the bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
* @param resId Resource of placeholder bitmap while the image loads.
*/
protected void loadImage(Object data, ImageView imageView, int resId) {
if (!loadingBitmaps.containsKey(resId)) {
// Store loading bitmap in a hash table to prevent continual decoding
loadingBitmaps.put(resId, BitmapFactory.decodeResource(mResources, resId));
}
loadImage(data, imageView, loadingBitmaps.get(resId));
}
/**
* Load an image specified by the data parameter into an ImageView (override
* {@link ImageWorker#processBitmap(Object)} to define the processing logic). A memory and disk
* cache will be used if an {@link ImageCache} has been set using
* {@link ImageWorker#addImageCache}. If the image is found in the memory cache, it
* is set immediately, otherwise an {@link AsyncTask} will be created to asynchronously load the
* bitmap.
*
* @param data The URL of the image to download.
* @param imageView The ImageView to bind the downloaded image to.
*/
public void loadImage(Object data, ImageView imageView, Bitmap loadingBitmap) {
if (data == null) {
return;
}
Bitmap bitmap = null;
if (mImageCache != null) {
bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data));
}
if (bitmap != null) {
// Bitmap found in memory cache
imageView.setImageBitmap(bitmap);
} else if (cancelPotentialWork(data, imageView)) {
final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
final AsyncDrawable asyncDrawable =
new AsyncDrawable(mResources, loadingBitmap, task);
imageView.setImageDrawable(asyncDrawable);
if (UIUtils.hasHoneycomb()) {
// On HC+ we execute on a dual thread executor. There really isn't much extra
// benefit to having a really large pool of threads. Having more than one will
// likely benefit network bottlenecks though.
task.executeOnExecutor(DUAL_THREAD_EXECUTOR, data);
} else {
// Otherwise pre-HC the default is a thread pool executor (not ideal, serial
// execution or a smaller number of threads would be better).
task.execute(data);
}
}
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param bitmap
*/
public void setLoadingImage(Bitmap bitmap) {
mLoadingBitmap = bitmap;
}
/**
* Set placeholder bitmap that shows when the the background thread is running.
*
* @param resId
*/
public void setLoadingImage(int resId) {
mLoadingBitmap = BitmapFactory.decodeResource(mResources, resId);
}
/**
* Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI
* thread).
* @param fragmentManager The FragmentManager to initialize and add the cache
* @param cacheParams The cache parameters to use
*/
public void addImageCache(FragmentManager fragmentManager,
ImageCache.ImageCacheParams cacheParams) {
mImageCacheParams = cacheParams;
setImageCache(ImageCache.findOrCreateCache(fragmentManager, mImageCacheParams));
new CacheAsyncTask().execute(MESSAGE_INIT_DISK_CACHE);
}
/**
* Adds an {@link ImageCache} to this worker in the background (to prevent disk access on UI
* thread) using default cache parameters.
* @param fragmentActivity The FragmentActivity to initialize and add the cache
*/
public void addImageCache(FragmentActivity fragmentActivity) {
addImageCache(fragmentActivity.getSupportFragmentManager(),
new ImageCache.ImageCacheParams(fragmentActivity));
}
/**
* Sets the {@link ImageCache} object to use with this ImageWorker. Usually you will not need
* to call this directly, instead use {@link ImageWorker#addImageCache} which will create and
* add the {@link ImageCache} object in a background thread (to ensure no disk access on the
* main/UI thread).
*
* @param imageCache
*/
public void setImageCache(ImageCache imageCache) {
mImageCache = imageCache;
}
/**
* If set to true, the image will fade-in once it has been loaded by the background thread.
*/
public void setImageFadeIn(boolean fadeIn) {
mFadeInBitmap = fadeIn;
}
/**
* Setting this to true will signal the working tasks to exit processing at the next chance.
* This helps finish up pending work when the activity is no longer in the foreground and
* completing the tasks is no longer useful.
* @param exitTasksEarly
*/
public void setExitTasksEarly(boolean exitTasksEarly) {
mExitTasksEarly = exitTasksEarly;
setPauseWork(false);
}
/**
* Subclasses should override this to define any processing or work that must happen to produce
* the final bitmap. This will be executed in a background thread and be long running. For
* example, you could resize a large bitmap here, or pull down an image from the network.
*
* @param data The data to identify which image to process, as provided by
* {@link ImageWorker#loadImage(Object, ImageView)}
* @return The processed bitmap
*/
protected abstract Bitmap processBitmap(Object data);
/**
* Cancels any pending work attached to the provided ImageView.
* @param imageView
*/
public static void cancelWork(ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
bitmapWorkerTask.cancel(true);
if (BuildConfig.DEBUG) {
LOGD(TAG, "cancelWork - cancelled work for " + bitmapWorkerTask.data);
}
}
}
/**
* Returns true if the current work has been canceled or if there was no work in
* progress on this image view.
* Returns false if the work in progress deals with the same data. The work is not
* stopped in that case.
*/
public static boolean cancelPotentialWork(Object data, ImageView imageView) {
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (bitmapWorkerTask != null) {
final Object bitmapData = bitmapWorkerTask.data;
if (bitmapData == null || !bitmapData.equals(data)) {
bitmapWorkerTask.cancel(true);
LOGD(TAG, "cancelPotentialWork - cancelled work for " + data);
} else {
// The same work is already in progress.
return false;
}
}
return true;
}
/**
* @param imageView Any imageView
* @return Retrieve the currently active work task (if any) associated with this imageView.
* null if there is no such task.
*/
private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
/**
* The actual AsyncTask that will asynchronously process the image.
*/
private class BitmapWorkerTask extends AsyncTask<Object, Void, Bitmap> {
private Object data;
private final WeakReference<ImageView> imageViewReference;
public BitmapWorkerTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
/**
* Background processing.
*/
@Override
protected Bitmap doInBackground(Object... params) {
LOGD(TAG, "doInBackground - starting work");
data = params[0];
final String dataString = String.valueOf(data);
Bitmap bitmap = null;
// Wait here if work is paused and the task is not cancelled
synchronized (mPauseWorkLock) {
while (mPauseWork && !isCancelled()) {
try {
mPauseWorkLock.wait();
} catch (InterruptedException e) {}
}
}
// If the image cache is available and this task has not been cancelled by another
// thread and the ImageView that was originally bound to this task is still bound back
// to this task and our "exit early" flag is not set then try and fetch the bitmap from
// the cache
if (mImageCache != null && !isCancelled() && getAttachedImageView() != null
&& !mExitTasksEarly) {
bitmap = mImageCache.getBitmapFromDiskCache(dataString);
}
// If the bitmap was not found in the cache and this task has not been cancelled by
// another thread and the ImageView that was originally bound to this task is still
// bound back to this task and our "exit early" flag is not set, then call the main
// process method (as implemented by a subclass)
if (bitmap == null && !isCancelled() && getAttachedImageView() != null
&& !mExitTasksEarly) {
bitmap = processBitmap(params[0]);
}
// If the bitmap was processed and the image cache is available, then add the processed
// bitmap to the cache for future use. Note we don't check if the task was cancelled
// here, if it was, and the thread is still running, we may as well add the processed
// bitmap to our cache as it might be used again in the future
if (bitmap != null && mImageCache != null) {
mImageCache.addBitmapToCache(dataString, bitmap);
}
LOGD(TAG, "doInBackground - finished work");
return bitmap;
}
/**
* Once the image is processed, associates it to the imageView
*/
@Override
protected void onPostExecute(Bitmap bitmap) {
// if cancel was called on this task or the "exit early" flag is set then we're done
if (isCancelled() || mExitTasksEarly) {
bitmap = null;
}
final ImageView imageView = getAttachedImageView();
if (bitmap != null && imageView != null) {
LOGD(TAG, "onPostExecute - setting bitmap");
setImageBitmap(imageView, bitmap);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
synchronized (mPauseWorkLock) {
mPauseWorkLock.notifyAll();
}
}
/**
* Returns the ImageView associated with this task as long as the ImageView's task still
* points to this task as well. Returns null otherwise.
*/
private ImageView getAttachedImageView() {
final ImageView imageView = imageViewReference.get();
final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask) {
return imageView;
}
return null;
}
}
/**
* A custom Drawable that will be attached to the imageView while the work is in progress.
* Contains a reference to the actual worker task, so that it can be stopped if a new binding is
* required, and makes sure that only the last started worker process can bind its result,
* independently of the finish order.
*/
private static class AsyncDrawable extends BitmapDrawable {
private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference<BitmapWorkerTask>(bitmapWorkerTask);
}
public BitmapWorkerTask getBitmapWorkerTask() {
return bitmapWorkerTaskReference.get();
}
}
/**
* Called when the processing is complete and the final bitmap should be set on the ImageView.
*
* @param imageView
* @param bitmap
*/
private void setImageBitmap(ImageView imageView, Bitmap bitmap) {
if (mFadeInBitmap) {
// Use TransitionDrawable to fade in
final TransitionDrawable td =
new TransitionDrawable(new Drawable[] {
new ColorDrawable(android.R.color.transparent),
new BitmapDrawable(mResources, bitmap)
});
//noinspection deprecation
imageView.setBackgroundDrawable(imageView.getDrawable());
imageView.setImageDrawable(td);
td.startTransition(FADE_IN_TIME);
} else {
imageView.setImageBitmap(bitmap);
}
}
/**
* Pause any ongoing background work. This can be used as a temporary
* measure to improve performance. For example background work could
* be paused when a ListView or GridView is being scrolled using a
* {@link android.widget.AbsListView.OnScrollListener} to keep
* scrolling smooth.
* <p>
* If work is paused, be sure setPauseWork(false) is called again
* before your fragment or activity is destroyed (for example during
* {@link android.app.Activity#onPause()}), or there is a risk the
* background thread will never finish.
*/
public void setPauseWork(boolean pauseWork) {
synchronized (mPauseWorkLock) {
mPauseWork = pauseWork;
if (!mPauseWork) {
mPauseWorkLock.notifyAll();
}
}
}
protected class CacheAsyncTask extends AsyncTask<Object, Void, Void> {
@Override
protected Void doInBackground(Object... params) {
switch ((Integer)params[0]) {
case MESSAGE_CLEAR:
clearCacheInternal();
break;
case MESSAGE_INIT_DISK_CACHE:
initDiskCacheInternal();
break;
case MESSAGE_FLUSH:
flushCacheInternal();
break;
case MESSAGE_CLOSE:
closeCacheInternal();
break;
}
return null;
}
}
protected void initDiskCacheInternal() {
if (mImageCache != null) {
mImageCache.initDiskCache();
}
}
protected void clearCacheInternal() {
if (mImageCache != null) {
mImageCache.clearCache();
}
}
protected void flushCacheInternal() {
if (mImageCache != null) {
mImageCache.flush();
}
}
protected void closeCacheInternal() {
if (mImageCache != null) {
mImageCache.close();
mImageCache = null;
}
}
public void clearCache() {
new CacheAsyncTask().execute(MESSAGE_CLEAR);
}
public void flushCache() {
new CacheAsyncTask().execute(MESSAGE_FLUSH);
}
public void closeCache() {
new CacheAsyncTask().execute(MESSAGE_CLOSE);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/ImageWorker.java
|
Java
|
asf20
| 20,168
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import java.lang.reflect.InvocationTargetException;
/**
* A set of helper methods for best-effort method calls via reflection.
*/
public class ReflectionUtils {
public static Object tryInvoke(Object target, String methodName, Object... args) {
Class<?>[] argTypes = new Class<?>[args.length];
for (int i = 0; i < args.length; i++) {
argTypes[i] = args[i].getClass();
}
return tryInvoke(target, methodName, argTypes, args);
}
public static Object tryInvoke(Object target, String methodName, Class<?>[] argTypes,
Object... args) {
try {
return target.getClass().getMethod(methodName, argTypes).invoke(target, args);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return null;
}
public static <E> E callWithDefault(Object target, String methodName, E defaultValue) {
try {
//noinspection unchecked
return (E) target.getClass().getMethod(methodName, (Class[]) null).invoke(target);
} catch (NoSuchMethodException ignored) {
} catch (IllegalAccessException ignored) {
} catch (InvocationTargetException ignored) {
}
return defaultValue;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/ReflectionUtils.java
|
Java
|
asf20
| 1,986
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.content.ContentProvider;
import android.net.Uri;
import android.text.format.Time;
import java.util.regex.Pattern;
/**
* Various utility methods used by {@link com.google.android.apps.iosched.io.JSONHandler}.
*/
public class ParserUtils {
public static final String BLOCK_TYPE_SESSION = "session";
public static final String BLOCK_TYPE_CODE_LAB = "codelab";
public static final String BLOCK_TYPE_KEYNOTE = "keynote";
/** Used to sanitize a string to be {@link Uri} safe. */
private static final Pattern sSanitizePattern = Pattern.compile("[^a-z0-9-_]");
private static final Time sTime = new Time();
/**
* Sanitize the given string to be {@link Uri} safe for building
* {@link ContentProvider} paths.
*/
public static String sanitizeId(String input) {
if (input == null) {
return null;
}
return sSanitizePattern.matcher(input.toLowerCase()).replaceAll("");
}
/**
* Parse the given string as a RFC 3339 timestamp, returning the value as
* milliseconds since the epoch.
*/
public static long parseTime(String time) {
sTime.parse3339(time);
return sTime.toMillis(false);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/ParserUtils.java
|
Java
|
asf20
| 1,868
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This class holds our bitmap caches (memory and disk).
*/
public class ImageCache {
private static final String TAG = makeLogTag(ImageCache.class);
// Default memory cache size as a percent of device memory class
private static final float DEFAULT_MEM_CACHE_PERCENT = 0.15f;
// Default disk cache size
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
// Default disk cache directory name
private static final String DEFAULT_DISK_CACHE_DIR = "images";
// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 75;
private static final int DISK_CACHE_INDEX = 0;
// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_CLEAR_DISK_CACHE_ON_START = false;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;
private DiskLruCache mDiskLruCache;
private LruCache<String, Bitmap> mMemoryCache;
private ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
/**
* Creating a new ImageCache object using the specified parameters.
*
* @param cacheParams The cache parameters to use to initialize the cache
*/
public ImageCache(ImageCacheParams cacheParams) {
init(cacheParams);
}
/**
* Creating a new ImageCache object using the default parameters.
*
* @param context The context to use
*/
public ImageCache(Context context) {
init(new ImageCacheParams(context));
}
/**
* Find and return an existing ImageCache stored in a {@link RetainFragment}, if not found a new
* one is created using the supplied params and saved to a {@link RetainFragment}.
*
* @param fragmentManager The fragment manager to use when dealing with the retained fragment.
* @param cacheParams The cache parameters to use if creating the ImageCache
* @return An existing retained ImageCache object or a new one if one did not exist
*/
public static ImageCache findOrCreateCache(
FragmentManager fragmentManager, ImageCacheParams cacheParams) {
// Search for, or create an instance of the non-UI RetainFragment
final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);
// See if we already have an ImageCache stored in RetainFragment
ImageCache imageCache = (ImageCache) mRetainFragment.getObject();
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(cacheParams);
mRetainFragment.setObject(imageCache);
}
return imageCache;
}
/**
* Initialize the cache, providing all parameters.
*
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
// Set up memory cache
if (mCacheParams.memoryCacheEnabled) {
LOGD(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
mMemoryCache = new LruCache<String, Bitmap>(mCacheParams.memCacheSize) {
/**
* Measure item size in kilobytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, Bitmap bitmap) {
final int bitmapSize = getBitmapSize(bitmap) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
};
}
// By default the disk cache is not initialized here as it should be initialized
// on a separate thread due to disk access.
if (cacheParams.initDiskCacheOnCreate) {
// Set up disk cache
initDiskCache();
}
}
/**
* Initializes the disk cache. Note that this includes disk access so this should not be
* executed on the main/UI thread. By default an ImageCache does not initialize the disk
* cache when it is created, instead you should call initDiskCache() to initialize it on a
* background thread.
*/
public void initDiskCache() {
// Set up disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
File diskCacheDir = mCacheParams.diskCacheDir;
if (mCacheParams.diskCacheEnabled && diskCacheDir != null) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdirs();
}
if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) {
try {
mDiskLruCache = DiskLruCache.open(
diskCacheDir, 1, 1, mCacheParams.diskCacheSize);
LOGD(TAG, "Disk cache initialized");
} catch (final IOException e) {
mCacheParams.diskCacheDir = null;
LOGE(TAG, "initDiskCache - " + e);
}
}
}
}
mDiskCacheStarting = false;
mDiskCacheLock.notifyAll();
}
}
/**
* Adds a bitmap to both memory and disk cache.
* @param data Unique identifier for the bitmap to store
* @param bitmap The bitmap to store
*/
public void addBitmapToCache(String data, Bitmap bitmap) {
if (data == null || bitmap == null) {
return;
}
// Add to memory cache
if (mMemoryCache != null && mMemoryCache.get(data) == null) {
mMemoryCache.put(data, bitmap);
}
synchronized (mDiskCacheLock) {
// Add to disk cache
if (mDiskLruCache != null) {
final String key = hashKeyForDisk(data);
OutputStream out = null;
try {
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot == null) {
final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
out = editor.newOutputStream(DISK_CACHE_INDEX);
bitmap.compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
out.close();
}
} else {
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
} catch (final IOException e) {
LOGE(TAG, "addBitmapToCache - " + e);
} catch (Exception e) {
LOGE(TAG, "addBitmapToCache - " + e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {}
}
}
}
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromMemCache(String data) {
if (mMemoryCache != null) {
final Bitmap memBitmap = mMemoryCache.get(data);
if (memBitmap != null) {
LOGD(TAG, "Memory cache hit");
return memBitmap;
}
}
return null;
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
final String key = hashKeyForDisk(data);
synchronized (mDiskCacheLock) {
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {}
}
if (mDiskLruCache != null) {
InputStream inputStream = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot != null) {
LOGD(TAG, "Disk cache hit");
inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
if (inputStream != null) {
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
}
} catch (final IOException e) {
LOGE(TAG, "getBitmapFromDiskCache - " + e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {}
}
}
return null;
}
}
/**
* Clears both the memory and disk cache associated with this ImageCache object. Note that
* this includes disk access so this should not be executed on the main/UI thread.
*/
public void clearCache() {
if (mMemoryCache != null) {
mMemoryCache.evictAll();
LOGD(TAG, "Memory cache cleared");
}
synchronized (mDiskCacheLock) {
mDiskCacheStarting = true;
if (mDiskLruCache != null && !mDiskLruCache.isClosed()) {
try {
mDiskLruCache.delete();
LOGD(TAG, "Disk cache cleared");
} catch (IOException e) {
LOGE(TAG, "clearCache - " + e);
}
mDiskLruCache = null;
initDiskCache();
}
}
}
/**
* Flushes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void flush() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
mDiskLruCache.flush();
LOGD(TAG, "Disk cache flushed");
} catch (IOException e) {
LOGE(TAG, "flush - " + e);
}
}
}
}
/**
* Closes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void close() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
if (!mDiskLruCache.isClosed()) {
mDiskLruCache.close();
mDiskLruCache = null;
LOGD(TAG, "Disk cache closed");
}
} catch (IOException e) {
LOGE(TAG, "close - " + e);
}
}
}
}
/**
* A holder class that contains cache parameters.
*/
public static class ImageCacheParams {
public int memCacheSize;
public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
public File diskCacheDir;
public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
public int compressQuality = DEFAULT_COMPRESS_QUALITY;
public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
public boolean clearDiskCacheOnStart = DEFAULT_CLEAR_DISK_CACHE_ON_START;
public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;
public ImageCacheParams(Context context) {
init(getDiskCacheDir(context, DEFAULT_DISK_CACHE_DIR));
}
public ImageCacheParams(Context context, String uniqueName) {
init(getDiskCacheDir(context, uniqueName));
}
public ImageCacheParams(File diskCacheDir) {
init(diskCacheDir);
}
private void init(File diskCacheDir) {
setMemCacheSizePercent(DEFAULT_MEM_CACHE_PERCENT);
this.diskCacheDir = diskCacheDir;
}
/**
* Sets the memory cache size based on a percentage of the max available VM memory.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the avilable
* memory. Throws {@link IllegalArgumentException} if percent is < 0.05 or > .8.
* memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
* to construct a LruCache which takes an int in its constructor.
*
* This value should be chosen carefully based on a number of factors
* Refer to the corresponding Android Training class for more discussion:
* http://developer.android.com/training/displaying-bitmaps/
*
* @param percent Percent of memory class to use to size memory cache
*/
public void setMemCacheSizePercent(float percent) {
if (percent < 0.05f || percent > 0.8f) {
throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
+ "between 0.05 and 0.8 (inclusive)");
}
memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
}
private static int getMemoryClass(Context context) {
return ((ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE)).getMemoryClass();
}
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context The context to use
* @param uniqueName A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable for using as a
* disk filename.
*/
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* Get the size in bytes of a bitmap.
* @param bitmap
* @return size in bytes
*/
@TargetApi(12)
public static int getBitmapSize(Bitmap bitmap) {
if (UIUtils.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/**
* Check if external storage is built-in or removable.
*
* @return True if external storage is removable (like an SD card), false
* otherwise.
*/
@TargetApi(9)
public static boolean isExternalStorageRemovable() {
if (UIUtils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
@TargetApi(8)
public static File getExternalCacheDir(Context context) {
if (UIUtils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
/**
* Check how much usable space is available at a given path.
*
* @param path The path to check
* @return The space available in bytes
*/
@TargetApi(9)
public static long getUsableSpace(File path) {
if (UIUtils.hasGingerbread()) {
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
/**
* Locate an existing instance of this Fragment or if not found, create and
* add it using FragmentManager.
*
* @param fm The FragmentManager manager to use.
* @return The existing instance of the Fragment or the new instance if just
* created.
*/
public static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
// Check to see if we have retained the worker fragment.
RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG);
// If not retained (or first time running), we need to create and add it.
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment();
fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss();
}
return mRetainFragment;
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over configuration
* changes. It will be used to retain the ImageCache object.
*/
public static class RetainFragment extends Fragment {
private Object mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* @param object The object to store
*/
public void setObject(Object object) {
mObject = object;
}
/**
* Get the stored object.
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/ImageCache.java
|
Java
|
asf20
| 21,190
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.ListView;
/**
* An implementation of {@link ActionMode} that proxies to the native
* {@link android.view.ActionMode} implementation (shows the contextual action bar).
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
class ActionModeHoneycomb extends ActionMode {
android.view.ActionMode mNativeActionMode;
ActionModeHoneycomb() {
}
static ActionModeHoneycomb startInternal(final FragmentActivity activity,
final Callback callback) {
final ActionModeHoneycomb actionMode = new ActionModeHoneycomb();
activity.startActionMode(new android.view.ActionMode.Callback() {
@Override
public boolean onCreateActionMode(android.view.ActionMode nativeActionMode, Menu menu) {
actionMode.mNativeActionMode = nativeActionMode;
return callback.onCreateActionMode(actionMode, menu);
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode nativeActionMode,
Menu menu) {
return callback.onPrepareActionMode(actionMode, menu);
}
@Override
public boolean onActionItemClicked(android.view.ActionMode nativeActionMode,
MenuItem menuItem) {
return callback.onActionItemClicked(actionMode, menuItem);
}
@Override
public void onDestroyActionMode(android.view.ActionMode nativeActionMode) {
callback.onDestroyActionMode(actionMode);
}
});
return actionMode;
}
/**{@inheritDoc}*/
@Override
public void setTitle(CharSequence title) {
mNativeActionMode.setTitle(title);
}
/**{@inheritDoc}*/
@Override
public void setTitle(int resId) {
mNativeActionMode.setTitle(resId);
}
/**{@inheritDoc}*/
@Override
public void invalidate() {
mNativeActionMode.invalidate();
}
/**{@inheritDoc}*/
@Override
public void finish() {
mNativeActionMode.finish();
}
/**{@inheritDoc}*/
@Override
public CharSequence getTitle() {
return mNativeActionMode.getTitle();
}
/**{@inheritDoc}*/
@Override
public MenuInflater getMenuInflater() {
return mNativeActionMode.getMenuInflater();
}
public static void beginMultiChoiceMode(ListView listView, FragmentActivity activity,
final MultiChoiceModeListener listener) {
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
ActionModeHoneycomb mWrappedActionMode;
@Override
public void onItemCheckedStateChanged(android.view.ActionMode actionMode, int position,
long id, boolean checked) {
listener.onItemCheckedStateChanged(mWrappedActionMode, position, id, checked);
}
@Override
public boolean onCreateActionMode(android.view.ActionMode actionMode, Menu menu) {
if (mWrappedActionMode == null) {
mWrappedActionMode = new ActionModeHoneycomb();
mWrappedActionMode.mNativeActionMode = actionMode;
}
return listener.onCreateActionMode(mWrappedActionMode, menu);
}
@Override
public boolean onPrepareActionMode(android.view.ActionMode actionMode, Menu menu) {
if (mWrappedActionMode == null) {
mWrappedActionMode = new ActionModeHoneycomb();
mWrappedActionMode.mNativeActionMode = actionMode;
}
return listener.onPrepareActionMode(mWrappedActionMode, menu);
}
@Override
public boolean onActionItemClicked(android.view.ActionMode actionMode,
MenuItem menuItem) {
return listener.onActionItemClicked(mWrappedActionMode, menuItem);
}
@Override
public void onDestroyActionMode(android.view.ActionMode actionMode) {
listener.onDestroyActionMode(mWrappedActionMode);
}
});
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionModeHoneycomb.java
|
Java
|
asf20
| 5,167
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import java.util.ArrayList;
/**
* A <em>really</em> dumb implementation of the {@link android.view.Menu} interface, that's only
* useful for our actionbar-compat purposes. See
* <code>com.android.internal.view.menu.MenuBuilder</code> in AOSP for a more complete
* implementation.
*/
public class SimpleMenu implements Menu {
private Context mContext;
private Resources mResources;
private ArrayList<SimpleMenuItem> mItems;
public SimpleMenu(Context context) {
mContext = context;
mResources = context.getResources();
mItems = new ArrayList<SimpleMenuItem>();
}
public Context getContext() {
return mContext;
}
public Resources getResources() {
return mResources;
}
public MenuItem add(CharSequence title) {
return addInternal(0, 0, title);
}
public MenuItem add(int titleRes) {
return addInternal(0, 0, mResources.getString(titleRes));
}
public MenuItem add(int groupId, int itemId, int order, CharSequence title) {
return addInternal(itemId, order, title);
}
public MenuItem add(int groupId, int itemId, int order, int titleRes) {
return addInternal(itemId, order, mResources.getString(titleRes));
}
/**
* Adds an item to the menu. The other add methods funnel to this.
*/
private MenuItem addInternal(int itemId, int order, CharSequence title) {
final SimpleMenuItem item = new SimpleMenuItem(this, itemId, order, title);
mItems.add(findInsertIndex(mItems, order), item);
return item;
}
private static int findInsertIndex(ArrayList<? extends MenuItem> items, int order) {
for (int i = items.size() - 1; i >= 0; i--) {
MenuItem item = items.get(i);
if (item.getOrder() <= order) {
return i + 1;
}
}
return 0;
}
public int findItemIndex(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
SimpleMenuItem item = mItems.get(i);
if (item.getItemId() == id) {
return i;
}
}
return -1;
}
public void removeItem(int itemId) {
removeItemAtInt(findItemIndex(itemId));
}
private void removeItemAtInt(int index) {
if ((index < 0) || (index >= mItems.size())) {
return;
}
mItems.remove(index);
}
public void clear() {
mItems.clear();
}
public MenuItem findItem(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
SimpleMenuItem item = mItems.get(i);
if (item.getItemId() == id) {
return item;
}
}
return null;
}
public int size() {
return mItems.size();
}
public MenuItem getItem(int index) {
return mItems.get(index);
}
// Unsupported operations.
public SubMenu addSubMenu(CharSequence charSequence) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int titleRes) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int groupId, int itemId, int order, CharSequence title) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public int addIntentOptions(int i, int i1, int i2, ComponentName componentName,
Intent[] intents, Intent intent, int i3, MenuItem[] menuItems) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void removeGroup(int i) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupCheckable(int i, boolean b, boolean b1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupVisible(int i, boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setGroupEnabled(int i, boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean hasVisibleItems() {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void close() {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean performShortcut(int i, KeyEvent keyEvent, int i1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean isShortcutKey(int i, KeyEvent keyEvent) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public boolean performIdentifierAction(int i, int i1) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
public void setQwertyMode(boolean b) {
throw new UnsupportedOperationException("This operation is not supported for SimpleMenu");
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/SimpleMenu.java
|
Java
|
asf20
| 6,416
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* A pre-Honeycomb, simple implementation of {@link ActionMode} that simply shows a context menu
* for the action mode.
*/
class ActionModeBase extends ActionMode implements DialogInterface.OnClickListener {
private FragmentActivity mActivity;
private Callback mCallback;
private MenuInflater mMenuInflater;
private ContextMenuDialog mDialog;
private CharSequence mTitle;
private SimpleMenu mMenu;
private ArrayAdapter<MenuItem> mMenuItemArrayAdapter;
ActionModeBase(FragmentActivity activity, Callback callback) {
mActivity = activity;
mCallback = callback;
}
static ActionModeBase startInternal(final FragmentActivity activity,
Callback callback) {
final ActionModeBase actionMode = new ActionModeBase(activity, callback);
actionMode.startInternal();
return actionMode;
}
void startInternal() {
mMenu = new SimpleMenu(mActivity);
mCallback.onCreateActionMode(this, mMenu);
mCallback.onPrepareActionMode(this, mMenu);
mMenuItemArrayAdapter = new ArrayAdapter<MenuItem>(mActivity,
android.R.layout.simple_list_item_1,
android.R.id.text1);
invalidate();
// DialogFragment.show() will take care of adding the fragment
// in a transaction. We also want to remove any currently showing
// dialog, so make our own transaction and take care of that here.
FragmentManager fm = mActivity.getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag("action_mode_context_menu");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
mDialog = new ContextMenuDialog();
mDialog.mActionModeBase = this;
mDialog.show(ft, "action_mode_context_menu");
}
/**{@inheritDoc}*/
@Override
public void setTitle(CharSequence title) {
mTitle = title;
}
/**{@inheritDoc}*/
@Override
public void setTitle(int resId) {
mTitle = mActivity.getResources().getString(resId);
}
/**{@inheritDoc}*/
@Override
public void invalidate() {
mMenuItemArrayAdapter.clear();
List<MenuItem> items = new ArrayList<MenuItem>();
for (int i = 0; i < mMenu.size(); i++) {
MenuItem item = mMenu.getItem(i);
if (item.isVisible()) {
items.add(item);
}
}
Collections.sort(items, new Comparator<MenuItem>() {
@Override
public int compare(MenuItem a, MenuItem b) {
return a.getOrder() - b.getOrder();
}
});
for (MenuItem item : items) {
mMenuItemArrayAdapter.add(item);
}
}
/**{@inheritDoc}*/
@Override
public void finish() {
if (mDialog != null) {
mDialog.dismiss();
}
mCallback.onDestroyActionMode(this);
mDialog = null;
mMenu = null;
mMenuItemArrayAdapter = null;
mTitle = null;
}
/**{@inheritDoc}*/
@Override
public CharSequence getTitle() {
return mTitle;
}
/**{@inheritDoc}*/
@Override
public MenuInflater getMenuInflater() {
if (mMenuInflater == null) {
mMenuInflater = mActivity.getMenuInflater();
}
return mMenuInflater;
}
public static void beginMultiChoiceMode(ListView listView, final FragmentActivity activity,
final MultiChoiceModeListener listener) {
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int position, long id) {
ActionMode mode = ActionModeBase.start(activity, listener);
listener.onItemCheckedStateChanged(mode, position, id, true);
return true;
}
});
}
@Override
public void onClick(DialogInterface dialogInterface, int position) {
mCallback.onActionItemClicked(this, mMenuItemArrayAdapter.getItem(position));
}
public static class ContextMenuDialog extends DialogFragment {
ActionModeBase mActionModeBase;
public ContextMenuDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
if (mActionModeBase == null) {
// TODO: support orientation changes and avoid this awful hack.
final Dialog d = new AlertDialog.Builder(getActivity()).create();
new Handler().post(new Runnable() {
@Override
public void run() {
d.dismiss();
}
});
return d;
}
return new AlertDialog.Builder(getActivity())
.setTitle(mActionModeBase.mTitle)
.setAdapter(mActionModeBase.mMenuItemArrayAdapter, mActionModeBase)
.create();
}
@Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (mActionModeBase == null) {
return;
}
mActionModeBase.mDialog = null;
mActionModeBase.finish();
}
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionModeBase.java
|
Java
|
asf20
| 6,806
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
/**
* A MultiChoiceModeListener receives events for {@link AbsListView#CHOICE_MODE_MULTIPLE_MODAL}.
* It acts as the {@link ActionMode.Callback} for the selection mode and also receives {@link
* #onItemCheckedStateChanged(ActionMode, int, long, boolean)} events when the user selects and
* deselects list items.
*/
public interface MultiChoiceModeListener extends ActionMode.Callback {
/**
* Called when an item is checked or unchecked during selection mode.
*
* @param mode The {@link ActionMode} providing the selection mode
* @param position Adapter position of the item that was checked or unchecked
* @param id Adapter ID of the item that was checked or unchecked
* @param checked <code>true</code> if the item is now checked, <code>false</code> if the
* item is now unchecked.
*/
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked);
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/MultiChoiceModeListener.java
|
Java
|
asf20
| 1,638
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.view.ActionProvider;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
/**
* A <em>really</em> dumb implementation of the {@link android.view.MenuItem} interface, that's only
* useful for our actionbar-compat purposes. See
* <code>com.android.internal.view.menu.MenuItemImpl</code> in AOSP for a more complete
* implementation.
*/
public class SimpleMenuItem implements MenuItem {
private SimpleMenu mMenu;
private final int mId;
private final int mOrder;
private CharSequence mTitle;
private CharSequence mTitleCondensed;
private Drawable mIconDrawable;
private int mIconResId = 0;
private boolean mEnabled = true;
public SimpleMenuItem(SimpleMenu menu, int id, int order, CharSequence title) {
mMenu = menu;
mId = id;
mOrder = order;
mTitle = title;
}
public int getItemId() {
return mId;
}
public int getOrder() {
return mOrder;
}
public MenuItem setTitle(CharSequence title) {
mTitle = title;
return this;
}
public MenuItem setTitle(int titleRes) {
return setTitle(mMenu.getContext().getString(titleRes));
}
public CharSequence getTitle() {
return mTitle;
}
public MenuItem setTitleCondensed(CharSequence title) {
mTitleCondensed = title;
return this;
}
public CharSequence getTitleCondensed() {
return mTitleCondensed != null ? mTitleCondensed : mTitle;
}
public MenuItem setIcon(Drawable icon) {
mIconResId = 0;
mIconDrawable = icon;
return this;
}
public MenuItem setIcon(int iconResId) {
mIconDrawable = null;
mIconResId = iconResId;
return this;
}
public Drawable getIcon() {
if (mIconDrawable != null) {
return mIconDrawable;
}
if (mIconResId != 0) {
return mMenu.getResources().getDrawable(mIconResId);
}
return null;
}
public MenuItem setEnabled(boolean enabled) {
mEnabled = enabled;
return this;
}
public boolean isEnabled() {
return mEnabled;
}
// No-op operations. We use no-ops to allow inflation from menu XML.
public int getGroupId() {
// Noop
return 0;
}
public View getActionView() {
// Noop
return null;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public MenuItem setActionProvider(ActionProvider actionProvider) {
// Noop
return this;
}
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public ActionProvider getActionProvider() {
// Noop
return null;
}
public boolean expandActionView() {
// Noop
return false;
}
public boolean collapseActionView() {
// Noop
return false;
}
public boolean isActionViewExpanded() {
// Noop
return false;
}
@Override
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public MenuItem setOnActionExpandListener(OnActionExpandListener onActionExpandListener) {
// Noop
return this;
}
public MenuItem setIntent(Intent intent) {
// Noop
return this;
}
public Intent getIntent() {
// Noop
return null;
}
public MenuItem setShortcut(char c, char c1) {
// Noop
return this;
}
public MenuItem setNumericShortcut(char c) {
// Noop
return this;
}
public char getNumericShortcut() {
// Noop
return 0;
}
public MenuItem setAlphabeticShortcut(char c) {
// Noop
return this;
}
public char getAlphabeticShortcut() {
// Noop
return 0;
}
public MenuItem setCheckable(boolean b) {
// Noop
return this;
}
public boolean isCheckable() {
// Noop
return false;
}
public MenuItem setChecked(boolean b) {
// Noop
return this;
}
public boolean isChecked() {
// Noop
return false;
}
public MenuItem setVisible(boolean b) {
// Noop
return this;
}
public boolean isVisible() {
// Noop
return true;
}
public boolean hasSubMenu() {
// Noop
return false;
}
public SubMenu getSubMenu() {
// Noop
return null;
}
public MenuItem setOnMenuItemClickListener(OnMenuItemClickListener onMenuItemClickListener) {
// Noop
return this;
}
public ContextMenu.ContextMenuInfo getMenuInfo() {
// Noop
return null;
}
public void setShowAsAction(int i) {
// Noop
}
public MenuItem setShowAsActionFlags(int i) {
// Noop
return null;
}
public MenuItem setActionView(View view) {
// Noop
return this;
}
public MenuItem setActionView(int i) {
// Noop
return this;
}
@Override
public String toString() {
return mTitle == null ? "" : mTitle.toString();
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/SimpleMenuItem.java
|
Java
|
asf20
| 6,007
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.util.actionmodecompat;
import com.google.android.apps.iosched.util.UIUtils;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
/**
* A compatibility shim for {@link android.view.ActionMode} that shows context menus
* on pre-Honeycomb devices.
*/
public abstract class ActionMode {
private Object mTag;
public static ActionMode start(FragmentActivity activity, Callback callback) {
if (UIUtils.hasHoneycomb()) {
return ActionModeHoneycomb.startInternal(activity, callback);
} else {
return ActionModeBase.startInternal(activity, callback);
}
}
public static void setMultiChoiceMode(ListView listView, FragmentActivity activity,
MultiChoiceModeListener listener) {
if (UIUtils.hasHoneycomb()) {
ActionModeHoneycomb.beginMultiChoiceMode(listView, activity, listener);
} else {
ActionModeBase.beginMultiChoiceMode(listView, activity, listener);
}
}
/**
* Set a tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @param tag Tag to associate with this ActionMode
*
* @see #getTag()
*/
public void setTag(Object tag) {
mTag = tag;
}
/**
* Retrieve the tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @return Tag associated with this ActionMode
*
* @see #setTag(Object)
*/
public Object getTag() {
return mTag;
}
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param title Title string to set
*
* @see #setTitle(int)
* @see #setCustomView(View)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the title
*
* @see #setTitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setTitle(int resId);
/**
* Invalidate the action mode and refresh menu content. The mode's
* {@link ActionMode.Callback} will have its
* {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called.
* If it returns true the menu will be scanned for updated content and any relevant changes
* will be reflected to the user.
*/
public abstract void invalidate();
/**
* Finish and close this action mode. The action mode's {@link ActionMode.Callback} will
* have its {@link Callback#onDestroyActionMode(ActionMode)} method called.
*/
public abstract void finish();
/**
* Returns the current title of this action mode.
* @return Title text
*/
public abstract CharSequence getTitle();
/**
* Returns a {@link MenuInflater} with the ActionMode's context.
*/
public abstract MenuInflater getMenuInflater();
/**
* Returns whether the UI presenting this action mode can take focus or not.
* This is used by internal components within the framework that would otherwise
* present an action mode UI that requires focus, such as an EditText as a custom view.
*
* @return true if the UI used to show this action mode can take focus
* @hide Internal use only
*/
public boolean isUiFocusable() {
return true;
}
/**
* Callback interface for action modes. Supplied to
* {@link View#startActionMode(Callback)}, a Callback
* configures and handles events raised by a user's interaction with an action mode.
*
* <p>An action mode's lifecycle is as follows:
* <ul>
* <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial
* creation</li>
* <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation
* and any time the {@link ActionMode} is invalidated</li>
* <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a
* contextual action button is clicked</li>
* <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode
* is closed</li>
* </ul>
*/
public interface Callback {
/**
* Called when action mode is first created. The menu supplied will be used to
* generate action buttons for the action mode.
*
* @param mode ActionMode being created
* @param menu Menu used to populate action buttons
* @return true if the action mode should be created, false if entering this
* mode should be aborted.
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu);
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
public boolean onPrepareActionMode(ActionMode mode, Menu menu);
/**
* Called to report a user click on an action button.
*
* @param mode The current ActionMode
* @param item The item that was clicked
* @return true if this callback handled the event, false if the standard MenuItem
* invocation should continue.
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item);
/**
* Called when an action mode is about to be exited and destroyed.
*
* @param mode The current ActionMode being destroyed
*/
public void onDestroyActionMode(ActionMode mode);
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/util/actionmodecompat/ActionMode.java
|
Java
|
asf20
| 6,836
|
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.appwidget;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter;
import com.google.android.apps.iosched.ui.widget.SimpleSectionedListAdapter.Section;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.ParserUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.ArrayList;
import java.util.List;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This is the service that provides the factory to be bound to the collection service.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MyScheduleWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetRemoveViewsFactory(this.getApplicationContext());
}
/**
* This is the factory that will provide data to the collection widget.
*/
private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class);
private Context mContext;
private Cursor mCursor;
private SparseIntArray mPMap;
private List<SimpleSectionedListAdapter.Section> mSections;
private SparseBooleanArray mHeaderPositionMap;
public WidgetRemoveViewsFactory(Context context) {
mContext = context;
}
public void onCreate() {
// Since we reload the cursor in onDataSetChanged() which gets called immediately after
// onCreate(), we do nothing here.
}
public void onDestroy() {
if (mCursor != null) {
mCursor.close();
}
}
public int getCount() {
if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) {
return 0;
}
int size = mCursor.getCount() + mSections.size();
if (size < 10) {
init();
size = mCursor.getCount() + mSections.size();
}
LOGV(TAG, "size returned:" + size);
return size;
}
public RemoteViews getViewAt(int position) {
RemoteViews rv;
boolean isSectionHeader = mHeaderPositionMap.get(position);
int offset = mPMap.get(position);
if (isSectionHeader) {
rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header);
Section section = mSections.get(offset - 1);
rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle());
} else {
int cursorPosition = position - offset;
mCursor.moveToPosition(cursorPosition);
rv = new RemoteViews(mContext.getPackageName(),
R.layout.list_item_schedule_block_widget);
final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID);
final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE);
final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META);
final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START);
final Resources res = mContext.getResources();
if (ParserUtils.BLOCK_TYPE_SESSION.equals(type)
|| ParserUtils.BLOCK_TYPE_CODE_LAB.equals(type)) {
final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
if (numStarredSessions == 0) {
// No sessions starred
rv.setTextViewText(R.id.block_title, mContext.getString(
R.string.schedule_empty_slot_title_template,
TextUtils.isEmpty(blockTitle)
? ""
: (" " + blockTitle.toLowerCase())));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1_positive));
rv.setTextViewText(R.id.block_subtitle, mContext.getString(
R.string.schedule_empty_slot_subtitle));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, false);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
} else if (numStarredSessions == 1) {
// exactly 1 session starred
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
String starredSessionRoomName =
mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (starredSessionRoomName == null) {
// TODO: remove this WAR for API not returning rooms for code labs
starredSessionRoomName = mContext.getString(
starredSessionTitle.contains("Code Lab")
? R.string.codelab_room
: R.string.unknown_room);
}
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle, starredSessionRoomName);
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID,
starredSessionId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
final Intent fillInIntent2 = new Intent();
final Bundle extras2 = new Bundle();
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true);
extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent2.putExtras(extras2);
rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2);
} else {
// 2 or more sessions starred
rv.setTextViewText(R.id.block_title,
mContext.getString(R.string.schedule_conflict_title,
numStarredSessions));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle,
mContext.getString(R.string.schedule_conflict_subtitle));
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
final Intent fillInIntent2 = new Intent();
final Bundle extras2 = new Bundle();
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras2.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION, true);
extras2.putBoolean(MyScheduleWidgetProvider.EXTRA_BUTTON, true);
extras2.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS,
numStarredSessions);
fillInIntent2.putExtras(extras2);
rv.setOnClickFillInIntent(R.id.extra_button, fillInIntent2);
}
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2));
} else if (ParserUtils.BLOCK_TYPE_KEYNOTE.equals(type)) {
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_STARRED_SESSION_ID,
starredSessionId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
} else {
rv.setTextViewText(R.id.block_title, blockTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled));
rv.setTextViewText(R.id.block_subtitle, blockMeta);
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled));
rv.setViewVisibility(R.id.extra_button, View.GONE);
// TODO: use TaskStackBuilder
final Intent fillInIntent = new Intent();
final Bundle extras = new Bundle();
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_ID, blockId);
extras.putString(MyScheduleWidgetProvider.EXTRA_BLOCK_TYPE, blockType);
extras.putInt(MyScheduleWidgetProvider.EXTRA_NUM_STARRED_SESSIONS, -1);
fillInIntent.putExtras(extras);
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillInIntent);
}
rv.setTextViewText(R.id.block_time, DateUtils.formatDateTime(mContext, blockStart,
DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_12HOUR));
}
return rv;
}
public RemoteViews getLoadingView() {
return null;
}
public int getViewTypeCount() {
return 2;
}
public long getItemId(int position) {
return position;
}
public boolean hasStableIds() {
return true;
}
public void onDataSetChanged() {
init();
}
private void init() {
if (mCursor != null) {
mCursor.close();
}
mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
ScheduleContract.Blocks.BLOCK_END + " >= ?",
new String[]{
Long.toString(UIUtils.getCurrentTime(mContext))
},
ScheduleContract.Blocks.DEFAULT_SORT);
mSections = new ArrayList<SimpleSectionedListAdapter.Section>();
mCursor.moveToFirst();
long previousTime = -1;
long time;
mPMap = new SparseIntArray();
mHeaderPositionMap = new SparseBooleanArray();
int offset = 0;
int globalPosition = 0;
while (!mCursor.isAfterLast()) {
time = mCursor.getLong(BlocksQuery.BLOCK_START);
if (!UIUtils.isSameDay(previousTime, time)) {
mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(),
DateUtils.formatDateTime(mContext, time,
DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_WEEKDAY)));
++offset;
mHeaderPositionMap.put(globalPosition, true);
mPMap.put(globalPosition, offset);
++globalPosition;
}
mHeaderPositionMap.put(globalPosition, false);
mPMap.put(globalPosition, offset);
++globalPosition;
previousTime = time;
mCursor.moveToNext();
}
LOGV(TAG, "Leaving init()");
}
}
public interface BlocksQuery {
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Blocks.BLOCK_ID,
ScheduleContract.Blocks.BLOCK_TITLE,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Blocks.BLOCK_TYPE,
ScheduleContract.Blocks.BLOCK_META,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_ID,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
};
int _ID = 0;
int BLOCK_ID = 1;
int BLOCK_TITLE = 2;
int BLOCK_START = 3;
int BLOCK_END = 4;
int BLOCK_TYPE = 5;
int BLOCK_META = 6;
int NUM_STARRED_SESSIONS = 7;
int STARRED_SESSION_ID = 8;
int STARRED_SESSION_TITLE = 9;
int STARRED_SESSION_ROOM_NAME = 10;
}
}
|
1162584980-google-io
|
android/src/com/google/android/apps/iosched/appwidget/MyScheduleWidgetService.java
|
Java
|
asf20
| 17,704
|