repo
string | commit
string | message
string | diff
string |
---|---|---|---|
360/360-Engine-for-Android
|
f375d3a9de112d40db69641af827c0a6624aa544
|
fix the not compiling unit test
|
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java
index 0113be1..89e4d25 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusPresenceTableTest.java
@@ -1,216 +1,216 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.Hashtable;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
import com.vodafone360.people.database.tables.PresenceTable;
import com.vodafone360.people.engine.presence.User;
import com.vodafone360.people.utils.LogUtils;
@Suppress
public class NowPlusPresenceTableTest extends NowPlusTableTestCase {
public NowPlusPresenceTableTest() {
super();
}
public void testCreate() {
Log.i(LOG_TAG, "***** testCreateTable *****");
mTestDatabase.getWritableDatabase().execSQL("ATTACH DATABASE ':memory:' AS presence1_db;");
PresenceTable.create(mTestDatabase.getWritableDatabase());
Log.i(LOG_TAG, "***** testCreateTable SUCCEEDED*****");
}
public void testUpdateUser() {
Log.i(LOG_TAG, "***** testUpdateUser *****");
PresenceTable.create(mTestDatabase.getWritableDatabase());
Log.i(LOG_TAG, "***** testUpdateUser: table created*****");
- assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
+ assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****");
Hashtable<String, String> status = new Hashtable<String, String>();
status.put("google", "online");
status.put("microsoft", "online");
status.put("mobile", "online");
status.put("pc", "online");
User user = new User("google::[email protected]", status);
user.setLocalContactId(12L);// fake localId
- assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED);
+ assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED);
Log.i(LOG_TAG, "***** testUpdateUser Good User test SUCCEEDED*****");
user = null;
// now, update the user
status.put("google", "offline");
status.put("microsoft", "online");
status.put("mobile", "online");
status.put("pc", "offline");
user = new User("google::[email protected]", status);
user.setLocalContactId(12L);// fake localId
- assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
+ assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
User user1 = PresenceTable.getUserPresenceByLocalContactId(12L, mTestDatabase.getReadableDatabase());
assertTrue("the initial and fetched users are not the same!", user.equals(user1));
Log.i(LOG_TAG, "***** testUpdateUser test SUCCEEDED*****");
}
public void testGetMeProfilePresenceById() {
Log.i(LOG_TAG, "***** GetMeProfilePresenceById() *****");
PresenceTable.create(mTestDatabase.getWritableDatabase());
Log.i(LOG_TAG, "***** GetMeProfilePresenceById(): table created*****");
Hashtable<String, String> status = new Hashtable<String, String>();
status.put("google", "online");
status.put("microsoft", "online");
status.put("mobile", "online");
status.put("pc", "online");
User user = new User("12345678", status); //imaginary Me Profile
user.setLocalContactId(12L);// fake localId
- assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
+ assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
Log.i(LOG_TAG, "***** testUpdateUser Good User test SUCCEEDED*****");
User user1 = PresenceTable.getUserPresenceByLocalContactId(12L, mTestDatabase.getReadableDatabase());
assertTrue("the initial and fetched users are not the same!", user.equals(user1));
assertNull(PresenceTable.getUserPresenceByLocalContactId(-1L, mTestDatabase.getReadableDatabase()));
Log.i(LOG_TAG, "***** GetMeProfilePresenceById() SUCCEEEDED*****");
}
// public void testDropTable() {
// Log.i(LOG_TAG, "***** testDropTable() *****");
// PresenceTable.create(mTestDatabase.getWritableDatabase());
// Log.i(LOG_TAG, "***** testDropTable(): table created*****");
//
// Hashtable<String, String> status = new Hashtable<String, String>();
// status.put("google", "online");
// status.put("microsoft", "online");
// status.put("mobile", "online");
// status.put("pc", "online");
// User user = new User("google::[email protected]", status);
// assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) != PresenceTable.USER_NOTADDED);
// user = null;
//// 4
// NowPlusPresenceDbUtilsTest.dropTable(mTestDatabase.getWritableDatabase());
// Log.i(LOG_TAG, "***** testDropTable(): dropped table*****");
//
// PresenceTable.create(mTestDatabase.getWritableDatabase());
// Log.i(LOG_TAG, "***** testDropTable(): table created again*****");
//
// int count = PresenceTable.setAllUsersOffline(mTestDatabase.getWritableDatabase());
// assertTrue("The count of deleted rows is not the expected one:"+count, count == 0);
// Log.i(LOG_TAG, "***** testDropTable() test SUCCEEDED*****");
// }
public void testSetAllUsersOffline() {
Log.i(LOG_TAG, "***** testSetAllUsersOffline() *****");
PresenceTable.create(mTestDatabase.getWritableDatabase());
Log.i(LOG_TAG, "***** testSetAllUsersOffline(): table created*****");
- assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
+ assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****");
// 1
Hashtable<String, String> status = new Hashtable<String, String>();
status.put("google", "online");
status.put("microsoft", "online");
status.put("mobile", "online");
// status.put("pc", "online");
User user = new User("google::[email protected]", status);
user.setLocalContactId(12L);
- assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
+ assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
LogUtils.logE("User1:"+user.toString());
user = null;
//4
// user = new User("UNPARSEBLE", status);
// assertTrue("the UNPARSEBLE user was added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_NOTADDED);
// user = null;
//4
user = new User("12345678", status);
user.setLocalContactId(13L);
- assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED);
+ assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED);
// user = null;
//8
// status.put("pc", "offline");
// user = new User("12345678", status);
user.setLocalContactId(13L);
LogUtils.logE("User2:"+user.toString());
LogUtils.logE(user.toString());
- assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
+ assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
//8
int count = PresenceTable.setAllUsersOffline(mTestDatabase.getWritableDatabase());
assertTrue("The count of deleted rows is not the expected one:"+count, count == 6);
Log.i(LOG_TAG, "***** testSetAllUsersOffline() test SUCCEEDED*****");
}
public void testSetAllUsersOfflineExceptForMe() {
Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe() *****");
PresenceTable.create(mTestDatabase.getWritableDatabase());
Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe(): table created*****");
- assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
+ assertTrue("The method adds a null user and returns true", PresenceTable.updateUser(null, null, mTestDatabase.getWritableDatabase())==PresenceTable.USER_NOTADDED);
Log.i(LOG_TAG, "***** testUpdateUser: NULL test SUCCEEDED *****");
// 1
Hashtable<String, String> status = new Hashtable<String, String>();
status.put("google", "online");
status.put("microsoft", "online");
status.put("mobile", "online");
// status.put("pc", "online");
User user = new User("google::[email protected]", status);
user.setLocalContactId(12L);
- assertTrue("the user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
+ assertTrue("the user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_ADDED);
LogUtils.logE("User1:"+user.toString());
user = null;
//4
user = new User("12345678", status);
user.setLocalContactId(13L);
- assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED);
+ assertTrue("the NowplusUser user was not added to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase())== PresenceTable.USER_ADDED);
// user = null;
//8
// status.put("pc", "offline");
// user = new User("12345678", status);
user.setLocalContactId(13L);
LogUtils.logE("User2:"+user.toString());
LogUtils.logE(user.toString());
- assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
+ assertTrue("the Existing NowplusUser might be duplicated to DB", PresenceTable.updateUser(user, null, mTestDatabase.getWritableDatabase()) == PresenceTable.USER_UPDATED);
//8
int count = PresenceTable.setAllUsersOfflineExceptForMe(12L, mTestDatabase.getWritableDatabase());
assertTrue("The count of deleted rows is not the expected one:"+count, count == 3);
Log.i(LOG_TAG, "***** testSetAllUsersOfflineExceptForMe() test SUCCEEDED*****");
}
}
|
360/360-Engine-for-Android
|
f8c218b3b54afa9ef7df4497281eb22ee4a22614
|
- adapted directory for build server
|
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties
index 20d27de..4b0e28f 100644
--- a/build_property_files/buildserver.properties
+++ b/build_property_files/buildserver.properties
@@ -1,11 +1,11 @@
# The directory that points to the Android SDK file on your machine
sdk.dir=/opt/local/android
# The directory that points to the XMLTask (ant task) on your machine
xml.task.dir=/opt/local/android/xmltask.jar
# The default emulator AVD to use for unit testing
default.avd=2_1_device_HVGA
# Name of the directory of the UI Project TODO move to generic properties file
-ui.project.name=360-UI-for-Android
\ No newline at end of file
+ui.project.name=Android_Trunk_Subtask_Checkout_UI
|
360/360-Engine-for-Android
|
bca9e42bbc52cfb495696ff8ad841320c5ed7d58
|
no comment
|
diff --git a/tests/build.xml b/tests/build.xml
index c73565d..87ceb78 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,696 +1,696 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
<property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
<!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
already on your system, please do so. After setting it, create a new properties file in
build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
to it. -->
<property file="../build_property_files/${env.USERNAME_360}.properties" />
<echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
XMLTask is found in ${xml.task.dir}...</echo>
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
- <src path="../../${ui.project}/${source.dir}" />
+ <src path="../../${ui.project.name}/${source.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests with output sent to ${junit.out.file}...</echo>
<exec executable="${adb}" failonerror="true" output="${junit.out.file}">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-r" /> <!-- XML output -->
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
<loadfile srcfile="${junit.out.file}" property="result">
<filterchain>
<linecontains>
<contains value="INSTRUMENTATION_CODE: -1"/>
</linecontains>
</filterchain>
</loadfile>
<loadfile srcfile="${junit.out.file}" property="result2">
<filterchain>
<linecontains>
<contains value="FAILURES"/>
</linecontains>
</filterchain>
</loadfile>
<echo>Result ${result} ${result2}</echo>
<loadfile property="junit-out-file" srcFile="${junit.out.file}"/>
<echo>Junit results...</echo>
<echo>${junit-out-file}</echo>
<fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
<fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
</project>
\ No newline at end of file
|
360/360-Engine-for-Android
|
562f0a52066e16eb484c48adddddf99194d5a986
|
- once more the build.xml
|
diff --git a/tests/build.xml b/tests/build.xml
index e9dcd87..c73565d 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,695 +1,696 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
<property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
<!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
already on your system, please do so. After setting it, create a new properties file in
build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
to it. -->
<property file="../build_property_files/${env.USERNAME_360}.properties" />
<echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
XMLTask is found in ${xml.task.dir}...</echo>
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
+ <src path="../../${ui.project}/${source.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests with output sent to ${junit.out.file}...</echo>
<exec executable="${adb}" failonerror="true" output="${junit.out.file}">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-r" /> <!-- XML output -->
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
<loadfile srcfile="${junit.out.file}" property="result">
<filterchain>
<linecontains>
<contains value="INSTRUMENTATION_CODE: -1"/>
</linecontains>
</filterchain>
</loadfile>
<loadfile srcfile="${junit.out.file}" property="result2">
<filterchain>
<linecontains>
<contains value="FAILURES"/>
</linecontains>
</filterchain>
</loadfile>
<echo>Result ${result} ${result2}</echo>
<loadfile property="junit-out-file" srcFile="${junit.out.file}"/>
<echo>Junit results...</echo>
<echo>${junit-out-file}</echo>
<fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
<fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
</project>
\ No newline at end of file
|
360/360-Engine-for-Android
|
fc62f96c6eebe564273d86529072cc7947f484ab
|
- altered build.xml one more time
|
diff --git a/tests/build.xml b/tests/build.xml
index c160cbb..e9dcd87 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,701 +1,695 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
-
- <property environment="env"/>
-
- <!-- The local.properties file is created and updated by the 'android' tool.
- It contains the path to the SDK. It should *NOT* be checked in in Version
- Control Systems. -->
- <!-- <property file="local.properties" /> Point to the SDK location manually -->
+ <property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
- <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
- already on your system, please do so. After setting it, create a new properties file in
- build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
- to it. -->
- <property file="../build_property_files/${env.USERNAME_360}.properties" />
- <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
- XMLTask is found in ${xml.task.dir}...</echo>
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="../build_property_files/${env.USERNAME_360}.properties" />
+ <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
+ XMLTask is found in ${xml.task.dir}...</echo>
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests with output sent to ${junit.out.file}...</echo>
<exec executable="${adb}" failonerror="true" output="${junit.out.file}">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-r" /> <!-- XML output -->
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
<loadfile srcfile="${junit.out.file}" property="result">
<filterchain>
<linecontains>
<contains value="INSTRUMENTATION_CODE: -1"/>
</linecontains>
</filterchain>
</loadfile>
<loadfile srcfile="${junit.out.file}" property="result2">
<filterchain>
<linecontains>
<contains value="FAILURES"/>
</linecontains>
</filterchain>
</loadfile>
<echo>Result ${result} ${result2}</echo>
<loadfile property="junit-out-file" srcFile="${junit.out.file}"/>
<echo>Junit results...</echo>
<echo>${junit-out-file}</echo>
<fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
<fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
-</project>
+</project>
\ No newline at end of file
|
360/360-Engine-for-Android
|
f9fb891460c7e523a21bc06e2ee12005086fd403
|
- added default.properties to tests
|
diff --git a/tests/default.properties b/tests/default.properties
new file mode 100755
index 0000000..c5d5335
--- /dev/null
+++ b/tests/default.properties
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "build.properties", and override values to adapt the script to your
+# project structure.
+
+# Indicates whether an apk should be generated for each density.
+split.density=false
+# Project target.
+target=android-8
+apk-configurations=
|
360/360-Engine-for-Android
|
4122008ae8d0b2235351951c4b81f186a103961b
|
-fixed build script for the tests
|
diff --git a/tests/build.xml b/tests/build.xml
index a63ee4b..c160cbb 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,693 +1,701 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
+ <property environment="env"/>
+
<!-- The local.properties file is created and updated by the 'android' tool.
It contains the path to the SDK. It should *NOT* be checked in in Version
Control Systems. -->
<!-- <property file="local.properties" /> Point to the SDK location manually -->
- <property name="sdk.dir" value="C:\\tools\\android-sdk-windows" />
- <property name="sdk-location" value="C:\\tools\\android-sdk-windows" />
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="../build_property_files/${env.USERNAME_360}.properties" />
+ <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
+ XMLTask is found in ${xml.task.dir}...</echo>
+
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests with output sent to ${junit.out.file}...</echo>
<exec executable="${adb}" failonerror="true" output="${junit.out.file}">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-r" /> <!-- XML output -->
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
<loadfile srcfile="${junit.out.file}" property="result">
<filterchain>
<linecontains>
<contains value="INSTRUMENTATION_CODE: -1"/>
</linecontains>
</filterchain>
</loadfile>
<loadfile srcfile="${junit.out.file}" property="result2">
<filterchain>
<linecontains>
<contains value="FAILURES"/>
</linecontains>
</filterchain>
</loadfile>
<echo>Result ${result} ${result2}</echo>
<loadfile property="junit-out-file" srcFile="${junit.out.file}"/>
<echo>Junit results...</echo>
<echo>${junit-out-file}</echo>
<fail unless="result">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
<fail if="result2">JUnit tests failed, please look at ${junit.out.file} for more
information.</fail>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk-location}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
-</project>
\ No newline at end of file
+</project>
|
360/360-Engine-for-Android
|
dca7cf311ac309755e4896d190d22bace5c6e021
|
fix for bug 1583/1464
|
diff --git a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java
index 8290a8e..5eaadee 100644
--- a/src/com/vodafone360/people/database/tables/ContactSummaryTable.java
+++ b/src/com/vodafone360/people/database/tables/ContactSummaryTable.java
@@ -1,1369 +1,1386 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.database.tables;
+import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteStatement;
import com.vodafone360.people.Settings;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.tables.ContactsTable.ContactIdInfo;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.datatypes.ContactSummary;
import com.vodafone360.people.datatypes.VCardHelper;
import com.vodafone360.people.datatypes.ContactDetail.DetailKeys;
import com.vodafone360.people.datatypes.ContactSummary.AltFieldType;
import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
import com.vodafone360.people.engine.presence.User;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.utils.CloseUtils;
import com.vodafone360.people.utils.LogUtils;
/**
* The ContactSummaryTable contains a summary of important contact details for
* each contact such as name, status and Avatar availability. This data is
* duplicated here to improve the performance of the main contact list in the UI
* (otherwise the a costly inner join between the contact and contact details
* table would be needed). This class is never instantiated hence all methods
* must be static.
*
* @version %I%, %G%
*/
public abstract class ContactSummaryTable {
/**
* The name of the table as it appears in the database.
*/
public static final String TABLE_NAME = "ContactSummary";
public static final String TABLE_INDEX_NAME = "ContactSummaryIndex";
/**
* This holds the presence information for each contact in the ContactSummaryTable
*/
private static HashMap<Long, Integer> sPresenceMap = new HashMap<Long, Integer>();
/**
* An enumeration of all the field names in the database.
*/
public static enum Field {
SUMMARYID("_id"),
LOCALCONTACTID("LocalContactId"),
DISPLAYNAME("DisplayName"),
STATUSTEXT("StatusText"),
ALTFIELDTYPE("AltFieldType"),
ALTDETAILTYPE("AltDetailType"),
ONLINESTATUS("OnlineStatus"),
NATIVEID("NativeId"),
FRIENDOFMINE("FriendOfMine"),
PICTURELOADED("PictureLoaded"),
SNS("Sns"),
SYNCTOPHONE("Synctophone");
/**
* The name of the field as it appears in the database
*/
private final String mField;
/**
* Constructor
*
* @param field - The name of the field (see list above)
*/
private Field(String field) {
mField = field;
}
/**
* @return the name of the field as it appears in the database.
*/
public String toString() {
return mField;
}
}
/**
* Creates ContactSummary Table.
*
* @param writeableDb A writable SQLite database
* @throws SQLException If an SQL compilation error occurs
*/
public static void create(SQLiteDatabase writeableDb) throws SQLException {
DatabaseHelper.trace(true, "ContactSummaryTable.create()");
//TODO: As of now kept the onlinestatus field in table. Would remove it later on
writeableDb.execSQL("CREATE TABLE " + TABLE_NAME + " (" + Field.SUMMARYID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCALCONTACTID + " LONG, "
+ Field.DISPLAYNAME + " TEXT, " + Field.STATUSTEXT + " TEXT, " + Field.ALTFIELDTYPE
+ " INTEGER, " + Field.ALTDETAILTYPE + " INTEGER, " + Field.ONLINESTATUS
+ " INTEGER, " + Field.NATIVEID + " INTEGER, " + Field.FRIENDOFMINE + " BOOLEAN, "
+ Field.PICTURELOADED + " BOOLEAN, " + Field.SNS + " STRING, " + Field.SYNCTOPHONE
+ " BOOLEAN);");
writeableDb.execSQL("CREATE INDEX " + TABLE_INDEX_NAME + " ON " + TABLE_NAME + " ( " + Field.LOCALCONTACTID + ", " + Field.DISPLAYNAME + " )");
clearPresenceMap();
}
/**
* Fetches the list of table fields that can be injected into an SQL query
* statement. The {@link #getQueryData(Cursor)} method can be used to obtain
* the data from the query.
*
* @return The query string
* @see #getQueryData(Cursor).
*/
private static String getFullQueryList() {
return Field.SUMMARYID + ", " + TABLE_NAME + "." + Field.LOCALCONTACTID + ", "
+ Field.DISPLAYNAME + ", " + Field.STATUSTEXT + ", " + Field.ONLINESTATUS + ", "
+ Field.NATIVEID + ", " + Field.FRIENDOFMINE + ", " + Field.PICTURELOADED + ", "
+ Field.SNS + ", " + Field.SYNCTOPHONE + ", " + Field.ALTFIELDTYPE + ", "
+ Field.ALTDETAILTYPE;
}
/**
* Returns a full SQL query statement to fetch the contact summary
* information. The {@link #getQueryData(Cursor)} method can be used to
* obtain the data from the query.
*
* @return The query string
* @see #getQueryData(Cursor).
*/
private static String getOrderedQueryStringSql() {
return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " ORDER BY LOWER("
+ Field.DISPLAYNAME + ")";
}
/**
* Returns a full SQL query statement to fetch the contact summary
* information. The {@link #getQueryData(Cursor)} method can be used to
* obtain the data from the query.
*
* @param whereClause An SQL where clause (without the "WHERE"). Cannot be
* null.
* @return The query string
* @see #getQueryData(Cursor).
*/
private static String getQueryStringSql(String whereClause) {
return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause;
}
/**
* Returns a full SQL query statement to fetch the contact summary
* information in alphabetical order of contact name. The
* {@link #getQueryData(Cursor)} method can be used to obtain the data from
* the query.
*
* @param whereClause An SQL where clause (without the "WHERE"). Cannot be
* null.
* @return The query string
* @see #getQueryData(Cursor).
*/
private static String getOrderedQueryStringSql(String whereClause) {
return "SELECT " + getFullQueryList() + " FROM " + TABLE_NAME + " WHERE " + whereClause
+ " ORDER BY LOWER(" + Field.DISPLAYNAME + ")";
}
/**
* UPDATE ContactSummary SET
* NativeId = ?
* WHERE LocalContactId = ?
*/
private static final String UPDATE_NATIVE_ID_BY_LOCAL_CONTACT_ID = "UPDATE " +
TABLE_NAME + " SET " + Field.NATIVEID + "=? WHERE " + Field.LOCALCONTACTID + "=?";
/**
* Column indices which match the query string returned by
* {@link #getFullQueryList()}.
*/
private static final int SUMMARY_ID = 0;
private static final int LOCALCONTACT_ID = 1;
private static final int FORMATTED_NAME = 2;
private static final int STATUS_TEXT = 3;
@SuppressWarnings("unused")
@Deprecated
private static final int ONLINE_STATUS = 4;
private static final int NATIVE_CONTACTID = 5;
private static final int FRIEND_MINE = 6;
private static final int PICTURE_LOADED = 7;
private static final int SNS = 8;
private static final int SYNCTOPHONE = 9;
private static final int ALTFIELD_TYPE = 10;
private static final int ALTDETAIL_TYPE = 11;
/**
* Fetches the contact summary data from the current record of the given
* cursor.
*
* @param c Cursor returned by one of the {@link #getFullQueryList()} based
* query methods.
* @return Filled in ContactSummary object
*/
public static ContactSummary getQueryData(Cursor c) {
ContactSummary contactSummary = new ContactSummary();
if (!c.isNull(SUMMARY_ID)) {
contactSummary.summaryID = c.getLong(SUMMARY_ID);
}
if (!c.isNull(LOCALCONTACT_ID)) {
contactSummary.localContactID = c.getLong(LOCALCONTACT_ID);
}
contactSummary.formattedName = c.getString(FORMATTED_NAME);
contactSummary.statusText = c.getString(STATUS_TEXT);
contactSummary.onlineStatus = getPresence(contactSummary.localContactID);
if (!c.isNull(NATIVE_CONTACTID)) {
contactSummary.nativeContactId = c.getInt(NATIVE_CONTACTID);
}
if (!c.isNull(FRIEND_MINE)) {
contactSummary.friendOfMine = (c.getInt(FRIEND_MINE) == 0 ? false : true);
}
if (!c.isNull(PICTURE_LOADED)) {
contactSummary.pictureLoaded = (c.getInt(PICTURE_LOADED) == 0 ? false : true);
}
if (!c.isNull(SNS)) {
contactSummary.sns = c.getString(SNS);
}
if (!c.isNull(SYNCTOPHONE)) {
contactSummary.synctophone = (c.getInt(SYNCTOPHONE) == 0 ? false : true);
}
if (!c.isNull(ALTFIELD_TYPE)) {
int val = c.getInt(ALTFIELD_TYPE);
if (val < AltFieldType.values().length) {
contactSummary.altFieldType = AltFieldType.values()[val];
}
}
if (!c.isNull(ALTDETAIL_TYPE)) {
int val = c.getInt(ALTDETAIL_TYPE);
if (val < ContactDetail.DetailKeys.values().length) {
contactSummary.altDetailType = ContactDetail.DetailKeyTypes.values()[val];
}
}
return contactSummary;
}
/**
* Fetches the contact summary for a particular contact
*
* @param localContactID The primary key ID of the contact to find
* @param summary A new ContactSummary object to be filled in
* @param readableDb Readable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus fetchSummaryItem(long localContactId, ContactSummary summary,
SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false, "ContactSummeryTable.fetchSummaryItem() localContactId["
+ localContactId + "]");
}
Cursor c1 = null;
try {
c1 = readableDb.rawQuery(
getQueryStringSql(Field.LOCALCONTACTID + "=" + localContactId), null);
if (!c1.moveToFirst()) {
LogUtils.logW("ContactSummeryTable.fetchSummaryItem() localContactId["
+ localContactId + "] not found in ContactSummeryTable.");
return ServiceStatus.ERROR_NOT_FOUND;
}
summary.copy(getQueryData(c1));
return ServiceStatus.SUCCESS;
} catch (SQLiteException e) {
LogUtils
.logE(
"ContactSummeryTable.fetchSummaryItem() Exception - Unable to fetch contact summary",
e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
} finally {
CloseUtils.close(c1);
c1 = null;
}
}
/**
* Processes a ContentValues object to handle a missing name or missing
* status.
* <ol>
* <li>If the name is missing it will be replaced using the alternative
* detail.</li>
* <li>If the name is present, but status is missing the status will be
* replaced using the alternative detail</li>
* <li>Otherwise, the althernative detail is not used</li>
* </ol>
* In any case the {@link Field#ALTFIELDTYPE} value will be updated to
* reflect how the alternative detail is being used.
*
* @param values The ContentValues object to be updated
* @param altDetail The must suitable alternative detail (see
* {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)}
*/
private static void updateAltValues(ContentValues values, ContactDetail altDetail) {
if (!values.containsKey(Field.DISPLAYNAME.toString())) {
values.put(Field.DISPLAYNAME.toString(), altDetail.getValue());
values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.NAME.ordinal());
} else if (!values.containsKey(Field.STATUSTEXT.toString())) {
values.put(Field.STATUSTEXT.toString(), altDetail.getValue());
values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.STATUS.ordinal());
} else {
values.put(Field.ALTFIELDTYPE.toString(), ContactSummary.AltFieldType.UNUSED.ordinal());
}
if (altDetail.keyType != null) {
values.put(Field.ALTDETAILTYPE.toString(), altDetail.keyType.ordinal());
}
}
/**
* Processes a ContentValues object to handle a missing name or missing
* status.
* <ol>
* <li>If type is NAME, the name will be set to the alternative detail.</li>
* <li>If type is STATUS, the status will be set to the alternative detail</li>
* <li>Otherwise, the alternative detail is not used</li>
* </ol>
* In any case the {@link Field#ALTFIELDTYPE} value will be updated to
* reflect how the alternative detail is being used.
*
* @param values The ContentValues object to be updated
* @param altDetail The must suitable alternative detail (see
* {@link #fetchNewAltDetail(long, ContactDetail, SQLiteDatabase)}
* @param type Specifies how the alternative detail should be used
*/
/*
* private static void updateAltValues(ContentValues values, ContactDetail
* altDetail, ContactSummary.AltFieldType type) { switch (type) { case NAME:
* values.put(Field.DISPLAYNAME.toString(), altDetail.getValue());
* values.put(Field.ALTFIELDTYPE.toString(),
* ContactSummary.AltFieldType.NAME .ordinal()); break; case STATUS:
* values.put(Field.STATUSTEXT.toString(), altDetail.getValue());
* values.put(Field.ALTFIELDTYPE.toString(),
* ContactSummary.AltFieldType.STATUS .ordinal()); break; default:
* values.put(Field.ALTFIELDTYPE.toString(),
* ContactSummary.AltFieldType.UNUSED .ordinal()); } if (altDetail.keyType
* != null) { values.put(Field.ALTDETAILTYPE.toString(),
* altDetail.keyType.ordinal()); } }
*/
/**
* Adds contact summary information to the table for a new contact. If the
* contact has no name or no status, an alternative detail will be used such
* as telephone number or email address.
*
* @param contact The new contact
* @param writableDb Writable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus addContact(Contact contact, SQLiteDatabase writableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true, "ContactSummeryTable.addContact() contactID["
+ contact.contactID + "]");
}
if (contact.localContactID == null) {
LogUtils.logE("ContactSummeryTable.addContact() Invalid parameters");
return ServiceStatus.ERROR_NOT_FOUND;
}
try {
final ContentValues values = new ContentValues();
values.put(Field.LOCALCONTACTID.toString(), contact.localContactID);
values.put(Field.NATIVEID.toString(), contact.nativeContactId);
values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine);
values.put(Field.SYNCTOPHONE.toString(), contact.synctophone);
ContactDetail altDetail = findAlternativeNameContactDetail(values, contact.details);
updateAltValues(values, altDetail);
addToPresenceMap(contact.localContactID);
if (writableDb.insertOrThrow(TABLE_NAME, null, values) < 0) {
LogUtils.logE("ContactSummeryTable.addContact() "
+ "Unable to insert new contact summary");
return ServiceStatus.ERROR_NOT_FOUND;
}
return ServiceStatus.SUCCESS;
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.addContact() SQLException - "
+ "Unable to insert new contact summary", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
}
/**
* This method returns the most preferred contact detail to be displayed
* instead of the contact name when vcard.name is missing.
*
* @param values - ContentValues to be stored in the DB for the added
* contact
* @param details - the list of all contact details for the contact being
* added
* @return the contact detail most suitable to replace the missing
* vcard.name. "Value" field may be empty if no suitable contact
* detail was found.
*/
private static ContactDetail findAlternativeNameContactDetail(ContentValues values,
List<ContactDetail> details) {
ContactDetail altDetail = new ContactDetail();
for (ContactDetail detail : details) {
getContactValuesFromDetail(values, detail);
if (isPreferredAltDetail(detail, altDetail)) {
altDetail.copy(detail);
}
}
return altDetail;
}
/**
* Deletes a contact summary record
*
* @param localContactID The primary key ID of the contact to delete
* @param writableDb Writeable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus deleteContact(Long localContactId, SQLiteDatabase writableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true, "ContactSummeryTable.deleteContact() localContactId["
+ localContactId + "]");
}
if (localContactId == null) {
LogUtils.logE("ContactSummeryTable.deleteContact() Invalid parameters");
return ServiceStatus.ERROR_NOT_FOUND;
}
try {
if (writableDb.delete(TABLE_NAME, Field.LOCALCONTACTID + "=" + localContactId, null) <= 0) {
LogUtils.logE("ContactSummeryTable.deleteContact() "
+ "Unable to delete contact summary");
return ServiceStatus.ERROR_NOT_FOUND;
}
deleteFromPresenceMap(localContactId);
return ServiceStatus.SUCCESS;
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.deleteContact() SQLException - "
+ "Unable to delete contact summary", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
}
/**
* Modifies contact parameters. Called when fields in the Contacts table
* have been changed.
*
* @param contact The modified contact
* @param writableDb Writable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus modifyContact(Contact contact, SQLiteDatabase writableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true, "ContactSummeryTable.modifyContact() contactID["
+ contact.contactID + "]");
}
if (contact.localContactID == null) {
LogUtils.logE("ContactSummeryTable.modifyContact() Invalid parameters");
return ServiceStatus.ERROR_NOT_FOUND;
}
try {
final ContentValues values = new ContentValues();
values.put(Field.LOCALCONTACTID.toString(), contact.localContactID);
values.put(Field.NATIVEID.toString(), contact.nativeContactId);
values.put(Field.FRIENDOFMINE.toString(), contact.friendOfMine);
values.put(Field.SYNCTOPHONE.toString(), contact.synctophone);
String[] args = {
String.format("%d", contact.localContactID)
};
if (writableDb.update(TABLE_NAME, values, Field.LOCALCONTACTID + "=?", args) < 0) {
LogUtils.logE("ContactSummeryTable.modifyContact() "
+ "Unable to update contact summary");
return ServiceStatus.ERROR_NOT_FOUND;
}
return ServiceStatus.SUCCESS;
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.modifyContact() "
+ "SQLException - Unable to update contact summary", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
}
/**
* Adds suitable entries to a ContentValues objects for inserting or
* updating the contact summary table, from a contact detail.
*
* @param contactValues The content values object to update
* @param newDetail The new or modified detail
* @return true if the summary table has been updated, false otherwise
*/
private static boolean getContactValuesFromDetail(ContentValues contactValues,
ContactDetail newDetail) {
switch (newDetail.key) {
case VCARD_NAME:
if (newDetail.value != null) {
VCardHelper.Name name = newDetail.getName();
if (name != null) {
String nameStr = name.toString();
// this is what we do to display names of contacts
// coming from server
if (nameStr.length() > 0) {
contactValues.put(Field.DISPLAYNAME.toString(), name.toString());
}
}
}
return true;
case PRESENCE_TEXT:
if (newDetail.value != null && newDetail.value.length() > 0) {
contactValues.put(Field.STATUSTEXT.toString(), newDetail.value);
contactValues.put(Field.SNS.toString(), newDetail.alt);
}
return true;
case PHOTO:
if (newDetail.value == null) {
contactValues.put(Field.PICTURELOADED.toString(), (Boolean)null);
} else {
contactValues.put(Field.PICTURELOADED.toString(), false);
}
return true;
default:
// Do Nothing.
}
return false;
}
/**
* Determines if a contact detail should be used in preference to the
* current alternative detail (the alternative detail is one that is shown
* when a contact has no name or no status).
*
* @param newDetail The new detail
* @param currentDetail The current alternative detail
* @return true if the new detail should be used, false otherwise
*/
private static boolean isPreferredAltDetail(ContactDetail newDetail, ContactDetail currentDetail) {
// this means we'll update the detail
if (currentDetail.key == null || (currentDetail.key == DetailKeys.UNKNOWN)) {
return true;
}
switch (newDetail.key) {
case VCARD_PHONE:
// AA:EMAIL,IMADDRESS,ORG will not be updated, PHONE will
// consider "preferred" detail check
switch (currentDetail.key) {
case VCARD_EMAIL:
case VCARD_IMADDRESS:
case VCARD_ORG:
case VCARD_ADDRESS:
case VCARD_BUSINESS:
case VCARD_TITLE:
case VCARD_ROLE:
return false;
case VCARD_PHONE:
break;
default:
return true;
}
break;
case VCARD_IMADDRESS:
// AA:will be updating everything, except for EMAIL and ORG, and
// IMADDRESS, when preferred details needs to be considered
// first
switch (currentDetail.key) {
case VCARD_IMADDRESS:
break;
case VCARD_EMAIL:
case VCARD_ORG:
case VCARD_ROLE:
case VCARD_TITLE:
return false;
default:
return true;
}
break;
case VCARD_ADDRESS:
case VCARD_BUSINESS:
// AA:will be updating everything, except for EMAIL and ORG,
// when preferred details needs to be considered first
switch (currentDetail.key) {
case VCARD_EMAIL:
case VCARD_ORG:
case VCARD_ROLE:
case VCARD_TITLE:
return false;
case VCARD_ADDRESS:
case VCARD_BUSINESS:
break;
default:
return true;
}
break;
case VCARD_ROLE:
case VCARD_TITLE:
// AA:will be updating everything, except for EMAIL and ORG,
// when preferred details needs to be considered first
switch (currentDetail.key) {
case VCARD_EMAIL:
case VCARD_ORG:
return false;
case VCARD_ROLE:
case VCARD_TITLE:
break;
default:
return true;
}
break;
case VCARD_ORG:
// AA:will be updating everything, except for EMAIL and ORG,
// when preferred details needs to be considered first
switch (currentDetail.key) {
case VCARD_EMAIL:
return false;
case VCARD_ORG:
break;
default:
return true;
}
break;
case VCARD_EMAIL:
// AA:will be updating everything, except for EMAIL, when
// preferred details needs to be considered first
switch (currentDetail.key) {
case VCARD_EMAIL:
break;
default:
return true;
}
break;
default:
return false;
}
if (currentDetail.order == null) {
return true;
}
if (newDetail.order != null && newDetail.order.compareTo(currentDetail.order) < 0) {
return true;
}
return false;
}
/**
* Fetches a list of native contact IDs from the summary table (in ascending
* order)
*
* @param summaryList A list that will be populated by this function
* @param readableDb Readable SQLite database
* @return true if successful, false otherwise
*/
public static boolean fetchNativeContactIdList(List<Integer> summaryList,
SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false, "ContactSummeryTable.fetchNativeContactIdList()");
}
summaryList.clear();
Cursor c = null;
try {
c = readableDb.rawQuery("SELECT " + Field.NATIVEID + " FROM " + TABLE_NAME + " WHERE "
+ Field.NATIVEID + " IS NOT NULL" + " ORDER BY " + Field.NATIVEID, null);
while (c.moveToNext()) {
if (!c.isNull(0)) {
summaryList.add(c.getInt(0));
}
}
return true;
} catch (SQLException e) {
return false;
} finally {
CloseUtils.close(c);
c = null;
}
}
/**
* Modifies the avatar loaded flag for a particular contact
*
* @param localContactID The primary key ID of the contact
* @param value Can be one of the following values:
* <ul>
* <li>true - The avatar has been loaded</li>
* <li>false - There contact has an avatar but it has not yet
* been loaded</li>
* <li>null - The contact does not have an avatar</li>
* </ul>
* @param writeableDb Writable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus modifyPictureLoadedFlag(Long localContactId, Boolean value,
SQLiteDatabase writeableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true,
"ContactSummeryTable.modifyPictureLoadedFlag() localContactId["
+ localContactId + "] value[" + value + "]");
}
try {
ContentValues cv = new ContentValues();
cv.put(Field.PICTURELOADED.toString(), value);
String[] args = {
String.format("%d", localContactId)
};
if (writeableDb.update(TABLE_NAME, cv, Field.LOCALCONTACTID + "=?", args) <= 0) {
LogUtils.logE("ContactSummeryTable.modifyPictureLoadedFlag() "
+ "Unable to modify picture loaded flag");
return ServiceStatus.ERROR_NOT_FOUND;
}
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.modifyPictureLoadedFlag() "
+ "SQLException - Unable to modify picture loaded flag", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
return ServiceStatus.SUCCESS;
}
/**
* Get a group constraint for SQL query depending on the group type.
*
* @param groupFilterId the group id
* @return a String containing the corresponding group constraint
*/
private static String getGroupConstraint(Long groupFilterId) {
if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_PHONEBOOK)) {
return " WHERE " + ContactSummaryTable.Field.SYNCTOPHONE + "=" + "1";
}
if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_CONNECTED_FRIENDS)) {
return " WHERE " + ContactSummaryTable.Field.FRIENDOFMINE + "=" + "1";
}
if ((groupFilterId != null) && (groupFilterId == GroupsTable.GROUP_ONLINE)) {
String inClause = getOnlineWhereClause();
return " WHERE " + ContactSummaryTable.Field.LOCALCONTACTID + " IN " + (inClause == null? "()": inClause);
}
return " INNER JOIN " + ContactGroupsTable.TABLE_NAME + " WHERE "
+ ContactSummaryTable.TABLE_NAME + "." + ContactSummaryTable.Field.LOCALCONTACTID
+ "=" + ContactGroupsTable.TABLE_NAME + "."
+ ContactGroupsTable.Field.LOCALCONTACTID + " AND "
+ ContactGroupsTable.Field.ZYBGROUPID + "=" + groupFilterId;
}
/**
* Fetches a contact list cursor for a given filter and search constraint
*
* @param groupFilterId The server group ID or null to fetch all groups
* @param constraint A search string or null to fetch without constraint
* @param meProfileId The current me profile Id which should be excluded
* from the returned list.
* @param readableDb Readable SQLite database
* @return The cursor or null if an error occurred
* @see #getQueryData(Cursor)
*/
public static Cursor openContactSummaryCursor(Long groupFilterId, CharSequence constraint,
Long meProfileId, SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() "
+ "groupFilterId[" + groupFilterId + "] constraint[" + constraint + "]"
+ " meProfileId[" + meProfileId + "]");
}
try {
if (meProfileId == null) {
// Ensure that when the profile is not available the function
// doesn't fail
// Since "Field <> null" always returns false
meProfileId = -1L;
}
if (groupFilterId == null) {
if (constraint == null) {
// Fetch all contacts
return openContactSummaryCursor(groupFilterId, meProfileId, readableDb);
} else {
return openContactSummaryCursor(constraint, meProfileId, readableDb);
}
} else {
// filtering by group id
if (constraint == null) {
return openContactSummaryCursor(groupFilterId, meProfileId, readableDb);
} else {
// filter by both group and constraint
final String dbSafeConstraint = DatabaseUtils.sqlEscapeString("%" + constraint
+ "%");
return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList()
+ " FROM " + ContactSummaryTable.TABLE_NAME
+ getGroupConstraint(groupFilterId) + " AND "
+ ContactSummaryTable.Field.DISPLAYNAME + " LIKE " + dbSafeConstraint
+ " AND " + ContactSummaryTable.TABLE_NAME + "."
+ ContactSummaryTable.Field.LOCALCONTACTID + "<>" + meProfileId
+ " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")",
null);
}
}
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.fetchContactList() "
+ "SQLException - Unable to fetch filtered summary cursor", e);
return null;
}
}
/**
* Fetches a contact list cursor for a given filter
*
* @param groupFilterId The server group ID or null to fetch all groups
* @param meProfileId The current me profile Id which should be excluded
* from the returned list.
* @param readableDb Readable SQLite database
* @return The cursor or null if an error occurred
* @see #getQueryData(Cursor)
*/
private static Cursor openContactSummaryCursor(Long groupFilterId, Long meProfileId,
SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() groupFilterId["
+ groupFilterId + "] meProfileId[" + meProfileId + "]");
}
try {
if (groupFilterId == null) {
// Fetch all contacts
return readableDb.rawQuery(getOrderedQueryStringSql(ContactSummaryTable.TABLE_NAME
+ "." + ContactSummaryTable.Field.LOCALCONTACTID + "<>" + meProfileId),
null);
}
return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList()
+ " FROM " + ContactSummaryTable.TABLE_NAME + getGroupConstraint(groupFilterId)
+ " AND " + ContactSummaryTable.TABLE_NAME + "."
+ ContactSummaryTable.Field.LOCALCONTACTID + "!=" + meProfileId
+ " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")", null);
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.fetchContactList() "
+ "SQLException - Unable to fetch filtered summary cursor", e);
return null;
}
}
/**
* Fetches a contact list cursor for a given search constraint
*
* @param constraint A search string or null to fetch without constraint
* @param meProfileId The current me profile Id which should be excluded
* from the returned list.
* @param readableDb Readable SQLite database
* @return The cursor or null if an error occurred
* @see #getQueryData(Cursor)
*/
private static Cursor openContactSummaryCursor(CharSequence constraint, Long meProfileId,
SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false, "ContactSummeryTable.fetchContactList() constraint["
+ constraint + "] meProfileId[" + meProfileId + "]");
}
try {
if (constraint == null) {
// Fetch all contacts
return readableDb.rawQuery(getOrderedQueryStringSql(), null);
}
final String dbSafeConstraint = DatabaseUtils.sqlEscapeString("%" + constraint + "%");
return readableDb.rawQuery("SELECT " + ContactSummaryTable.getFullQueryList()
+ " FROM " + ContactSummaryTable.TABLE_NAME + " WHERE "
+ ContactSummaryTable.Field.DISPLAYNAME + " LIKE " + dbSafeConstraint + " AND "
+ ContactSummaryTable.TABLE_NAME + "."
+ ContactSummaryTable.Field.LOCALCONTACTID + "!=" + meProfileId
+ " ORDER BY LOWER(" + ContactSummaryTable.Field.DISPLAYNAME + ")", null);
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.fetchContactList() "
+ "SQLException - Unable to fetch filtered summary cursor", e);
return null;
}
}
/**
* Fetches the current alternative field type for a contact This value
* determines how the alternative detail is currently being used for the
* record.
*
* @param localContactID The primary key ID of the contact
* @param readableDb Readable SQLite database
* @return The alternative field type or null if a database error occurred
*/
/*
* private static AltFieldType fetchAltFieldType(long localContactId,
* SQLiteDatabase readableDb) { if (Settings.ENABLED_DATABASE_TRACE) {
* DatabaseHelper.trace(false,
* "ContactSummeryTable.FetchAltFieldType() localContactId[" +
* localContactId + "]"); } Cursor c = null; try { c =
* readableDb.rawQuery("SELECT " + Field.ALTFIELDTYPE + " FROM " +
* ContactSummaryTable.TABLE_NAME + " WHERE " + Field.LOCALCONTACTID + "=" +
* localContactId, null); AltFieldType type = AltFieldType.UNUSED; if
* (c.moveToFirst() && !c.isNull(0)) { int val = c.getInt(0); if (val <
* AltFieldType.values().length) { type = AltFieldType.values()[val]; } }
* return type; } catch (SQLException e) {
* LogUtils.logE("ContactSummeryTable.fetchContactList() " +
* "SQLException - Unable to fetch alt field type", e); return null; }
* finally { CloseUtils.close(c); c = null; } }
*/
/**
* Fetches an SQLite statement object which can be used to merge the native
* information from one contact to another.
*
* @param writableDb Writable SQLite database
* @return The SQL statement, or null if a compile error occurred
* @see #mergeContact(ContactIdInfo, SQLiteStatement)
*/
public static SQLiteStatement mergeContactStatement(SQLiteDatabase
writableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true, "ContactSummeryTable.mergeContact()");
} try {
return writableDb.compileStatement(UPDATE_NATIVE_ID_BY_LOCAL_CONTACT_ID);
} catch (SQLException e) {
LogUtils.logE("ContactSummaryTable.mergeContactStatement() compile error:\n", e);
return null;
}
}
/**
* Copies the contact native information from one contact to another
*
* @param info Copies the {@link ContactIdInfo#nativeId} value to the
* contact with local ID {@link ContactIdInfo#mergedLocalId}.
* @param statement The statement returned by
* {@link #mergeContactStatement(SQLiteDatabase)}.
* @return SUCCESS or a suitable error code
* @see #mergeContactStatement(SQLiteDatabase)
*/
public static ServiceStatus mergeContact(ContactIdInfo info, SQLiteStatement statement) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(true, "ContactSummeryTable.mergeContact()");
}
if (statement == null) {
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
try {
statement.bindLong(1, info.nativeId);
statement.bindLong(2, info.mergedLocalId);
statement.execute();
return ServiceStatus.SUCCESS;
} catch (SQLException e) {
LogUtils.logE("ContactSummeryTable.mergeContact() "
+ "SQLException - Unable to merge contact summary native info:\n", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
}
}
/**
* TODO: be careful
*
* @param user
* @param writableDb
* @return
*/
public synchronized static ServiceStatus updateOnlineStatus(User user) {
sPresenceMap.put(user.getLocalContactId(), user.isOnline());
return ServiceStatus.SUCCESS;
}
+
+ /**
+ * This method sets users offline except for provided local contact ids.
+ * @param userIds - ArrayList of integer user ids, if null - all user will be removed from the presence hash.
+ * @param writableDb - database.
+ */
+ public synchronized static void setUsersOffline(ArrayList<Long> userIds) {
+ Iterator<Long> itr = sPresenceMap.keySet().iterator();
+ Long localId = null;
+ while(itr.hasNext()) {
+ localId = itr.next();
+ if (userIds == null || !userIds.contains(localId)) {
+ itr.remove();
+ }
+ }
+ }
/**
* @param user
* @param writableDb
* @return
*/
public synchronized static ServiceStatus setOfflineStatus() {
// If any contact is not present within the presenceMap, then its status
// is considered as OFFLINE. This is taken care in the getPresence API.
if (sPresenceMap != null) {
sPresenceMap.clear();
}
return ServiceStatus.SUCCESS;
}
/**
* @param localContactIdOfMe
* @param writableDb
* @return
*/
public synchronized static ServiceStatus setOfflineStatusExceptForMe(long localContactIdOfMe) {
// If any contact is not present within the presenceMap, then its status
// is considered as OFFLINE. This is taken care in the getPresence API.
if (sPresenceMap != null) {
sPresenceMap.clear();
sPresenceMap.put(localContactIdOfMe, OnlineStatus.OFFLINE.ordinal());
}
return ServiceStatus.SUCCESS;
}
/**
* Updates the native IDs for a list of contacts.
*
* @param contactIdList A list of ContactIdInfo objects. For each object,
* the local ID must match a local contact ID in the table. The
* Native ID will be used for the update. Other fields are
* unused.
* @param writeableDb Writable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus syncSetNativeIds(List<ContactIdInfo> contactIdList,
SQLiteDatabase writableDb) {
DatabaseHelper.trace(true, "ContactSummaryTable.syncSetNativeIds()");
if (contactIdList.size() == 0) {
return ServiceStatus.SUCCESS;
}
final SQLiteStatement statement1 = writableDb.compileStatement("UPDATE " + TABLE_NAME
+ " SET " + Field.NATIVEID + "=? WHERE " + Field.LOCALCONTACTID + "=?");
for (int i = 0; i < contactIdList.size(); i++) {
final ContactIdInfo info = contactIdList.get(i);
try {
writableDb.beginTransaction();
if (info.nativeId == null) {
statement1.bindNull(1);
} else {
statement1.bindLong(1, info.nativeId);
}
statement1.bindLong(2, info.localId);
statement1.execute();
writableDb.setTransactionSuccessful();
} catch (SQLException e) {
LogUtils.logE("ContactSummaryTable.syncSetNativeIds() "
+ "SQLException - Unable to update contact native Ids", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
} finally {
writableDb.endTransaction();
}
}
return ServiceStatus.SUCCESS;
}
private static boolean isEmpty(String string) {
if (string == null)
return true;
if (string.trim().length() == 0)
return true;
return false;
}
/**
* Updates the summary for a contact Replaces the complex logic of updating
* the summary with a new contactdetail. Instead the method gets a whole
* contact after it has been modified and builds the summary infos.
*
* @param contact A Contact object that has been modified
* @param writeableDb Writable SQLite database
* @return SUCCESS or a suitable error code
*/
public static ServiceStatus updateNameAndStatus(Contact contact, SQLiteDatabase writableDb) {
// These two Arrays contains the order in which the details are queried.
// First valid (not empty or unknown) detail is taken
ContactDetail.DetailKeys prefferredNameDetails[] = {
ContactDetail.DetailKeys.VCARD_NAME, ContactDetail.DetailKeys.VCARD_ORG,
ContactDetail.DetailKeys.VCARD_EMAIL, ContactDetail.DetailKeys.VCARD_PHONE
};
ContactDetail.DetailKeys prefferredStatusDetails[] = {
ContactDetail.DetailKeys.PRESENCE_TEXT, ContactDetail.DetailKeys.VCARD_PHONE,
ContactDetail.DetailKeys.VCARD_EMAIL
};
ContactDetail name = null;
ContactDetail status = null;
// Query the details for the name field
for (ContactDetail.DetailKeys key : prefferredNameDetails) {
if ((name = contact.getContactDetail(key)) != null) {
// Some contacts have only email but the name detail!=null
// (gmail for example)
if (key == ContactDetail.DetailKeys.VCARD_NAME && name.getName() == null)
continue;
if (key != ContactDetail.DetailKeys.VCARD_NAME && isEmpty(name.getValue()))
continue;
break;
}
}
// Query the details for status field
for (ContactDetail.DetailKeys key : prefferredStatusDetails) {
if ((status = contact.getContactDetail(key)) != null) {
// Some contacts have only email but the name detail!=null
// (gmail for example)
if (key == ContactDetail.DetailKeys.VCARD_NAME && status.getName() == null)
continue;
if (key != ContactDetail.DetailKeys.VCARD_NAME && isEmpty(status.getValue()))
continue;
break;
}
}
// Build the name
String nameString = name != null ? name.getValue() : null;
if (nameString == null)
nameString = ContactDetail.UNKNOWN_NAME;
if (name != null && name.key == ContactDetail.DetailKeys.VCARD_NAME)
nameString = name.getName().toString();
// Build the status
String statusString = status != null ? status.getValue() : null;
if (statusString == null)
statusString = "";
if (status != null && status.key == ContactDetail.DetailKeys.VCARD_NAME)
statusString = status.getName().toString();
int altFieldType = AltFieldType.STATUS.ordinal();
int altDetailType = (status != null && status.keyType != null) ? status.keyType.ordinal()
: ContactDetail.DetailKeyTypes.UNKNOWN.ordinal();
// This has to be done in order to set presence text. altFieldType and
// altDetailType have to be 0, SNS has to be set
String sns = "";
if (status != null && status.key == ContactDetail.DetailKeys.PRESENCE_TEXT) {
altFieldType = AltFieldType.UNUSED.ordinal();
altDetailType = 0;
sns = status.alt;
}
// If no status is present, display nothing
if (isEmpty(statusString)) {
altFieldType = AltFieldType.UNUSED.ordinal();
altDetailType = 0;
}
// Start updating the table
SQLiteStatement statement = null;
try {
statement = writableDb.compileStatement("UPDATE " + TABLE_NAME
+ " SET " + Field.DISPLAYNAME + "=?," + Field.STATUSTEXT + "=?,"
+ Field.ALTDETAILTYPE + "=?," + Field.ALTFIELDTYPE + "=?," + Field.SNS
+ "=? WHERE " + Field.LOCALCONTACTID + "=?");
writableDb.beginTransaction();
statement.bindString(1, nameString);
statement.bindString(2, statusString);
statement.bindLong(3, altDetailType);
statement.bindLong(4, altFieldType);
statement.bindString(5, sns);
statement.bindLong(6, contact.localContactID);
statement.execute();
writableDb.setTransactionSuccessful();
} catch (SQLException e) {
LogUtils.logE("ContactSummaryTable.updateNameAndStatus() "
+ "SQLException - Unable to update contact native Ids", e);
return ServiceStatus.ERROR_DATABASE_CORRUPT;
} finally {
writableDb.endTransaction();
if(statement != null) {
statement.close();
statement = null;
}
}
return ServiceStatus.SUCCESS;
}
/**
* LocalId = ?
*/
private final static String SQL_STRING_LOCAL_ID_EQUAL_QUESTION_MARK = Field.LOCALCONTACTID + " = ?";
/**
*
* @param localContactId
* @param writableDb
* @return
*/
public static boolean setNativeContactId(long localContactId, long nativeContactId, SQLiteDatabase writableDb) {
final ContentValues values = new ContentValues();
values.put(Field.NATIVEID.toString(), nativeContactId);
try {
if (writableDb.update(TABLE_NAME, values, SQL_STRING_LOCAL_ID_EQUAL_QUESTION_MARK, new String[] { Long.toString(localContactId) }) == 1) {
return true;
}
} catch (Exception e) {
LogUtils.logE("ContactsTable.setNativeContactId() Exception - " + e);
}
return false;
}
/**
* Clears the Presence Map table. This needs to be called whenever the ContactSummaryTable is cleared
* or recreated.
*/
private synchronized static void clearPresenceMap() {
sPresenceMap.clear();
}
/**
* Fetches the presence of the contact with localContactID
*
* @param localContactID
* @return the presence status of the contact
*/
private synchronized static OnlineStatus getPresence(Long localContactID) {
OnlineStatus onlineStatus = OnlineStatus.OFFLINE;
Integer val = sPresenceMap.get(localContactID);
if (val != null) {
if (val < ContactSummary.OnlineStatus.values().length) {
onlineStatus = ContactSummary.OnlineStatus.values()[val];
}
}
return onlineStatus;
}
/**
* This API should be called whenever a contact is added. The presenceMap should be consistent
* with the ContactSummaryTable. Hence the default status of OFFLINE is set for every contact added
* @param localContactID
*/
private synchronized static void addToPresenceMap(Long localContactID) {
sPresenceMap.put(localContactID, OnlineStatus.OFFLINE.ordinal());
}
/**
* This API should be called whenever a contact is deleted from teh ContactSUmmaryTable. This API
* removes the presence information for the given contact
* @param localContactId
*/
private synchronized static void deleteFromPresenceMap(Long localContactId) {
sPresenceMap.remove(localContactId);
}
/**
* This API creates the string to be used in the IN clause when getting the list of all
* online contacts.
* @return The list of contacts in the proper format for the IN list
*/
private synchronized static String getOnlineWhereClause() {
Set<Entry<Long, Integer>> set = sPresenceMap.entrySet();
Iterator<Entry<Long, Integer>> i = set.iterator();
String inClause = "(";
boolean isFirst = true;
while (i.hasNext()) {
Entry<Long, Integer> me = (Entry<Long, Integer>) i.next();
Integer value = me.getValue();
if (value != null
&& (value == OnlineStatus.ONLINE.ordinal() || value == OnlineStatus.IDLE
.ordinal())) {
if (isFirst == false) {
inClause = inClause.concat(",");
} else {
isFirst = false;
}
inClause = inClause.concat(String.valueOf(me.getKey()));
}
}
if (isFirst == true) {
inClause = null;
} else {
inClause = inClause.concat(")");
}
return inClause;
}
/**
* Fetches the formattedName for the corresponding localContactId.
*
* @param localContactId The primary key ID of the contact to find
* @param readableDb Readable SQLite database
* @return String formattedName or NULL on error
*/
public static String fetchFormattedNamefromLocalContactId(
final long localContactId, final SQLiteDatabase readableDb) {
if (Settings.ENABLED_DATABASE_TRACE) {
DatabaseHelper.trace(false,
"ContactSummaryTable.fetchFormattedNamefromLocalContactId"
+ " localContactId[" + localContactId + "]");
}
Cursor c1 = null;
String formattedName = null;
try {
String query = "SELECT " + Field.DISPLAYNAME + " FROM " + TABLE_NAME
+ " WHERE " + Field.LOCALCONTACTID + "=" + localContactId;
c1 = readableDb.rawQuery(query, null);
if (c1 != null && c1.getCount() > 0) {
c1.moveToFirst();
formattedName = c1.getString(0);
}
return formattedName;
} catch (SQLiteException e) {
LogUtils
.logE(
"fetchFormattedNamefromLocalContactId() "
+ "Exception - Unable to fetch contact summary",
e);
return formattedName;
} finally {
CloseUtils.close(c1);
c1 = null;
}
}
}
diff --git a/src/com/vodafone360/people/database/tables/PresenceTable.java b/src/com/vodafone360/people/database/tables/PresenceTable.java
index 8238a79..41e0a11 100644
--- a/src/com/vodafone360/people/database/tables/PresenceTable.java
+++ b/src/com/vodafone360/people/database/tables/PresenceTable.java
@@ -1,316 +1,414 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.database.tables;
import java.util.ArrayList;
+import java.util.Iterator;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.SQLKeys;
-
import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
import com.vodafone360.people.engine.presence.NetworkPresence;
import com.vodafone360.people.engine.presence.User;
import com.vodafone360.people.utils.CloseUtils;
import com.vodafone360.people.utils.LogUtils;
import com.vodafone360.people.utils.StringBufferPool;
/**
* PresenceTable... The table for storing the presence states of contacts.
*
* @throws SQLException is thrown when request to create a table fails with an
* SQLException
* @throws NullPointerException if the passed in database instance is null
*/
public abstract class PresenceTable {
/***
* The name of the table as it appears in the database.
*/
public static final String TABLE_NAME = "Presence"; // it is used in the
// tests
/**
* The return types for the add/update method: if a new record was added.
*/
public static final int USER_ADDED = 0;
/**
* The return types for the add/update method: if an existing record was
* updated.
*/
public static final int USER_UPDATED = 1;
/**
* The return types for the add/update method: if an error happened and
* prevented the record from being added or updated.
*/
public static final int USER_NOTADDED = 2;
/**
* An enumeration of all the field names in the database, containing ID,
* LOCAL_CONTACT_ID, USER_ID, NETWORK_ID, NETWORK_STATUS.
*/
private static enum Field {
/**
* The primary key.
*/
ID("id"),
/**
* The internal representation of the serverId for this account.
*/
LOCAL_CONTACT_ID("LocalContactId"),
/**
* This is contact list id: gmail, facebook, nowplus or other account,
* STRING.
*/
USER_ID("ImAddress"),
/**
* The SocialNetwork id, INT.
*/
NETWORK_ID("NetworkId"),
/**
* The presence status id, INT.
*/
NETWORK_STATUS("Status");
/**
* The name of the field as it appears in the database.
*/
private String mField;
/**
* Constructor.
*
* @param field - Field name
*/
private Field(String field) {
mField = field;
}
/*
* This implementation returns the field name. (non-Javadoc)
* @see java.lang.Enum#toString()
*/
public String toString() {
return mField;
}
}
/**
* The constants for column indexes in the table: LocalContactId
*/
private static final int LOCAL_CONTACT_ID = 1;
/**
* The constants for column indexes in the table: ImAddress
*/
private static final int USER_ID = 2;
/**
* The constants for column indexes in the table: NetworkId
*/
private static final int NETWORK_ID = 3;
/**
* The constants for column indexes in the table: Status
*/
private static final int NETWORK_STATUS = 4;
/**
* The default message for the NullPointerException caused by the null
* instance of database passed into PresenceTable methods.
*/
private static final String DEFAULT_ERROR_MESSAGE = "PresenceTable: the passed in database is null!";
/**
* This method creates the PresenceTable.
*
* @param writableDb - the writable database
* @throws SQLException is thrown when request to create a table fails with
* an SQLException
* @throws NullPointerException if the passed in database instance is null
*/
public static void create(SQLiteDatabase writableDb) throws SQLException, NullPointerException {
DatabaseHelper.trace(true, "PresenceTable.create()");
if (writableDb == null) {
throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
}
String createSql = "CREATE TABLE IF NOT EXISTS " + DatabaseHelper.DATABASE_PRESENCE + "." + TABLE_NAME + " (" + Field.ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + Field.LOCAL_CONTACT_ID + " LONG, "
+ Field.USER_ID + " STRING, " + Field.NETWORK_ID + " INT, " + Field.NETWORK_STATUS
+ " INT);";
writableDb.execSQL(createSql);
}
/**
* This method updates the user with the information from the User wrapper.
*
* @param user2Update - User info to update
+ * @param ignoredNetworkIds - ArrayList of integer network ids presence state for which must be ignored.
* @param writableDatabase - writable database
* @return USER_ADDED if no user with user id like the one in user2Update
* payload "status.getUserId()" ever existed in this table,
* USER_UPDATED if the user already existed in the table and has
* been successfully added, USER_NOT_ADDED - if user was not added.
* @throws SQLException if the database layer throws this exception.
* @throws NullPointerException if the passed in database instance is null.
*/
- public static int updateUser(User user2Update, SQLiteDatabase writableDatabase)
+ public static int updateUser(User user2Update, ArrayList<Integer> ignoredNetworkIds, SQLiteDatabase writableDatabase)
throws SQLException, NullPointerException {
int ret = USER_NOTADDED;
if (writableDatabase == null) {
throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
}
if (user2Update != null) {
+
ArrayList<NetworkPresence> statusesOnNetworks = user2Update.getPayload();
if (!statusesOnNetworks.isEmpty()) {
ContentValues values = new ContentValues();
StringBuffer where = null;
- for (NetworkPresence status : statusesOnNetworks) {
- values.put(Field.LOCAL_CONTACT_ID.toString(), user2Update.getLocalContactId());
- values.put(Field.USER_ID.toString(), status.getUserId());
- values.put(Field.NETWORK_ID.toString(), status.getNetworkId());
- values.put(Field.NETWORK_STATUS.toString(), status.getOnlineStatusId());
+ Iterator<NetworkPresence> itr = statusesOnNetworks.iterator();
+ NetworkPresence status = null;
+ while (itr.hasNext()) {
+ status = itr.next();
+ if (ignoredNetworkIds == null || !ignoredNetworkIds.contains(status.getNetworkId())) {
+ values.put(Field.LOCAL_CONTACT_ID.toString(), user2Update.getLocalContactId());
+ values.put(Field.USER_ID.toString(), status.getUserId());
+ values.put(Field.NETWORK_ID.toString(), status.getNetworkId());
+ values.put(Field.NETWORK_STATUS.toString(), status.getOnlineStatusId());
- where = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString());
-
- where.append(SQLKeys.EQUALS).append(user2Update.getLocalContactId()).
- append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(status.getNetworkId());
-
- int numberOfAffectedRows = writableDatabase.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where),
- null);
- if (numberOfAffectedRows == 0) {
- if (writableDatabase.insert(TABLE_NAME, null, values) != -1) {
- ret = USER_ADDED;
+ where = StringBufferPool.getStringBuffer(Field.LOCAL_CONTACT_ID.toString());
+
+ where.append(SQLKeys.EQUALS).append(user2Update.getLocalContactId()).
+ append(SQLKeys.AND).append(Field.NETWORK_ID).append(SQLKeys.EQUALS).append(status.getNetworkId());
+
+ int numberOfAffectedRows = writableDatabase.update(TABLE_NAME, values, StringBufferPool.toStringThenRelease(where),
+ null);
+ if (numberOfAffectedRows == 0) {
+ if (writableDatabase.insert(TABLE_NAME, null, values) != -1) {
+ ret = USER_ADDED;
+ } else {
+ LogUtils.logE("PresenceTable updateUser(): could not add new user!");
+ }
} else {
- LogUtils.logE("PresenceTable updateUser(): could not add new user!");
- }
- } else {
- if (ret == USER_NOTADDED) {
- ret = USER_UPDATED;
+ if (ret == USER_NOTADDED) {
+ ret = USER_UPDATED;
+ }
}
+ values.clear();
+ } else if (ignoredNetworkIds != null) { // presence information from this network needs to be ignored
+ itr.remove();
}
- values.clear();
}
}
}
return ret;
}
/**
+ * This method fills the provided user object with presence information.
+ *
+ * @param user User - the user with a localContactId != -1
+ * @param readableDatabase - the database to read from
+ * @return user/me profile presence state wrapped in "User" wrapper class,
+ * or NULL if the specified localContactId doesn't exist
+ * @throws SQLException if the database layer throws this exception.
+ * @throws NullPointerException if the passed in database instance is null.
+ */
+ public static void getUserPresence(User user,
+ SQLiteDatabase readableDatabase) throws SQLException, NullPointerException {
+ if (readableDatabase == null) {
+ throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
+ }
+ if (user.getLocalContactId() < 0) {
+ LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): "
+ + "#localContactId# parameter is -1 ");
+ return;
+ }
+ Cursor c = null;
+ try {
+ c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE "
+ + Field.LOCAL_CONTACT_ID + "=" + user.getLocalContactId(), null);
+
+ int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0
+
+ user.getPayload().clear();
+
+ while (c.moveToNext()) {
+ String userId = c.getString(USER_ID);
+ int networkId = c.getInt(NETWORK_ID);
+ int statusId = c.getInt(NETWORK_STATUS);
+ if (statusId > onlineStatus) {
+ onlineStatus = statusId;
+ }
+ user.getPayload().add(new NetworkPresence(userId, networkId, statusId));
+ }
+ user.setOverallOnline(onlineStatus);
+ } finally {
+ CloseUtils.close(c);
+ c = null;
+ }
+ }
+
+ /**
* This method returns user/me profile presence state.
*
* @param localContactId - me profile localContactId
* @param readableDatabase - the database to read from
* @return user/me profile presence state wrapped in "User" wrapper class,
* or NULL if the specified localContactId doesn't exist
* @throws SQLException if the database layer throws this exception.
* @throws NullPointerException if the passed in database instance is null.
+ * @return user - User object filled with presence information.
*/
public static User getUserPresenceByLocalContactId(long localContactId,
SQLiteDatabase readableDatabase) throws SQLException, NullPointerException {
if (readableDatabase == null) {
throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
}
User user = null;
if (localContactId < 0) {
LogUtils.logE("PresenceTable.getUserPresenceByLocalContactId(): "
+ "#localContactId# parameter is -1 ");
return user;
}
Cursor c = null;
try {
c = readableDatabase.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE "
+ Field.LOCAL_CONTACT_ID + "=" + localContactId, null);
ArrayList<NetworkPresence> networkPresence = new ArrayList<NetworkPresence>();
user = new User();
int onlineStatus = OnlineStatus.OFFLINE.ordinal(); // i.e. 0
while (c.moveToNext()) {
user.setLocalContactId(c.getLong(LOCAL_CONTACT_ID));
String userId = c.getString(USER_ID);
int networkId = c.getInt(NETWORK_ID);
int statusId = c.getInt(NETWORK_STATUS);
if (statusId > onlineStatus) {
onlineStatus = statusId;
}
networkPresence.add(new NetworkPresence(userId, networkId, statusId));
}
if (!networkPresence.isEmpty()) {
user.setOverallOnline(onlineStatus);
user.setPayload(networkPresence);
}
- // this finally part should always run, while the exception is still
- // thrown
} finally {
CloseUtils.close(c);
c = null;
}
return user;
}
/**
* The method cleans the presence table: deletes all the rows.
*
* @param writableDatabase - database to write to.
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise.
* @throws NullPointerException if the passed in database instance is null.
*/
public static int setAllUsersOffline(SQLiteDatabase writableDatabase)
throws NullPointerException {
if (writableDatabase == null) {
throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
}
// To remove all rows and get a count pass "1" as the whereClause
return writableDatabase.delete(TABLE_NAME, "1", null);
}
-
+
+
/**
* The method cleans the presence table: deletes all the rows, except for
* the given user localContactId ("Me Profile" localContactId)
*
* @param localContactIdOfMe - the localContactId of the user (long), whose
* info should not be deleted
* @param writableDatabase - database to write to.
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise.
* @throws NullPointerException if the passed in database instance is null.
*/
public static int setAllUsersOfflineExceptForMe(long localContactIdOfMe,
SQLiteDatabase writableDatabase) throws NullPointerException {
if (writableDatabase == null) {
throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
}
return writableDatabase.delete(TABLE_NAME, Field.LOCAL_CONTACT_ID + " != "
+ localContactIdOfMe, null);
}
+
+ /**
+ * This method returns the array of distinct user local contact ids in this table.
+ * @param readableDatabase - database.
+ * @return ArrayList of Long distinct local contact ids from this table.
+ */
+ public static ArrayList<Long> getLocalContactIds(SQLiteDatabase readableDatabase) {
+ Cursor c = null;
+ ArrayList<Long> ids = new ArrayList<Long>();
+ c = readableDatabase.rawQuery("SELECT DISTINCT " +Field.LOCAL_CONTACT_ID+ " FROM " + TABLE_NAME, null);
+ try {
+ while (c.moveToNext()) {
+ ids.add(c.getLong(0));
+ }
+ } finally {
+ c.close();
+ c = null;
+ }
+ return ids;
+ }
+ /**
+ * This method deletes information about the user presence states on the provided networks.
+ * @param networksToDelete - ArrayList of integer network ids.
+ * @param writableDatabase - writable database.
+ * @throws NullPointerException is thrown when the provided database is null.
+ */
+ public static void setTPCNetworksOffline(ArrayList<Integer> networksToDelete,
+ SQLiteDatabase writableDatabase) throws NullPointerException {
+ if (writableDatabase == null) {
+ throw new NullPointerException(DEFAULT_ERROR_MESSAGE);
+ }
+ StringBuffer networks = StringBufferPool.getStringBuffer();
+ final String COMMA = ",";
+ for (Integer network : networksToDelete) {
+ networks.append(network).append(COMMA);
+ }
+ if (networks.length() > 0) {
+ networks.deleteCharAt(networks.lastIndexOf(COMMA));
+ }
+ StringBuilder where = new StringBuilder(Field.NETWORK_ID.toString());
+ where.append(" IN (").append(StringBufferPool.toStringThenRelease(networks)).append(")");
+
+ writableDatabase.delete(TABLE_NAME, where.toString(), null);
+ }
}
diff --git a/src/com/vodafone360/people/datatypes/SystemNotification.java b/src/com/vodafone360/people/datatypes/SystemNotification.java
index 6b60832..db28b4d 100644
--- a/src/com/vodafone360/people/datatypes/SystemNotification.java
+++ b/src/com/vodafone360/people/datatypes/SystemNotification.java
@@ -1,316 +1,325 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.datatypes;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import com.vodafone360.people.engine.EngineManager.EngineId;
import com.vodafone360.people.utils.LogUtils;
/**
* BaseDataType encapsulating a System notification message received from server
* This message contains a code and error test and should be routed to the
* approproate engine(s).
*/
public class SystemNotification extends PushEvent {
/**
* <String> "code" / <String> message code <String> "message" / <String>
* message to the user Note: Currently not in scope but should be discussed,
* system notifications would provide system messages, error conditions, etc
*/
/**
* Enumeration of System Notification codes that can be returned from
* Server.
*/
public enum SysNotificationCode {
AUTH_INVALID("101"),
COMMUNITY_AUTH_INVALID("102"),
COMMUNITY_AUTH_VALID("103"),
COMMUNITY_LOGOUT_FAILED("110"),
COMMUNITY_LOGOUT_SUCCESSFUL("111"),
COMMUNITY_NETWORK_LOGOUT("112"),
SEND_MESSAGE_FAILED("201"),
GENERIC("1000"),
UNKNOWN("1001"),
UNKNOWN_USER("1002"),
FRIENDS_LIST_NULL("1003"),
UNKNOWN_EVENT("1004"),
UNKNOWN_MESSAGE_TYPE("1005"),
CONVERSATION_NULL("1006"),
SEND_MESSAGE_PARAMS_INVALID("1007"),
SET_AVAILABILITY_PARAMS_INVALID("1008"),
TOS_NULL("1009"),
SMS_WAKEUP_FAILED("1010"),
SMS_FAILED("1011"),
UNKNOWN_CHANNEL("1012"),
INVITATIONS_ACCEPT_ERROR("1013"),
INVITATIONS_DENY_ERROR("1014"),
CONTACTS_UPDATE_FAILED("1015"),
MOBILE_REQUEST_PAYLOAD_PARSE_ERROR("1101"),
EXTERNAL_HTTP_ERROR("1102"),
MOBILE_EXTERNAL_PROXY("1103"),
MOBILE_INTERNAL_PROXY("1104"),
CHAT_HISTORY_NULL("1900"),
CHAT_SUMMARY_NULL("1901");
private final String tag;
/**
* Constructor creating SysNotificationCode item for specified String.
*
* @param s String value for Tags item.
*/
private SysNotificationCode(String s) {
tag = s;
}
/**
* String value associated with SysNotificationCode item.
*
* @return String value for SysNotificationCode item.
*/
private String tag() {
return tag;
}
/**
* Find SysNotificationCode item for specified String.
*
* @param tag String value to find Tags item for.
* @return SysNotificationCode item for specified String, null
* otherwise.
*/
private static SysNotificationCode findTag(String tag) {
for (SysNotificationCode tags : SysNotificationCode.values()) {
if (tag.compareTo(tags.tag()) == 0) {
return tags;
}
}
return null;
}
}
/**
* Tags associated with SystemNotification item.
*/
public enum Tags {
/**
* The type ofthe notification.
*/
CODE("code"),
/**
* The message in the notification.
*/
MESSAGE("message"),
/**
* The message recipients address (for messages 201, 1006)
*/
TOS("tos"),
/**
* The message conversation id (for messages 201, 1006)
*/
- CONVERSATION("conversation");
+ CONVERSATION("conversation"),
+ /**
+ * service name (for messages 111)
+ */
+ SERVICE("service");
+
private final String tag;
/**
* String value associated with Tags item.
*
* @return String value for Tags item.
*/
private Tags(String s) {
tag = s;
}
/**
* String value associated with Tags item.
*
* @return String value for Tags item.
*/
private String tag() {
return tag;
}
/**
* Find Tags item for specified String
*
* @param tag String value to find Tags item for
* @return Tags item for specified String, null otherwise
*/
private static Tags findTag(String tag) {
for (Tags tags : Tags.values()) {
if (tag.compareTo(tags.tag()) == 0) {
return tags;
}
}
return null;
}
}
private String code = null;
private String message = null;
/**
* The hash of optional data, can be empty.
*/
private Hashtable<String, String> info = new Hashtable<String, String>();
private SysNotificationCode mSysCode;
/** {@inheritDoc} */
@Override
public String name() {
return "SystemNotification";
}
/**
* Create SystemNotification message from hashtable generated by
* Hessian-decoder.
*
* @param hash Hashtable containing SystemNotification parameters.
* @param engId ID for engine this message should be routed to.
* @return SystemNotification created from hashtable.
*/
static public SystemNotification createFromHashtable(Hashtable<String, Object> hash,
EngineId engId) {
SystemNotification sn = new SystemNotification();
sn.mEngineId = engId;
Enumeration<String> e = hash.keys();
while (e.hasMoreElements()) {
String key = e.nextElement();
Object value = hash.get(key);
Tags tag = Tags.findTag(key);
sn.setValue(tag, value);
}
sn.setEngine();
return sn;
}
/**
* Sets the value of the member data item associated with the specified tag.
*
* @param tag Current tag
* @param val Value associated with the tag
*/
private void setValue(Tags tag, Object value) {
if (tag == null)
return;
switch (tag) {
case CODE:
code = (String)value;
mSysCode = SysNotificationCode.findTag((String)value);
break;
case MESSAGE:
message = (String)value;
break;
case TOS:
info.put(Tags.TOS.toString(), ((Vector<String>)value).firstElement());
break;
case CONVERSATION:
info.put(Tags.CONVERSATION.toString(), (String)value);
break;
+ case SERVICE:
+ info.put(Tags.SERVICE.toString(), (String)value);
+ break;
default:
// Do nothing.
break;
}
}
/**
* Set EngineId of Engine that needs to handle the System Notification.
*/
private void setEngine() {
if (mSysCode != null) {
switch (mSysCode) {
case SEND_MESSAGE_FAILED:
case CONVERSATION_NULL:
case SEND_MESSAGE_PARAMS_INVALID:
case SET_AVAILABILITY_PARAMS_INVALID:
case TOS_NULL:
case CHAT_HISTORY_NULL:
case CHAT_SUMMARY_NULL:
case COMMUNITY_AUTH_VALID:
+ case COMMUNITY_LOGOUT_SUCCESSFUL:
mEngineId = EngineId.PRESENCE_ENGINE;
LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message);
break;
case EXTERNAL_HTTP_ERROR:
// This error can come for thumbnail download. As of now the
// download is being done in ContactSyncEngine for MeProfile
// and in the Content Engine for other normal contacts.
// Hence as of here this engine ID would be undefined. But
// in the run() of the decoder thread, we assign the engine
// ID based on the request ID.
// mEngineId = EngineId.CONTACT_SYNC_ENGINE;
LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message);
break;
case UNKNOWN_EVENT:
case UNKNOWN_MESSAGE_TYPE:
case GENERIC:
case UNKNOWN:
LogUtils.logE("SYSTEM_NOTIFICATION:" + mSysCode + ", message:" + message);
break;
default:
LogUtils.logE("SYSTEM_NOTIFICATION UNHANDLED:" + code + ", message:" + message);
}
} else {
LogUtils.logE("UNEXPECTED UNHANDLED SYSTEM_NOTIFICATION:" + code + ", message:"
+ message);
}
}
/**
* Get current System Notification code.
*
* @return current System Notification code.
*/
public SysNotificationCode getSysCode() {
return mSysCode;
}
/** {@inheritDoc} */
@Override
public String toString() {
return "SystemNotification [code=" + code + ", mSysCode=" + mSysCode + ", message="
+ message + "]";
}
/**
* This method returns hash of optional parameters coming with this message.
* @return hash Hashtable<String, String> - hash of optional parameters.
*/
public Hashtable<String, String> getInfo() {
return info;
}
}
diff --git a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java
index f360b2f..49cae52 100644
--- a/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java
+++ b/src/com/vodafone360/people/engine/presence/PresenceDbUtils.java
@@ -1,269 +1,323 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.presence;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.database.tables.PresenceTable;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
import com.vodafone360.people.engine.meprofile.SyncMeDbUtils;
import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.service.agent.UiAgent;
+import com.vodafone360.people.utils.HardcodedUtils;
import com.vodafone360.people.utils.LogUtils;
public class PresenceDbUtils {
/**
* the user id of the me profile contact
*/
private static long sMeProfileUserId = -1L;
/**
* the local contact id of the me profile contact
*/
private static long sMeProfileLocalContactId = -1L;
public static void resetMeProfileIds() {
sMeProfileUserId = -1L;
sMeProfileLocalContactId = -1L;
}
-
+
/**
- * Parses user data before storing it to database
- *
- * @param user
- * @param databaseHelper
- * @return
+ * This method returns true if the provided user id matches the one of me profile.
+ * @return TRUE if the provided user id matches the one of me profile.
*/
- private static boolean convertUserIds(User user, DatabaseHelper databaseHelper) {
- if (!user.getPayload().isEmpty()) {
- long localContactId = -1;
- ArrayList<NetworkPresence> payload = user.getPayload();
- boolean resetOverallPresenceStatus = false;
- String userId = null;
- for (NetworkPresence presence : payload) {
- userId = presence.getUserId();
- if (notNullOrBlank(userId)) {
- int networkId = presence.getNetworkId();
- if (userId.equals(String.valueOf(getMeProfileUserId(databaseHelper)))) {
- localContactId = sMeProfileLocalContactId;
- // remove the PC presence
- if (networkId == SocialNetwork.PC.ordinal()) {
- user.getPayload().remove(presence);
- resetOverallPresenceStatus = true;
- break;
- }
- } else {
- if (networkId == SocialNetwork.MOBILE.ordinal()
- || (networkId == SocialNetwork.PC.ordinal())) {
- localContactId = ContactsTable.fetchLocalIdFromUserId(Long
- .valueOf(userId), databaseHelper.getReadableDatabase());
- } else {
- localContactId = ContactDetailsTable.findLocalContactIdByKey(
- SocialNetwork.getPresenceValue(networkId).toString(), userId,
- ContactDetail.DetailKeys.VCARD_IMADDRESS, databaseHelper
- .getReadableDatabase());
- }
- if (localContactId != UiAgent.ALL_USERS) {
- break;
- }
- }
- }
- }
- if (resetOverallPresenceStatus) {
- int max = OnlineStatus.OFFLINE.ordinal();
- for (NetworkPresence presence : user.getPayload()) {
- if (presence.getOnlineStatusId() > max)
- max = presence.getOnlineStatusId();
- }
- user.setOverallOnline(max);
- }
- user.setLocalContactId(localContactId);
- return true;
- }
- LogUtils.logE("presence data can't be parsed!!");
- return false;
+ private static boolean isMeProfile(String userId, DatabaseHelper databaseHelper) {
+ return userId.equals(String.valueOf(getMeProfileUserId(databaseHelper)));
}
-
+
/**
* @param databaseHelper
* @return
*/
protected static Long getMeProfileUserId(DatabaseHelper databaseHelper) {
if (sMeProfileUserId == -1L) {
Contact meProfile = new Contact();
if (SyncMeDbUtils.fetchMeProfile(databaseHelper, meProfile) != ServiceStatus.ERROR_NOT_FOUND) {
sMeProfileUserId = meProfile.userID;
sMeProfileLocalContactId = meProfile.localContactID;
}
}
return sMeProfileUserId;
}
/**
* @param databaseHelper
* @return
*/
protected static User getMeProfilePresenceStatus(DatabaseHelper databaseHelper) {
// if
// (!sMeProfileLocalContactId.equals(databaseHelper.getMeProfileId())) {
Long meProfileId = SyncMeDbUtils.getMeProfileLocalContactId(databaseHelper);
sMeProfileLocalContactId = (meProfileId == null || meProfileId.intValue() == -1) ? -1
: meProfileId;
// LogUtils.logE("The DB Helper and Utils IDs are not synchronized");
// }
User user = PresenceTable.getUserPresenceByLocalContactId(
getMeProfileUserId(databaseHelper), databaseHelper.getWritableDatabase());
if (user == null || (user.getPayload() == null)) { // the table is
// empty, need to set
// the status for the
// 1st time
// TODO: this hard code needs change, must filter the identities
// info by VCARD.IMADRESS
Hashtable<String, String> status = new Hashtable<String, String>();
status.put("google", "online");
status.put("microsoft", "online");
status.put("mobile", "online");
status.put("facebook.com", "online");
status.put("hyves.nl", "online");
user = new User(String.valueOf(getMeProfileUserId(databaseHelper)), status);
}
return user;
}
/**
* This method returns wrapper with the presence information for all user
* networks
*
* @param localContactId - the localContactId of the contact we want to get
* presence states information for.
* @param databaseHelper
* @return User wrapper with the presence information for all user networks.
* If no information is on the database the payload is NULL
*/
public static User getUserPresenceStatusByLocalContactId(long localContactId,
DatabaseHelper databaseHelper) {
User user = PresenceTable.getUserPresenceByLocalContactId(localContactId, databaseHelper
.getWritableDatabase());
LogUtils.logW("UI called getUserPresenceStatusByLocalContactId: " + user);
return user;
}
/**
* Here we update the PresenceTable, and the ContactSummaryTable afterwards
* the HandlerAgent receives the notification of presence states changes.
*
* @param users List<User> - the list of user presence states
* @param users idListeningTo long - local contact id which this UI is watching, -1 is all contacts
* @param dbHelper DatabaseHelper - the database.
- *
+ * @return TRUE if database has changed in result of the modifications.
*/
protected static boolean updateDatabase(List<User> users, long idListeningTo,
DatabaseHelper dbHelper) {
- boolean contactsChanged = false;
- for (User user : users) {
- if (convertUserIds(user, dbHelper)) {
- SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
+ boolean presenceChanged = false;
+ boolean deleteNetworks = false;
+
+ // the list of networks presence information for me we ignore - the networks where user is offline.
+ ArrayList<Integer> ignoredNetworks = new ArrayList<Integer>();
- int status = PresenceTable.updateUser(user, writableDb);
- if (PresenceTable.USER_NOTADDED != status) {
- user = PresenceTable.getUserPresenceByLocalContactId(user.getLocalContactId(), writableDb);
- if (user != null) {
- ContactSummaryTable.updateOnlineStatus(user);
- if (user.getLocalContactId() == idListeningTo) {
- contactsChanged = true;
+ for (User user : users) {
+ if (!user.getPayload().isEmpty()) {
+ long localContactId = -1;
+ ArrayList<NetworkPresence> payload = user.getPayload();
+ // if it is the me profile User
+ boolean meProfile = false;
+ String userId = null;
+ for (NetworkPresence presence : payload) {
+ userId = presence.getUserId();
+ if (notNullOrBlank(userId)) {
+ int networkId = presence.getNetworkId();
+ // if this is me profile contact
+ if (isMeProfile(userId, dbHelper)) {
+ localContactId = sMeProfileLocalContactId;
+ meProfile = true;
+ // remove the PC presence, as we don't display it in me profile
+ if (networkId == SocialNetwork.PC.ordinal()) {
+ presenceChanged = true;
+ }
+
+ } // 360 contact, PC or MOBILE network
+ else if (networkId == SocialNetwork.PC.ordinal() || networkId == SocialNetwork.MOBILE.ordinal()) {
+ localContactId = ContactsTable.fetchLocalIdFromUserId(Long
+ .valueOf(userId), dbHelper.getReadableDatabase());
+ if (localContactId != -1) {
+ break;
+ }
+ } else { // 3rd party accounts
+ localContactId = ContactDetailsTable.findLocalContactIdByKey(
+ SocialNetwork.getPresenceValue(networkId).toString(), userId,
+ ContactDetail.DetailKeys.VCARD_IMADDRESS, dbHelper
+ .getReadableDatabase());
+ if (localContactId != -1) {
+ break;
+ }
}
- } else {
- LogUtils.logE("PresenceDbUtils.updateDatabase(): USER WAS NOT FOUND");
}
- } else {
- LogUtils.logE("PresenceDbUtils.updateDatabase(): USER WAS NOT ADDED");
}
- }
+ // set the local contact id
+ user.setLocalContactId(localContactId);
+
+ if (meProfile) {
+ if (deleteNetworks = processMeProfile(presenceChanged, user, ignoredNetworks)) {
+// delete the information about offline networks from PresenceTable
+ PresenceTable.setTPCNetworksOffline(ignoredNetworks, dbHelper.getWritableDatabase());
+ }
+ }
+ if (user.getLocalContactId() > -1) {
+ SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
+
+// write the user presence update into the database and read the complete wrapper
+ PresenceTable.updateUser(user, ignoredNetworks, writableDb);
+ PresenceTable.getUserPresence(user, writableDb);
+
+// update the user aggregated presence state in the ContactSummaryTable
+ ContactSummaryTable.updateOnlineStatus(user);
+
+ if (user.getLocalContactId() == idListeningTo) {
+ presenceChanged = true;
+ }
+ }
+ }
+ }
+ // if contact summary table needs extra refresh, to make sure no statuses are displayed for offline TPC networks users
+ if (deleteNetworks) {
+ ArrayList<Long> userIds = PresenceTable.getLocalContactIds(dbHelper.getWritableDatabase());
+ ContactSummaryTable.setUsersOffline(userIds);
+ presenceChanged = true;
}
+
if (idListeningTo == UiAgent.ALL_USERS) {
- contactsChanged = true;
+ presenceChanged = true;
}
- return contactsChanged;
+ return presenceChanged;
}
+ /**
+ * This method alter the User wrapper fro me profile, and returns true if me profile information contains the ignored TPC networks information.
+ * Based on the result this information may be deleted.
+ * @param removePCPresence - if TRUE the PC network will be removed from the network list.
+ * @param user - the me profile wrapper.
+ * @param ignoredNetworks - the list if ignored integer network ids.
+ * @return
+ */
+ private static boolean processMeProfile(boolean removePCPresence, User user, ArrayList<Integer> ignoredNetworks){
+ if (removePCPresence) {
+ user.removeNetwork(SocialNetwork.PC.ordinal());
+ int max = OnlineStatus.OFFLINE.ordinal();
+ // calculate the new aggregated presence status
+ for (NetworkPresence presence : user.getPayload()) {
+ if (presence.getOnlineStatusId() > max) {
+ max = presence.getOnlineStatusId();
+ }
+ }
+ user.setOverallOnline(max);
+ }
+ // the list of chat network ids in this User wrapper
+ ArrayList<Integer> userNetworks = new ArrayList<Integer>();
+
+ ArrayList<NetworkPresence> payload = user.getPayload();
+
+ for (NetworkPresence presence : payload) {
+ int networkId = presence.getNetworkId();
+ userNetworks.add(networkId);
+ // 1. ignore offline TPC networks
+ if (presence.getOnlineStatusId() == OnlineStatus.OFFLINE.ordinal()) {
+ ignoredNetworks.add(networkId);
+ }
+ }
+ // 2. ignore the TPC networks presence state for which is unknown
+ for (int networkId : HardcodedUtils.THIRD_PARTY_CHAT_ACCOUNTS) {
+ if (!userNetworks.contains(networkId)) {
+ ignoredNetworks.add(networkId);
+ }
+ }
+
+ if (!ignoredNetworks.isEmpty()) {
+ return true;
+ }
+ return false;
+ }
+
+
protected static boolean updateMyPresence(User user, DatabaseHelper dbHelper) {
boolean contactsChanged = false;
SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
- if (PresenceTable.updateUser(user, writableDb) != PresenceTable.USER_NOTADDED) {
+ if (PresenceTable.updateUser(user, null, writableDb) != PresenceTable.USER_NOTADDED) {
contactsChanged = (ContactSummaryTable.updateOnlineStatus(user) == ServiceStatus.SUCCESS);
}
return contactsChanged;
}
/**
* Set all users to offline state
*
* @param dbHelper
*/
protected static void setPresenceOfflineInDatabase(DatabaseHelper dbHelper) {
SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
PresenceTable.setAllUsersOffline(writableDatabase);
ContactSummaryTable.setOfflineStatus();
}
/**
* Removes all presence infos besides those related to MeProfile
*
* @param dbHelper
*/
protected static void resetPresenceStatesAcceptForMe(long localContactIdOfMe,
DatabaseHelper dbHelper) {
SQLiteDatabase writableDb = dbHelper.getWritableDatabase();
if (writableDb != null) {
LogUtils.logW(" PresenceDBUtils.resetPresenceStatesAcceptForMe: "
+ "#rows affected by delete method "
+ PresenceTable.setAllUsersOfflineExceptForMe(localContactIdOfMe, writableDb));
ContactSummaryTable.setOfflineStatusExceptForMe(localContactIdOfMe);
}
}
/**
* @param input
* @return
*/
public static boolean notNullOrBlank(String input) {
return (input != null) && input.length() > 0;
}
}
diff --git a/src/com/vodafone360/people/engine/presence/PresenceEngine.java b/src/com/vodafone360/people/engine/presence/PresenceEngine.java
index 6f0edcf..a0d7714 100644
--- a/src/com/vodafone360/people/engine/presence/PresenceEngine.java
+++ b/src/com/vodafone360/people/engine/presence/PresenceEngine.java
@@ -1,819 +1,823 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.presence;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.tables.ActivitiesTable.TimelineSummaryItem;
import com.vodafone360.people.datatypes.BaseDataType;
import com.vodafone360.people.datatypes.ChatMessage;
import com.vodafone360.people.datatypes.Conversation;
import com.vodafone360.people.datatypes.PresenceList;
import com.vodafone360.people.datatypes.PushAvailabilityEvent;
import com.vodafone360.people.datatypes.PushChatMessageEvent;
import com.vodafone360.people.datatypes.PushClosedConversationEvent;
import com.vodafone360.people.datatypes.PushEvent;
import com.vodafone360.people.datatypes.ServerError;
import com.vodafone360.people.datatypes.SystemNotification;
import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
import com.vodafone360.people.datatypes.SystemNotification.Tags;
import com.vodafone360.people.engine.BaseEngine;
import com.vodafone360.people.engine.EngineManager;
import com.vodafone360.people.engine.EngineManager.EngineId;
import com.vodafone360.people.engine.contactsync.ContactSyncEngine.IContactSyncObserver;
import com.vodafone360.people.engine.contactsync.ContactSyncEngine.Mode;
import com.vodafone360.people.engine.contactsync.ContactSyncEngine.State;
import com.vodafone360.people.engine.login.LoginEngine.ILoginEventsListener;
import com.vodafone360.people.engine.meprofile.SyncMeDbUtils;
import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.service.ServiceUiRequest;
import com.vodafone360.people.service.agent.UiAgent;
import com.vodafone360.people.service.io.ResponseQueue.Response;
import com.vodafone360.people.service.io.api.Chat;
import com.vodafone360.people.service.io.api.Presence;
import com.vodafone360.people.service.transport.ConnectionManager;
import com.vodafone360.people.service.transport.tcp.ITcpConnectionListener;
import com.vodafone360.people.utils.LogUtils;
/**
* Handles the Presence life cycle
*/
public class PresenceEngine extends BaseEngine implements ILoginEventsListener,
IContactSyncObserver, ITcpConnectionListener {
/** Check every 10 minutes. **/
private final static long CHECK_FREQUENCY = 24 * 60 * 60 * 1000;
/** Max attempts to try. **/
- private final static int MAX_RETRY_COUNT = 3;
+// private final static int MAX_RETRY_COUNT = 3;
/** Reconnecting before firing offline state to the handlers. **/
private boolean mLoggedIn = false;
private long mNextRuntime = -1;
// private AgentState mNetworkAgentState = AgentState.CONNECTED;
private DatabaseHelper mDbHelper;
private int mRetryNumber;
private final Hashtable<String, ChatMessage> mSendMessagesHash; // (to, message)
private List<TimelineSummaryItem> mFailedMessagesList; // (to, network)
private boolean mContObsAdded;
/** The list of Users still to be processed. **/
private List<User> mUsers = null;
/**
* This state indicates there are no more pending presence payload
* information to be processed.
**/
private static final int IDLE = 0;
/**
* This state indicates there are some pending presence payload information
* to be processed.
**/
private static final int UPDATE_PROCESSING_GOING_ON = 1;
/** Timeout between each presence update processing. **/
private static final long UPDATE_PRESENCE_TIMEOUT_MILLS = 0;
/** The page size i.e the number of presence updates processed at a time. **/
private static final int UPDATE_PRESENCE_PAGE_SIZE = 10;
/** The number of pages after which the HandlerAgent is notified. **/
private static final int NOTIFY_AGENT_PAGE_INTERVAL = 5;
/** The state of the presence Engine. **/
private int mState = IDLE;
/**
* Number of pages of presence Updates done. This is used to control when a
* notification is sent to the UI.
**/
private int mIterations = 0;
/**
*
* @param eventCallback
* @param databaseHelper
*/
public PresenceEngine(IEngineEventCallback eventCallback, DatabaseHelper databaseHelper) {
super(eventCallback);
mEngineId = EngineId.PRESENCE_ENGINE;
mDbHelper = databaseHelper;
mSendMessagesHash = new Hashtable<String, ChatMessage>();
mFailedMessagesList = new ArrayList<TimelineSummaryItem>();
addAsContactSyncObserver();
}
@Override
public void onCreate() {
}
@Override
public void onDestroy() {
if (mDbHelper != null && SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper) != null) {
PresenceDbUtils.resetPresenceStatesAcceptForMe(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper),
mDbHelper);
}
EngineManager.getInstance().getLoginEngine().removeListener(this);
}
/**
* checks the external conditions which have to be happen before the engine
* can run
*
* @return true if everything is ready
*/
private boolean canRun() {
return EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete() &&
EngineManager.getInstance().getContactSyncEngine().isFirstTimeSyncComplete();
}
@Override
public long getNextRunTime() {
if (!mContObsAdded) {
addAsContactSyncObserver();
}
if (!canRun()) {
mNextRuntime = -1;
LogUtils.logV("PresenceEngine.getNextRunTime(): 1st contact sync is not finished:"
+ mNextRuntime);
return mNextRuntime;
}
if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED || !mLoggedIn) {
return -1;
}
/**
* need isUiRequestOutstanding() because currently the worker thread is
* running and finishing before PresenceEngine.setNextRuntime is called
*/
if (isCommsResponseOutstanding() || isUiRequestOutstanding()) {
LogUtils.logV("PresenceEngine getNextRunTime() comms response outstanding");
return 0;
}
if (mNextRuntime == -1) {
LogUtils.logV("PresenceEngine getNextRunTime() Run PresenceEngine for the first time!");
return 0;
} else {
return mNextRuntime;
}
}
@Override
public void run() {
LogUtils.logV("PresenceEngine.run() isCommsResponseOutstanding["
+ isCommsResponseOutstanding() + "] mLoggedIn[" + mLoggedIn + "] mNextRuntime["
+ mNextRuntime + "]");
if (isCommsResponseOutstanding() && processCommsInQueue()) {
LogUtils.logV("PresenceEngine.run() handled processCommsInQueue()");
return;
}
if (processTimeout()) {
LogUtils.logV("PresenceEngine.run() handled processTimeout()");
return;
}
if (ConnectionManager.getInstance().getConnectionState() == STATE_CONNECTED) {
if (mLoggedIn && (mNextRuntime <= System.currentTimeMillis())) {
if (canRun()) {
getPresenceList();
initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase());
// Request to update the UI
setNextRuntime();
} else { // check after 30 seconds
LogUtils.logE("Can't run PresenceEngine before the contact"
+ " list is downloaded:3 - set next runtime in 30 seconds");
mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY / 20;
}
}
} else {
LogUtils.logV("PresenceEngine.run(): AgentState.DISCONNECTED");
setPresenceOffline();
}
/**
* and the getNextRunTime must check the uiRequestReady() function and
* return 0 if it is true
*/
if (uiRequestReady() && processUiQueue()) {
return;
}
}
/**
* Helper function which returns true if a UI request is waiting on the
* queue and we are ready to process it.
*
* @return true if the request can be processed now.
*/
private boolean uiRequestReady() {
return isUiRequestOutstanding();
}
private User getMyAvailabilityStatusFromDatabase() {
return PresenceDbUtils.getMeProfilePresenceStatus(mDbHelper);
}
private void setNextRuntime() {
LogUtils.logV("PresenceEngine.setNextRuntime() Run again in ["
+ (CHECK_FREQUENCY / (1000 * 60)) + "] minutes");
mNextRuntime = System.currentTimeMillis() + CHECK_FREQUENCY;
}
private void setRunNow() {
LogUtils.logV("PresenceEngine.setNextRuntime() Run again NOW");
mNextRuntime = 0;
}
@Override
public void onLoginStateChanged(boolean loggedIn) {
LogUtils.logI("PresenceEngine.onLoginStateChanged() loggedIn[" + loggedIn + "]");
mLoggedIn = loggedIn;
if (mLoggedIn) {
initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase());
setNextRuntime();
} else {
setPresenceOffline();
mContObsAdded = false;
mRetryNumber = 0;
mFailedMessagesList.clear();
mSendMessagesHash.clear();
}
}
/***
* Set the Global presence status to offline.
*/
private synchronized void setPresenceOffline() {
PresenceDbUtils.setPresenceOfflineInDatabase(mDbHelper);
// We clear the mUsers of any pending presence updates because this
// Offline presence update request should take the highest priority.
mUsers = null;
mState = IDLE;
mEventCallback.getUiAgent().updatePresence(-1);
}
@Override
protected void onRequestComplete() {
LogUtils.logI("PresenceEngine.onRequestComplete()");
}
@Override
protected void onTimeoutEvent() {
LogUtils.logI("PresenceEngine.onTimeoutEvent()");
switch (mState) {
case UPDATE_PROCESSING_GOING_ON:
updatePresenceDatabaseNextPage();
break;
case IDLE:
default:
setRunNow();
}
}
@Override
protected void processCommsResponse(Response resp) {
handleServerResponse(resp.mDataTypes);
}
private void showErrorNotification(ServiceUiRequest errorEvent, ChatMessage msg) {
UiAgent uiAgent = mEventCallback.getUiAgent();
if (uiAgent != null && uiAgent.isSubscribedWithChat()) {
uiAgent.sendUnsolicitedUiEvent(errorEvent, null);
}
}
/**
* Here we update the PresenceTable, and the ContactSummaryTable afterwards
* the HandlerAgent receives the notification of presence states changes.
*
* @param users List of users that require updating.
*/
private synchronized void updatePresenceDatabase(List<User> users) {
if (users == null || users.size() == 0) {
LogUtils.logW("PresenceEngine.updatePresenceDatabase() users is NULL or zero size");
} else {
if (mUsers == null) {
mUsers = users;
} else {
// Doing an add one by one is not an efficient way but then
// there is an issue in the addAll API. It crashes sometimes.
// And the java code for the AddAll API seems to be erroneous.
// More investigation is needed on this.
for (User user : users) {
mUsers.add(user);
}
- //mUsers.addAll(users);
}
}
mState = UPDATE_PROCESSING_GOING_ON;
updatePresenceDatabaseNextPage();
}
/**
* This API makes the presence updates in pages of 10 with a timeout
* after each page. The HandlerAgent is notified after every 10 pages.
*/
private synchronized void updatePresenceDatabaseNextPage(){
UiAgent uiAgent = mEventCallback.getUiAgent();
if(mUsers == null){
mState = IDLE;
return;
}
int listSize = mUsers.size();
int start = 0;
int end = UPDATE_PRESENCE_PAGE_SIZE;
if(listSize == 0){
mState = IDLE;
mUsers = null;
return;
} else if(listSize < end) {
end = listSize;
}
List<User> userSubset = mUsers.subList(start, end);
if ((userSubset != null)) {
long idListeningTo = UiAgent.ALL_USERS;
if (uiAgent != null) {
idListeningTo = uiAgent.getLocalContactId();
}
boolean updateUI = PresenceDbUtils.updateDatabase(userSubset, idListeningTo, mDbHelper);
userSubset.clear();
// Send the update notification to UI for every UPDATE_PRESENCE_PAGE_SIZE*NOTIFY_AGENT_PAGE_INTERVAL updates.
if (updateUI) {
if (mUsers.size() == 0 || NOTIFY_AGENT_PAGE_INTERVAL == mIterations) {
if (uiAgent != null) {
uiAgent.updatePresence(idListeningTo);
}
mIterations = 0;
} else {
mIterations++;
}
}
if (mUsers.size() > 0) {
this.setTimeout(UPDATE_PRESENCE_TIMEOUT_MILLS);
}
}
}
/**
* Updates the database with the given ChatMessage and Type.
*
* @param message ChatMessage.
* @param type TimelineSummaryItem.Type.
*/
private void updateChatDatabase(ChatMessage message, TimelineSummaryItem.Type type) {
ChatDbUtils.convertUserIds(message, mDbHelper);
LogUtils.logD("PresenceEngine.updateChatDatabase() with [" + type.name() + "] message");
if (message.getLocalContactId() == null || message.getLocalContactId() < 0) {
LogUtils.logE("PresenceEngine.updateChatDatabase() "
+ "WILL NOT UPDATE THE DB! - INVALID localContactId = "
+ message.getLocalContactId());
return;
}
/** We mark all incoming messages as unread. **/
ChatDbUtils.saveChatMessageAsATimeline(message, type, mDbHelper);
UiAgent uiAgent = mEventCallback.getUiAgent();
if (uiAgent != null && (message.getLocalContactId() != -1)) {
uiAgent.updateChat(message.getLocalContactId(), true);
}
}
/**
* Here we update the PresenceTable, and the ContactSummaryTable afterwards
* the HandlerAgent receives the notification of presence states changes.
*
* @param users User that requires updating.
*/
private void updateMyPresenceInDatabase(User myself) {
LogUtils.logV("PresenceEnfgine.updateMyPresenceInDatabase() myself[" + myself + "]");
UiAgent uiAgent = mEventCallback.getUiAgent();
if (PresenceDbUtils.updateMyPresence(myself, mDbHelper)) {
uiAgent.updatePresence(myself.getLocalContactId());
}
}
/**
* This method handles incoming presence status change push events and the
* whole PresenceList
*
* @param dataTypes
*/
private void handleServerResponse(List<BaseDataType> dataTypes) {
if (!canRun()) {
LogUtils.logE("PresenceEngine.handleServerResponce(): "
+ "Can't run PresenceEngine before the contact list is downloaded:2");
return;
}
if (dataTypes != null) {
for (BaseDataType mBaseDataType : dataTypes) {
String name = mBaseDataType.name();
if (name.equals(PresenceList.NAME)) {
handlePresenceList((PresenceList)mBaseDataType);
} else if (name.equals(PushEvent.NAME)) {
handlePushEvent(((PushEvent)mBaseDataType));
} else if (name.equals(Conversation.NAME)) {
// a new conversation has just started
handleNewConversationId((Conversation)mBaseDataType);
} else if (name.equals(SystemNotification.class.getSimpleName())) {
handleSystemNotification((SystemNotification)mBaseDataType);
} else if (name.equals(ServerError.NAME)) {
handleServerError((ServerError)mBaseDataType);
} else {
LogUtils.logE("PresenceEngine.handleServerResponse()"
+ ": response datatype not recognized:" + name);
}
}
} else {
LogUtils.logE("PresenceEngine.handleServerResponse(): response is null!");
}
}
private void handlePresenceList(PresenceList presenceList) {
mRetryNumber = 0; // reset time out
updatePresenceDatabase(presenceList.getUsers());
}
private void handleServerError(ServerError srvError) {
LogUtils.logE("PresenceEngine.handleServerResponse() - Server error: " + srvError);
ServiceStatus errorStatus = srvError.toServiceStatus();
if (errorStatus == ServiceStatus.ERROR_COMMS_TIMEOUT) {
LogUtils.logW("PresenceEngine handleServerResponce():"
+ " TIME OUT IS RETURNED TO PRESENCE ENGINE:" + mRetryNumber);
- if (mRetryNumber < MAX_RETRY_COUNT) {
- getPresenceList();
- mRetryNumber++;
- } else {
- mRetryNumber = 0;
- setPresenceOffline();
- }
+// I believe retrying getPresenceList makes no sense, as it may "confuse" the RPG
+// if (mRetryNumber < MAX_RETRY_COUNT) {
+// getPresenceList();
+// mRetryNumber++;
+// } else {
+// mRetryNumber = 0;
+// setPresenceOffline();
+// }
}
}
private void handleNewConversationId(Conversation conversation) {
if (conversation.getTos() != null) {
mRetryNumber = 0; // reset time out
String to = conversation.getTos().get(0);
if (mSendMessagesHash.containsKey(to)) {
ChatMessage message = mSendMessagesHash.get(to);
message.setConversationId(conversation.getConversationId());
/** Update the DB with an outgoing message. **/
updateChatDatabase(message, TimelineSummaryItem.Type.OUTGOING);
Chat.sendChatMessage(message);
// clean check if DB needs a cleaning (except for
// the current conversation id)
ChatDbUtils.cleanOldConversationsExceptForContact(message.getLocalContactId(),
mDbHelper);
}
}
}
private void handlePushEvent(PushEvent event) {
switch (event.mMessageType) {
case AVAILABILITY_STATE_CHANGE:
mRetryNumber = 0; // reset time out
PushAvailabilityEvent pa = (PushAvailabilityEvent)event;
updatePresenceDatabase(pa.mChanges);
break;
case CHAT_MESSAGE:
PushChatMessageEvent pc = (PushChatMessageEvent)event;
// update the DB with an incoming message
updateChatDatabase(pc.getChatMsg(), TimelineSummaryItem.Type.INCOMING);
break;
case CLOSED_CONVERSATION:
PushClosedConversationEvent pcc = (PushClosedConversationEvent)event;
// delete the conversation in DB
if (pcc.getConversation() != null) {
ChatDbUtils.deleteConversationById(pcc.getConversation(), mDbHelper);
}
break;
case IDENTITY_CHANGE:
// identity has been added or removed, reset availability
initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase());
break;
default:
LogUtils.logE("PresenceEngine.handleServerResponse():"
+ " push message type was not recognized:" + event.name());
}
}
private void handleSystemNotification(SystemNotification sn) {
LogUtils.logE("PresenceEngine.handleServerResponse(): " + sn);
switch (sn.getSysCode()) {
case SEND_MESSAGE_FAILED:
ChatMessage msg = mSendMessagesHash.get(sn.getInfo().get(Tags.TOS.toString()));
if (msg != null) {
ChatDbUtils.deleteUnsentMessage(mDbHelper, msg);
}
showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, null);
break;
case CONVERSATION_NULL:
if (!mSendMessagesHash.isEmpty()) {
mSendMessagesHash.remove(sn.getInfo().get(Tags.TOS.toString()));
}
showErrorNotification(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, null);
break;
+ case COMMUNITY_LOGOUT_SUCCESSFUL:
+ break;
+
default:
LogUtils.logE("PresenceEngine.handleServerResponse()"
+ " - unhandled notification: " + sn);
}
}
@Override
protected void processUiRequest(ServiceUiRequest requestId, Object data) {
if (!canRun()) {
LogUtils.logE("PresenceEngine.processUIRequest():"
+ " Can't run PresenceEngine before the contact list is downloaded:1");
return;
}
LogUtils.logW("PresenceEngine.processUiRequest() requestId.name[" + requestId.name() + "]");
switch (requestId) {
case SET_MY_AVAILABILITY:
if (data != null) {
Presence.setMyAvailability((Hashtable<String, String>)data);
completeUiRequest(ServiceStatus.SUCCESS, null);
setNextRuntime();
}
break;
case GET_PRESENCE_LIST:
Presence.getPresenceList(EngineId.PRESENCE_ENGINE, null);
completeUiRequest(ServiceStatus.SUCCESS, null);
setNextRuntime();
break;
case CREATE_CONVERSATION:
if (data != null) {
List<String> tos = ((ChatMessage)data).getTos();
LogUtils.logW("PresenceEngine processUiRequest() CREATE_CONVERSATION with: "
+ tos);
Chat.startChat(tos);
// Request to update the UI
completeUiRequest(ServiceStatus.SUCCESS, null);
// Request to update the UI
setNextRuntime();
}
break;
case SEND_CHAT_MESSAGE:
if (data != null) {
ChatMessage msg = (ChatMessage)data;
updateChatDatabase(msg, TimelineSummaryItem.Type.OUTGOING);
LogUtils.logW("PresenceEngine processUiRequest() SEND_CHAT_MESSAGE :" + msg);
//cache the message (necessary for failed message sending failures)
mSendMessagesHash.put(msg.getTos().get(0), msg);
Chat.sendChatMessage(msg);
// Request to update the UI
completeUiRequest(ServiceStatus.SUCCESS, null);
// Request to update the UI
setNextRuntime();
}
break;
default:
LogUtils.logE("PresenceEngine processUiRequest() Unhandled UI request ["
+ requestId.name() + "]");
}
}
/**
* Initiate the "get presence list" request sending to server. Makes the
* engine run asap.
*
* @return
*/
public void getPresenceList() {
addUiRequestToQueue(ServiceUiRequest.GET_PRESENCE_LIST, null);
}
private void initSetMyAvailabilityRequest(User myself) {
if (myself == null) {
LogUtils.logE("PresenceEngine.initSetMyAvailabilityRequest():"
+ " Can't send the setAvailability request due to DB reading errors");
return;
}
if ((myself.isOnline() == OnlineStatus.ONLINE.ordinal() &&
ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED)
|| !canRun()) {
LogUtils.logD("PresenceEngine.initSetMyAvailabilityRequest():"
+ " return NO NETWORK CONNECTION or not ready");
return;
}
Hashtable<String, String> availability = new Hashtable<String, String>();
for (NetworkPresence presence : myself.getPayload()) {
availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(),
OnlineStatus.getValue(presence.getOnlineStatusId()).toString());
}
// set the DB values
myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper));
updateMyPresenceInDatabase(myself);
addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability);
}
/**
* Changes the state of the engine. Also displays the login notification if
* necessary.
*
* @param accounts
*/
public void setMyAvailability(Hashtable<String, String> myselfPresence) {
if (myselfPresence == null) {
LogUtils.logE("PresenceEngine setMyAvailability:"
+ " Can't send the setAvailability request due to DB reading errors");
return;
}
LogUtils.logV("PresenceEngine setMyAvailability() called with:" + myselfPresence);
if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) {
LogUtils.logD("PresenceEnfgine.setMyAvailability(): skip - NO NETWORK CONNECTION");
return;
}
User myself = new User(String.valueOf(PresenceDbUtils.getMeProfileUserId(mDbHelper)),
myselfPresence);
Hashtable<String, String> availability = new Hashtable<String, String>();
for (NetworkPresence presence : myself.getPayload()) {
availability.put(SocialNetwork.getPresenceValue(presence.getNetworkId()).toString(),
OnlineStatus.getValue(presence.getOnlineStatusId()).toString());
}
// set the DB values for myself
myself.setLocalContactId(SyncMeDbUtils.getMeProfileLocalContactId(mDbHelper));
updateMyPresenceInDatabase(myself);
// set the engine to run now
addUiRequestToQueue(ServiceUiRequest.SET_MY_AVAILABILITY, availability);
}
private void createConversation(ChatMessage msg) {
LogUtils.logW("PresenceEngine.createConversation():" + msg);
// as we currently support sending msgs to just one person getting the 0
// element of "Tos" must be acceptable
mSendMessagesHash.put(msg.getTos().get(0), msg);
addUiRequestToQueue(ServiceUiRequest.CREATE_CONVERSATION, msg);
}
/**
* This method should be used to send a message to a contact
*
* @param tos - tlocalContactId of ContactSummary items the message is
* intended for. Current protocol version only supports a single
* recipient.
* @param body the message text
*/
public void sendMessage(long toLocalContactId, String body, int networkId) {
LogUtils.logW("PresenceEngine.sendMessage() to:" + toLocalContactId + ", body:" + body
+ ", at:" + networkId);
if (ConnectionManager.getInstance().getConnectionState() != STATE_CONNECTED) {
LogUtils.logD("PresenceEnfgine.sendMessage: skip - NO NETWORK CONNECTION");
return;
}
ChatMessage msg = new ChatMessage();
msg.setBody(body);
// TODO: remove the hard code - go to UI and check what is there
if (networkId == SocialNetwork.MOBILE.ordinal()
|| (networkId == SocialNetwork.PC.ordinal())) {
msg.setNetworkId(SocialNetwork.VODAFONE.ordinal());
} else {
msg.setNetworkId(networkId);
}
msg.setLocalContactId(toLocalContactId);
ChatDbUtils.fillMessageByLocalContactIdAndNetworkId(msg, mDbHelper);
if (msg.getConversationId() != null) {
// TODO: re-factor this
if (msg.getNetworkId() != SocialNetwork.VODAFONE.ordinal()) {
String fullUserId = SocialNetwork.getChatValue(msg.getNetworkId()).toString()
+ ChatDbUtils.COLUMNS + msg.getUserId();
msg.setUserId(fullUserId);
}
addUiRequestToQueue(ServiceUiRequest.SEND_CHAT_MESSAGE, msg);
} else {
// if the conversation was not found that means it didn't exist,
// need start a new one
if (msg.getUserId() == null) {
ChatDbUtils.findUserIdForMessageByLocalContactIdAndNetworkId(msg, mDbHelper);
createConversation(msg);
}
}
}
/**
* Add ActivitiesEngine as an observer of the ContactSyncEngine. Need to be
* able to obtain a handle to the EngineManager and a handle to the
* ContactSyncEngine.
*/
private void addAsContactSyncObserver() {
if (EngineManager.getInstance() != null
&& EngineManager.getInstance().getContactSyncEngine() != null) {
EngineManager.getInstance().getContactSyncEngine().addEventCallback(this);
mContObsAdded = true;
LogUtils.logD("ActivityEngine contactSync observer added.");
} else {
LogUtils.logE("ActivityEngine can't add to contactSync observers.");
}
}
@Override
public void onContactSyncStateChange(Mode mode, State oldState, State newState) {
LogUtils.logD("PresenceEngine onContactSyncStateChange called.");
}
@Override
public void onProgressEvent(State currentState, int percent) {
if (percent == 100) {
switch (currentState) {
case FETCHING_SERVER_CONTACTS:
LogUtils
.logD("PresenceEngine onProgressEvent: FETCHING_SERVER_CONTACTS is done");
// mDownloadServerContactsComplete = true;
// break;
// case SYNCING_SERVER_ME_PROFILE:
// LogUtils
// .logD("PresenceEngine onProgressEvent: FETCHING_SERVER_ME_PROFILE is done");
// mDownloadMeProfileComplete = true;
// break;
default:
// nothing to do now
break;
}
}
}
@Override
public void onSyncComplete(ServiceStatus status) {
LogUtils.logD("PresenceEngine onSyncComplete called.");
}
@Override
public void onConnectionStateChanged(int state) {
switch (state) {
case STATE_CONNECTED:
+ getPresenceList();
initSetMyAvailabilityRequest(getMyAvailabilityStatusFromDatabase());
break;
case STATE_CONNECTING:
case STATE_DISCONNECTED:
setPresenceOffline();
mRetryNumber = 0;
mFailedMessagesList.clear();
mSendMessagesHash.clear();
break;
}
}
}
diff --git a/src/com/vodafone360/people/engine/presence/User.java b/src/com/vodafone360/people/engine/presence/User.java
index fba7aad..a70c941 100644
--- a/src/com/vodafone360/people/engine/presence/User.java
+++ b/src/com/vodafone360/people/engine/presence/User.java
@@ -1,251 +1,270 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.presence;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
+import java.util.Iterator;
import com.vodafone360.people.datatypes.ContactSummary;
import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork;
/**
* User is a class encapsulating the information about a user's presence state.
*/
public class User {
private static final String COLUMNS = "::";
private long mLocalContactId; // the database id of the contact, which
// corresponds to, e.g. "[email protected]"
private int mOverallOnline; // the overall presence state displayed in the
// common contact list
private ArrayList<NetworkPresence> mPayload; // communities presence status
// {google:online, pc:online,
// mobile:online}
/**
* Default Constructor.
*/
public User() {
}
/**
* Constructor.
*
* @param userId - user id in the contact list, e.g.
* "google::[email protected]" or "882339"
* @param payload - communities presence status {google:online, pc:online,
* mobile:online}
*/
public User(String userId, Hashtable<String, String> payload) {
mOverallOnline = isOverallOnline(payload);
mPayload = createPayload(userId, payload);
}
/**
* This method returns the localContactId for this contact in DB across the
* application .
*
* @return the localContactId for this contact in DB
*/
public long getLocalContactId() {
return mLocalContactId;
}
public void setLocalContactId(long mLocalContactId) {
this.mLocalContactId = mLocalContactId;
}
/**
* Returns communities presence status
*
* @return communities presence status, e.g. {google:online, pc:online,
* mobile:online}
*/
public ArrayList<NetworkPresence> getPayload() {
return mPayload;
}
public OnlineStatus getStatusForNetwork(SocialNetwork network) {
if (network == null) {
return null;
}
OnlineStatus os = OnlineStatus.OFFLINE;
if (mPayload != null) {
if (network == SocialNetwork.VODAFONE) {
int aggregated = 0; // aggregated state for "mobile" and "pc"
for (NetworkPresence np : mPayload) {
if (np.getNetworkId() == SocialNetwork.MOBILE.ordinal()
|| (np.getNetworkId() == SocialNetwork.PC.ordinal())) {
if (aggregated < np.getOnlineStatusId()) {
aggregated += np.getOnlineStatusId();
}
}
}
os = OnlineStatus.getValue(aggregated);
} else {
for (NetworkPresence np : mPayload) {
- // need to return aggregated status for "pc" and "mobile"
- // for Vodafone
if (np.getNetworkId() == network.ordinal()) {
os = OnlineStatus.getValue(np.getOnlineStatusId());
break;
}
}
}
}
return os;
}
/**
* Returns communities presence status
*
* @return communities presence status, e.g. {google:online, pc:online,
* mobile:online}
*/
public void setPayload(ArrayList<NetworkPresence> payload) {
mPayload = payload;
}
/**
* Returns the overall user presence status
*
* @return true if user is online at least at one community, e.g. true if
* {google:offline, pc:offline, mobile:online}
*/
private int isOverallOnline(Hashtable<String, String> payload) {
if (payload != null) {
if (payload.values().contains(ContactSummary.OnlineStatus.ONLINE.toString()))
return ContactSummary.OnlineStatus.ONLINE.ordinal();
if (payload.values().contains(ContactSummary.OnlineStatus.INVISIBLE.toString()))
return ContactSummary.OnlineStatus.INVISIBLE.ordinal();
if (payload.values().contains(ContactSummary.OnlineStatus.IDLE.toString()))
return ContactSummary.OnlineStatus.IDLE.ordinal();
}
return ContactSummary.OnlineStatus.OFFLINE.ordinal();
}
/**
* Returns the overall user presence status: in fact the one from the below
* status states first encountered for all known user accounts next:
* INVISIBLE, ONLINE, IDLE, OFFLINE
*
* @return presence state
*/
public int isOnline() {
return mOverallOnline;
}
/**
* @param payload
* @return
*/
- private static ArrayList<NetworkPresence> createPayload(String userId,
+ private ArrayList<NetworkPresence> createPayload(String userId,
Hashtable<String, String> payload) {
ArrayList<NetworkPresence> presenceList = new ArrayList<NetworkPresence>(payload.size());
String parsedUserId = parseUserName(userId);
String key = null;
SocialNetwork network = null;
String value = null;
OnlineStatus status = null;
for (Enumeration<String> en = payload.keys(); en.hasMoreElements();) {
key = en.nextElement();
network = SocialNetwork.getValue(key);
if (network != null) {
int keyIdx = network.ordinal();
value = payload.get(key);
if (value != null) {
status = OnlineStatus.getValue(value);
if (status != null) {
int valueIdx = status.ordinal();
presenceList.add(new NetworkPresence(parsedUserId, keyIdx, valueIdx));
}
}
}
}
return presenceList;
}
/**
* @param user
* @return
*/
private static String parseUserName(String userId) {
if (userId != null) {
int columnsIndex = userId.indexOf(COLUMNS);
if (columnsIndex > -1) {
return userId.substring(columnsIndex + COLUMNS.length());
} else {
return userId;
}
}
return null;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + mOverallOnline;
result = prime * result + ((mPayload == null) ? 0 : mPayload.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User)obj;
if (mOverallOnline != other.mOverallOnline)
return false;
if (mPayload == null) {
if (other.mPayload != null)
return false;
} else if (!mPayload.equals(other.mPayload))
return false;
return true;
}
@Override
public String toString() {
return "User [mLocalContactId=" + mLocalContactId + ", mOverallOnline=" + mOverallOnline
+ ", mPayload=" + mPayload + "]";
}
+ /**
+ * This method sets the overall user presence status,
+ * @parameter the online status id - the ordinal, see @OnlineStatus
+ */
public void setOverallOnline(int overallOnline) {
this.mOverallOnline = overallOnline;
}
+ /**
+ * This method removes the network presence information with the given presence id from the User.
+ * @param ordinal - the network id, ordinal in @see SocialNetworks
+ */
+ public void removeNetwork(int ordinal) {
+ Iterator<NetworkPresence> itr = mPayload.iterator();
+ NetworkPresence presence = null;
+ while (itr.hasNext()) {
+ presence = itr.next();
+ if (presence.getNetworkId() == ordinal) {
+ itr.remove();
+ break;
+ }
+ }
+ }
+
}
diff --git a/src/com/vodafone360/people/service/agent/NetworkAgent.java b/src/com/vodafone360/people/service/agent/NetworkAgent.java
index a871314..b10f73b 100644
--- a/src/com/vodafone360/people/service/agent/NetworkAgent.java
+++ b/src/com/vodafone360/people/service/agent/NetworkAgent.java
@@ -1,560 +1,558 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.service.agent;
import java.security.InvalidParameterException;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
import android.text.format.DateUtils;
-import android.widget.Toast;
import com.vodafone360.people.Intents;
import com.vodafone360.people.MainApplication;
-import com.vodafone360.people.R;
import com.vodafone360.people.service.PersistSettings;
import com.vodafone360.people.service.RemoteService;
import com.vodafone360.people.service.PersistSettings.InternetAvail;
import com.vodafone360.people.service.interfaces.IConnectionManagerInterface;
import com.vodafone360.people.service.interfaces.IWorkerThreadControl;
import com.vodafone360.people.utils.LogUtils;
/**
* The network Agent monitors the connectivity status of the device and makes
* decisions about the communication strategy. The Agent has the following
* states {connected | disconnected}, with changes reported to various listeners
* in the service.
*/
public class NetworkAgent {
/** Roaming notification is on */
public static final int ROAMING_DIALOG_GLOBAL_ON = 0;
/** Roaming notification is off */
public static final int ROAMING_DIALOG_GLOBAL_OFF = 1;
private static final int TYPE_WIFI = 1;
private static AgentState mAgentState = AgentState.UNKNOWN;
private ConnectivityManager mConnectivityManager;
private ContentResolver mContentResolver;
private AgentDisconnectReason mDisconnectReason = AgentDisconnectReason.UNKNOWN;
private SettingsContentObserver mDataRoamingSettingObserver;
private boolean mInternetConnected;
private boolean mDataRoaming;
private boolean mBackgroundData;
private boolean mIsRoaming;
private boolean mIsInBackground;
private boolean mWifiActive;
private boolean mNetworkWorking = true;
// dateTime value in milliseconds
private Long mDisableRoamingNotificationUntil = null;
private IWorkerThreadControl mWorkerThreadControl;
private IConnectionManagerInterface mConnectionMgrIf;
private Context mContext;
public enum AgentState {
CONNECTED,
DISCONNECTED,
UNKNOWN
};
/**
* Reasons for Service Agent changing state to disconnected
*/
public enum AgentDisconnectReason {
AGENT_IS_CONNECTED, // Sanity check
NO_INTERNET_CONNECTION,
NO_WORKING_NETWORK,
DATA_SETTING_SET_TO_MANUAL_CONNECTION,
DATA_ROAMING_DISABLED,
BACKGROUND_CONNECTION_DISABLED,
// WIFI_INACTIVE,
UNKNOWN
}
public enum StatesOfService {
IS_CONNECTED_TO_INTERNET,
IS_NETWORK_WORKING,
IS_ROAMING,
IS_ROAMING_ALLOWED,
IS_INBACKGROUND,
IS_BG_CONNECTION_ALLOWED,
IS_WIFI_ACTIVE
};
/**
* Listens for changes made to People client's status. The NetworkAgent is
* specifically interested in changes to the data settings (e.g. data
* disabled, only in home network or roaming).
*/
private class SettingsContentObserver extends ContentObserver {
private String mSettingName;
private SettingsContentObserver(String settingName) {
super(new Handler());
mSettingName = settingName;
}
/**
* Start content observer.
*/
private void start() {
if (mContentResolver != null) {
mContentResolver.registerContentObserver(Settings.Secure.getUriFor(mSettingName),
true, this);
}
}
/**
* De-activate content observer.
*/
private void close() {
if (mContentResolver != null) {
mContentResolver.unregisterContentObserver(this);
}
}
@Override
public void onChange(boolean selfChange) {
onDataSettingChanged(mSettingName);
}
public boolean getBooleanValue() {
if (mContentResolver != null) {
try {
return (Settings.Secure.getInt(mContentResolver, mSettingName) != 0);
} catch (SettingNotFoundException e) {
LogUtils.logE("NetworkAgent.SettingsContentObserver.getBooleanValue() "
+ "SettingNotFoundException", e);
return false;
}
}
return false;
}
}
/**
* The constructor.
*
* @param context Android context.
* @param workerThreadControl Handle to kick the worker thread.
* @param connMgrIf Handler to signal the connection manager.
* @throws InvalidParameterException Context is NULL.
* @throws InvalidParameterException IWorkerThreadControl is NULL.
* @throws InvalidParameterException IConnectionManagerInterface is NULL.
*/
public NetworkAgent(Context context, IWorkerThreadControl workerThreadControl,
IConnectionManagerInterface connMgrIf) {
if (context == null) {
throw new InvalidParameterException("NetworkAgent() Context canot be NULL");
}
if (workerThreadControl == null) {
throw new InvalidParameterException("NetworkAgent() IWorkerThreadControl canot be NULL");
}
if (connMgrIf == null) {
throw new InvalidParameterException(
"NetworkAgent() IConnectionManagerInterface canot be NULL");
}
mContext = context;
mWorkerThreadControl = workerThreadControl;
mConnectionMgrIf = connMgrIf;
mContentResolver = context.getContentResolver();
mConnectivityManager = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
mDataRoamingSettingObserver = new SettingsContentObserver(Settings.Secure.DATA_ROAMING);
}
/**
* Create NetworkAgent and start observers of device connectivity state.
*
* @throws InvalidParameterException DataRoamingSettingObserver is NULL.
* @throws InvalidParameterException Context is NULL.
* @throws InvalidParameterException ConnectivityManager is NULL.
*/
public void onCreate() {
if (mDataRoamingSettingObserver == null) {
throw new InvalidParameterException(
"NetworkAgent.onCreate() DataRoamingSettingObserver canot be NULL");
}
if (mContext == null) {
throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL");
}
if (mConnectivityManager == null) {
throw new InvalidParameterException(
"NetworkAgent.onCreate() ConnectivityManager canot be NULL");
}
mDataRoamingSettingObserver.start();
mDataRoaming = mDataRoamingSettingObserver.getBooleanValue();
mContext.registerReceiver(mBackgroundDataBroadcastReceiver, new IntentFilter(
ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED));
mContext.registerReceiver(mInternetConnectivityReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
mContext.registerReceiver(mServiceStateRoamingReceiver, new IntentFilter(
"android.intent.action.SERVICE_STATE"));
NetworkInfo info = mConnectivityManager.getActiveNetworkInfo();
if (info != null) {
mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED);
mWifiActive = (info.getType() == TYPE_WIFI);
mIsRoaming = info.isRoaming();
}
mBackgroundData = mConnectivityManager.getBackgroundDataSetting();
onConnectionStateChanged();
}
/**
* Destroy NetworkAgent and un-register observers.
*
* @throws InvalidParameterException Context is NULL.
* @throws InvalidParameterException DataRoamingSettingObserver is NULL.
*/
public void onDestroy() {
if (mContext == null) {
throw new InvalidParameterException("NetworkAgent.onCreate() Context canot be NULL");
}
if (mDataRoamingSettingObserver == null) {
throw new InvalidParameterException(
"NetworkAgent.onDestroy() DataRoamingSettingObserver canot be NULL");
}
mContext.unregisterReceiver(mInternetConnectivityReceiver);
mContext.unregisterReceiver(mBackgroundDataBroadcastReceiver);
mContext.unregisterReceiver(mServiceStateRoamingReceiver);
mDataRoamingSettingObserver.close();
mDataRoamingSettingObserver = null;
}
/**
* Receive notification from
* ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED
*/
private final BroadcastReceiver mBackgroundDataBroadcastReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LogUtils
.logV("NetworkAgent.broadcastReceiver.onReceive() ACTION_BACKGROUND_DATA_SETTING_CHANGED");
synchronized (NetworkAgent.this) {
if (mConnectivityManager != null) {
mBackgroundData = mConnectivityManager.getBackgroundDataSetting();
onConnectionStateChanged();
}
}
}
};
/**
* Receive notification from ConnectivityManager.CONNECTIVITY_ACTION
*/
private final BroadcastReceiver mInternetConnectivityReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() CONNECTIVITY_ACTION");
synchronized (NetworkAgent.this) {
mInternetConnected = false;
NetworkInfo info = (NetworkInfo)intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (!intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)) {
if (info != null) {
mInternetConnected = (info.getState() == NetworkInfo.State.CONNECTED);
mWifiActive = (info.getType() == TYPE_WIFI);
}
}
onConnectionStateChanged();
}
}
};
/**
* Receive notification from android.intent.action.SERVICE_STATE
*/
private final BroadcastReceiver mServiceStateRoamingReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() SERVICE_STATE");
synchronized (NetworkAgent.this) {
// //ConnectivityManager provides wrong information about
// roaming
// NetworkInfo info =
// mConnectivityManager.getActiveNetworkInfo();
// if (info != null) {
// mIsRoaming = info.isRoaming();
// }
LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Extras are: "
+ intent.getExtras());
Bundle bu = intent.getExtras();
// int state = bu.getInt("state");
boolean roam = bu.getBoolean("roaming");
mIsRoaming = roam;
onConnectionStateChanged();
LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() Network Roaming = "
+ mIsRoaming);
LogUtils.logV("NetworkAgent.broadcastReceiver.onReceive() WiFi active = "
+ mWifiActive);
}
processRoaming(null);
}
};
/**
* Notify interested parties of changes in Internet setting.
*
* @param val updated InternetAvail value.
*/
public void notifyDataSettingChanged(InternetAvail val) {
processRoaming(val);
onConnectionStateChanged();
}
/**
* Displaying notification to the user about roaming
*
* @param InternetAvail value.
*/
private void processRoaming(InternetAvail val) {
InternetAvail internetAvail;
if (val != null) {
internetAvail = val;
} else {
internetAvail = getInternetAvailSetting();
}
Intent intent = new Intent();
if (mContext != null
&& mIsRoaming
&& (internetAvail == InternetAvail.ALWAYS_CONNECT)
&& (mDisableRoamingNotificationUntil == null || mDisableRoamingNotificationUntil < System
.currentTimeMillis())) {
LogUtils.logV("NetworkAgent.processRoaming() "
+ "Displaying notification - DisplayRoaming[" + mIsRoaming + "]");
intent.setAction(Intents.ROAMING_ON);
} else {
/*
* We are not roaming then we should remove notification, if no
* notification were before nothing happens
*/
LogUtils.logV("NetworkAgent.processRoaming() Removing notification - "
+ " DisplayRoaming[" + mIsRoaming + "]");
intent.setAction(Intents.ROAMING_OFF);
}
mContext.sendBroadcast(intent);
}
private InternetAvail getInternetAvailSetting() {
if (mContext != null) {
PersistSettings setting = ((MainApplication)((RemoteService)mContext).getApplication())
.getDatabase().fetchOption(PersistSettings.Option.INTERNETAVAIL);
if (setting != null) {
return setting.getInternetAvail();
}
}
return null;
}
public int getRoamingNotificationType() {
int type;
if (mDataRoaming) {
type = ROAMING_DIALOG_GLOBAL_ON;
} else {
type = ROAMING_DIALOG_GLOBAL_OFF;
}
return type;
}
/**
* Get current device roaming setting.
*
* @return current device roaming setting.
*/
public boolean getRoamingDeviceSetting() {
return mDataRoaming;
}
public void setShowRoamingNotificationAgain(boolean showAgain) {
LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() " + "showAgain[" + showAgain
+ "]");
if (showAgain) {
mDisableRoamingNotificationUntil = null;
} else {
mDisableRoamingNotificationUntil = System.currentTimeMillis() + DateUtils.DAY_IN_MILLIS;
if (mContext != null) {
LogUtils.logV("NetworkAgent.setShowRoamingNotificationAgain() "
+ "Next notification on ["
+ DateUtils.formatDateTime(mContext, mDisableRoamingNotificationUntil,
DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME
| DateUtils.FORMAT_SHOW_YEAR) + "]");
}
}
processRoaming(null);
}
/**
* Received when user modifies one of the system settings
*/
private synchronized void onDataSettingChanged(String settingName) {
LogUtils.logV("NetworkAgent.onDataSettingChanged() settingName[" + settingName + "]"
+ " has changed");
if (settingName.equals(Settings.Secure.DATA_ROAMING)) {
if (mDataRoamingSettingObserver != null) {
mDataRoaming = mDataRoamingSettingObserver.getBooleanValue();
onConnectionStateChanged();
}
}
}
/**
* Contains the main logic that determines the agent state for network
* access
*/
private void onConnectionStateChanged() {
if (!mInternetConnected) {
LogUtils.logV("NetworkAgent.onConnectionStateChanged() No internet connection");
mDisconnectReason = AgentDisconnectReason.NO_INTERNET_CONNECTION;
setNewState(AgentState.DISCONNECTED);
return;
} else {
if (mWifiActive) {
LogUtils.logV("NetworkAgent.onConnectionStateChanged() WIFI connected");
} else {
LogUtils.logV("NetworkAgent.onConnectionStateChanged() Cellular connected");
}
}
if (mContext != null) {
MainApplication app = (MainApplication)((RemoteService)mContext).getApplication();
if ((app.getInternetAvail() == InternetAvail.MANUAL_CONNECT)/*
* AA: I
* commented
* it -
* TBD
* &&!
* mWifiActive
*/) {
LogUtils.logV("NetworkAgent.onConnectionStateChanged()"
+ " Internet allowed only in manual mode");
mDisconnectReason = AgentDisconnectReason.DATA_SETTING_SET_TO_MANUAL_CONNECTION;
setNewState(AgentState.DISCONNECTED);
return;
}
}
if (!mNetworkWorking) {
LogUtils.logV("NetworkAgent.onConnectionStateChanged() Network is not working");
mDisconnectReason = AgentDisconnectReason.NO_WORKING_NETWORK;
setNewState(AgentState.DISCONNECTED);
return;
}
if (mIsRoaming && !mDataRoaming) {
LogUtils.logV("NetworkAgent.onConnectionStateChanged() "
+ "Connect while roaming not allowed");
mDisconnectReason = AgentDisconnectReason.DATA_ROAMING_DISABLED;
setNewState(AgentState.DISCONNECTED);
return;
}
if (mIsInBackground && !mBackgroundData) {
LogUtils
.logV("NetworkAgent.onConnectionStateChanged() Background connection not allowed");
mDisconnectReason = AgentDisconnectReason.BACKGROUND_CONNECTION_DISABLED;
setNewState(AgentState.DISCONNECTED);
return;
}
LogUtils.logV("NetworkAgent.onConnectionStateChanged() Connection available");
setNewState(AgentState.CONNECTED);
}
public static AgentState getAgentState() {
LogUtils.logV("NetworkAgent.getAgentState() mAgentState[" + mAgentState.name() + "]");
return mAgentState;
}
private void setNewState(AgentState newState) {
if (newState == mAgentState) {
return;
}
LogUtils.logI("NetworkAgent.setNewState(): " + mAgentState + " -> " + newState);
mAgentState = newState;
if (newState == AgentState.CONNECTED) {
mDisconnectReason = AgentDisconnectReason.AGENT_IS_CONNECTED;
onConnected();
} else if (newState == AgentState.DISCONNECTED) {
onDisconnected();
}
}
private void onConnected() {
checkActiveNetworkState();
if (mWorkerThreadControl != null) {
mWorkerThreadControl.kickWorkerThread();
}
if (mConnectionMgrIf != null) {
mConnectionMgrIf.signalConnectionManager(true);
}
}
private void onDisconnected() {
// AA:need to kick it to make engines run and set the
if (mWorkerThreadControl != null) {
mWorkerThreadControl.kickWorkerThread();
}
if (mConnectionMgrIf != null) {
mConnectionMgrIf.signalConnectionManager(false);
}
}
private void checkActiveNetworkState() {
if (mConnectivityManager != null) {
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo == null) {
diff --git a/src/com/vodafone360/people/utils/HardcodedUtils.java b/src/com/vodafone360/people/utils/HardcodedUtils.java
index 8e4c75f..fc97e55 100644
--- a/src/com/vodafone360/people/utils/HardcodedUtils.java
+++ b/src/com/vodafone360/people/utils/HardcodedUtils.java
@@ -1,57 +1,71 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the Common Development
- * and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at
- * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
- * http://github.com/360/360-Engine-for-Android
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each file and
- * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
- * If applicable, add the following below this CDDL HEADER, with the fields
- * enclosed by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
- * Use is subject to license terms.
- */
-package com.vodafone360.people.utils;
-
-import java.util.Hashtable;
-
-import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
-import com.vodafone360.people.engine.presence.NetworkPresence;
-
-/**
- * @author timschwerdtner
- * Collection of hardcoded and duplicated code as a first step for refactoring.
- */
-public class HardcodedUtils {
-
- /**
- * To be used with IPeopleService.setAvailability until identity handling
- * has been refactored.
- * @param Desired availability state
- * @return A hashtable for the set availability call
- */
- public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) {
- Hashtable<String, String> availability = new Hashtable<String, String>();
-
- LogUtils.logD("Setting Availability to: " + onlineStatus.toString());
- // TODO: REMOVE HARDCODE setting everything possible to currentStatus
- availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString());
- availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString());
- availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString());
- availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString());
- availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString());
-
- return availability;
- }
-}
+/*
+ * CDDL HEADER START
+ *
+ * The contents of this file are subject to the terms of the Common Development
+ * and Distribution License (the "License").
+ * You may not use this file except in compliance with the License.
+ *
+ * You can obtain a copy of the license at
+ * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
+ * http://github.com/360/360-Engine-for-Android
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * When distributing Covered Code, include this CDDL HEADER in each file and
+ * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
+ * If applicable, add the following below this CDDL HEADER, with the fields
+ * enclosed by brackets "[]" replaced with your own identifying information:
+ * Portions Copyright [yyyy] [name of copyright owner]
+ *
+ * CDDL HEADER END
+ *
+ * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
+ * Use is subject to license terms.
+ */
+package com.vodafone360.people.utils;
+
+import java.util.ArrayList;
+import java.util.Hashtable;
+
+import com.vodafone360.people.datatypes.ContactSummary.OnlineStatus;
+import com.vodafone360.people.engine.presence.NetworkPresence;
+import com.vodafone360.people.engine.presence.NetworkPresence.SocialNetwork;
+
+/**
+ * @author timschwerdtner
+ * Collection of hardcoded and duplicated code as a first step for refactoring.
+ */
+public class HardcodedUtils {
+
+ /**
+ * To be used with IPeopleService.setAvailability until identity handling
+ * has been refactored.
+ * @param Desired availability state
+ * @return A hashtable for the set availability call
+ */
+ public static Hashtable<String, String> createMyAvailabilityHashtable(OnlineStatus onlineStatus) {
+ Hashtable<String, String> availability = new Hashtable<String, String>();
+
+ LogUtils.logD("Setting Availability to: " + onlineStatus.toString());
+ // TODO: REMOVE HARDCODE setting everything possible to currentStatus
+ availability.put(NetworkPresence.SocialNetwork.GOOGLE.toString(), onlineStatus.toString());
+ availability.put(NetworkPresence.SocialNetwork.MICROSOFT.toString(), onlineStatus.toString());
+ availability.put(NetworkPresence.SocialNetwork.MOBILE.toString(), onlineStatus.toString());
+ availability.put(NetworkPresence.SocialNetwork.HYVES_NL.toString(), onlineStatus.toString());
+ availability.put(NetworkPresence.SocialNetwork.FACEBOOK_COM.toString(), onlineStatus.toString());
+
+ return availability;
+ }
+
+ /**
+ * The static list of supported TPC accounts.
+ */
+ public static final ArrayList<Integer> THIRD_PARTY_CHAT_ACCOUNTS = new ArrayList<Integer>();
+
+ static {
+ THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.FACEBOOK_COM.ordinal());
+ THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.GOOGLE.ordinal());
+ THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.HYVES_NL.ordinal());
+ THIRD_PARTY_CHAT_ACCOUNTS.add(SocialNetwork.MICROSOFT.ordinal());
+ }
+}
|
360/360-Engine-for-Android
|
a160d76db16e1a6209d19870246c3525e64b9a74
|
added a dot into the comment
|
diff --git a/src/com/vodafone360/people/engine/EngineManager.java b/src/com/vodafone360/people/engine/EngineManager.java
index 85f4713..4cb717c 100644
--- a/src/com/vodafone360/people/engine/EngineManager.java
+++ b/src/com/vodafone360/people/engine/EngineManager.java
@@ -1,592 +1,592 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine;
import java.security.InvalidParameterException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import com.vodafone360.people.MainApplication;
import com.vodafone360.people.Settings;
import com.vodafone360.people.SettingsManager;
import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback;
import com.vodafone360.people.engine.activities.ActivitiesEngine;
import com.vodafone360.people.engine.contactsync.ContactSyncEngine;
import com.vodafone360.people.engine.groups.GroupsEngine;
import com.vodafone360.people.engine.content.ContentEngine;
import com.vodafone360.people.engine.identities.IdentityEngine;
import com.vodafone360.people.engine.login.LoginEngine;
import com.vodafone360.people.engine.meprofile.SyncMeEngine;
import com.vodafone360.people.engine.presence.PresenceEngine;
import com.vodafone360.people.engine.upgrade.UpgradeEngine;
import com.vodafone360.people.service.RemoteService;
import com.vodafone360.people.service.WorkerThread;
import com.vodafone360.people.service.io.ResponseQueue;
import com.vodafone360.people.service.transport.ConnectionManager;
import com.vodafone360.people.utils.LogUtils;
/**
* EngineManager class is responsible for creating, handling and deletion of
* engines in the People client. The EngineManager determine when each engine
* should be run based on the engine's next run time or whether there is a
* waiting request for that engine. The EngineManager routes received responses
* to the appropriate engine.
*/
public class EngineManager {
/**
* Identifiers for engines.
*/
public enum EngineId {
LOGIN_ENGINE,
CONTACT_SYNC_ENGINE,
GROUPS_ENGINE,
ACTIVITIES_ENGINE,
IDENTITIES_ENGINE,
PRESENCE_ENGINE,
UPGRADE_ENGINE,
CONTENT_ENGINE,
SYNCME_ENGINE,
UNDEFINED
// add ids as we progress
}
/**
- * {@link EngineManager} is a singleton, so this is the static reference
+ * {@link EngineManager} is a singleton, so this is the static reference.
*/
private static EngineManager sEngineManager;
/**
* Engine manager maintains a list of all engines in the system. This is a
* map between the engine ID and the engine reference.
*/
private final HashMap<Integer, BaseEngine> mEngineList = new HashMap<Integer, BaseEngine>();
/**
* Reference to the {@RemoteService} object which provides
* access to the {@link WorkerThread}.
*/
private RemoteService mService;
/**
* Engines require access the {@link IEngineEventCallback} interface.
* Implements several useful methods for engines such as UI request
* complete.
*/
private IEngineEventCallback mUiEventCallback;
/**
* @see LoginEngine
*/
private LoginEngine mLoginEngine;
/**
* @see UpgradeEngine
*/
private UpgradeEngine mUpgradeEngine;
/**
* @see ActivitiesEngine
*/
private ActivitiesEngine mActivitiesEngine;
/**
* @see SyncMeEngine
*/
private SyncMeEngine mSyncMeEngine;
/**
* @see PresenceEngine
*/
private PresenceEngine mPresenceEngine;
/**
* @see IdentityEngine
*/
private IdentityEngine mIdentityEngine;
/**
* @see ContactSyncEngine
*/
private ContactSyncEngine mContactSyncEngine;
/**
* @see GroupsEngine
*/
private GroupsEngine mGroupsEngine;
/**
* @see ContentEngine
*/
private ContentEngine mContentEngine;
/**
* Maximum time the run function for an engine is allowed to run before a
* warning message will be displayed (debug only)
*/
private static final long ENGINE_RUN_TIME_THRESHOLD = 3000;
/**
* Engine Manager Constructor
*
* @param service {@link RemoteService} reference
* @param uiCallback Provides useful engine callback functionality.
*/
private EngineManager(RemoteService service, IEngineEventCallback uiCallback) {
mService = service;
mUiEventCallback = uiCallback;
}
/**
* Create instance of EngineManager.
*
* @param service {@link RemoteService} reference
* @param uiCallback Provides useful engine callback functionality.
*/
public static void createEngineManager(RemoteService service, IEngineEventCallback uiCallback) {
sEngineManager = new EngineManager(service, uiCallback);
sEngineManager.onCreate();
}
/**
* Destroy EngineManager.
*/
public static void destroyEngineManager() {
if (sEngineManager != null) {
sEngineManager.onDestroy();
sEngineManager = null;
}
}
/**
* Get single instance of {@link EngineManager}.
*
* @return {@link EngineManager} singleton instance.
*/
public static EngineManager getInstance() {
if (sEngineManager == null) {
throw new InvalidParameterException("Please call EngineManager.createEngineManager() "
+ "before EngineManager.getInstance()");
}
return sEngineManager;
}
/**
* Add a new engine to the EngineManager.
*
* @param newEngine Engine to be added.
*/
private synchronized void addEngine(BaseEngine newEngine) {
final String newName = newEngine.getClass().getSimpleName();
String[] deactivatedEngines = SettingsManager
.getStringArrayProperty(Settings.DEACTIVATE_ENGINE_LIST_KEY);
for (String engineName : deactivatedEngines) {
if (engineName.equals(newName)) {
LogUtils.logW("DEACTIVATE ENGINE: " + engineName);
newEngine.deactivateEngine();
}
}
if (!newEngine.isDeactivated()) {
newEngine.onCreate();
mEngineList.put(newEngine.mEngineId.ordinal(), newEngine);
}
mService.kickWorkerThread();
}
/**
* Closes an engine and removes it from the list.
*
* @param engine Reference of engine by base class {@link BaseEngine} to
* close
*/
private synchronized void closeEngine(BaseEngine engine) {
mEngineList.remove(engine.engineId().ordinal());
if (!engine.isDeactivated()) {
engine.onDestroy();
}
}
/**
* Called immediately after manager has been created. Starts the necessary
* engines
*/
private synchronized void onCreate() {
// LogUtils.logV("EngineManager.onCreate()");
createLoginEngine();
createIdentityEngine();
createSyncMeEngine();
createContactSyncEngine();
createGroupsEngine();
if (SettingsManager.getProperty(Settings.UPGRADE_CHECK_URL_KEY) != null) {
createUpgradeEngine();
}
createActivitiesEngine();
createPresenceEngine();
createContentEngine();
}
/**
* Called just before the service is stopped. Shuts down all the engines
*/
private synchronized void onDestroy() {
final int engineCount = mEngineList.values().size();
BaseEngine[] engineList = new BaseEngine[engineCount];
mEngineList.values().toArray(engineList);
for (int i = 0; i < engineCount; i++) {
closeEngine(engineList[i]);
}
mLoginEngine = null;
mUpgradeEngine = null;
mActivitiesEngine = null;
mPresenceEngine = null;
mIdentityEngine = null;
mContactSyncEngine = null;
mGroupsEngine = null;
mContentEngine = null;
}
/**
* Obtains a reference to the login engine
*
* @return a reference to the LoginEngine
*/
public LoginEngine getLoginEngine() {
assert mLoginEngine != null;
return mLoginEngine;
}
/**
* Create instance of LoginEngine.
*/
private synchronized void createLoginEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mLoginEngine = new LoginEngine(mService, mUiEventCallback, app.getDatabase());
addEngine(mLoginEngine);
}
/**
* Fetch upgrade engine
*
* @return UpgradeEngine object
*/
public UpgradeEngine getUpgradeEngine() {
assert mUpgradeEngine != null;
return mUpgradeEngine;
}
/**
* Create instance of UpgradeEngine.
*/
private synchronized void createUpgradeEngine() {
mUpgradeEngine = new UpgradeEngine(mService, mUiEventCallback);
addEngine(mUpgradeEngine);
}
/**
* Fetch activities engine
*
* @return a ActivitiesEngine object
*/
public ActivitiesEngine getActivitiesEngine() {
assert mActivitiesEngine != null;
return mActivitiesEngine;
}
/**
* Create instance of ActivitiesEngine.
*/
private synchronized void createActivitiesEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mActivitiesEngine = new ActivitiesEngine(mService, mUiEventCallback, app.getDatabase());
getLoginEngine().addListener(mActivitiesEngine);
addEngine(mActivitiesEngine);
}
/**
* Fetch sync me engine, starting it if necessary.
*
* @return The SyncMeEngine
*/
public SyncMeEngine getSyncMeEngine() {
assert mSyncMeEngine != null;
return mSyncMeEngine;
}
/**
* Create instance of SyncMeEngine.
*/
private synchronized void createSyncMeEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mSyncMeEngine = new SyncMeEngine(mService, mUiEventCallback, app.getDatabase());
addEngine(mSyncMeEngine);
}
/**
* Fetch presence engine
*
* @return Presence Engine object
*/
public PresenceEngine getPresenceEngine() {
assert mPresenceEngine != null;
return mPresenceEngine;
}
/**
* Fetch identity engine
*
* @return IdentityEngine object
*/
public IdentityEngine getIdentityEngine() {
assert mIdentityEngine != null;
return mIdentityEngine;
}
/**
* Fetch content engine
*
* @return ContentEngine object
*/
public ContentEngine getContentEngine() {
assert mContentEngine != null;
return mContentEngine;
}
/**
* Fetch contact sync engine
*
* @return ContactSyncEngine object
*/
public ContactSyncEngine getContactSyncEngine() {
assert mContactSyncEngine != null;
return mContactSyncEngine;
}
private synchronized void createContactSyncEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mContactSyncEngine = new ContactSyncEngine(mUiEventCallback, mService, app.getDatabase(),
null);
addEngine(mContactSyncEngine);
}
/**
* Fetch groups engine
*
* @return GroupEngine object
*/
public GroupsEngine getGroupsEngine() {
assert mGroupsEngine != null;
return mGroupsEngine;
}
private synchronized void createGroupsEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mGroupsEngine = new GroupsEngine(mService, mUiEventCallback, app.getDatabase());
addEngine(mGroupsEngine);
}
/**
* Create instance of IdentityEngine.
*/
private synchronized void createIdentityEngine() {
mIdentityEngine = new IdentityEngine(mUiEventCallback);
addEngine(mIdentityEngine);
}
/**
* Create instance of ContentEngine.
*/
private synchronized void createContentEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mContentEngine = new ContentEngine(mUiEventCallback, app.getDatabase());
addEngine(mContentEngine);
}
/**
* Create instance of PresenceEngine.
*/
private synchronized void createPresenceEngine() {
final MainApplication app = (MainApplication)mService.getApplication();
mPresenceEngine = new PresenceEngine(mUiEventCallback, app.getDatabase());
ConnectionManager.getInstance().addConnectionListener(mPresenceEngine);
getLoginEngine().addListener(mPresenceEngine);
addEngine(mPresenceEngine);
}
/**
* Respond to incoming message received from Comms layer. If this message
* has a valid engine id it is routed to that engine, otherwise The
* {@link EngineManager} will try to get the next response.
*
* @param source EngineId associated with incoming message.
*/
public void onCommsInMessage(EngineId source) {
BaseEngine engine = null;
if (source != null) {
engine = mEngineList.get(source.ordinal());
}
if (engine != null) {
engine.onCommsInMessage();
} else {
LogUtils.logE("EngineManager.onCommsInMessage - "
+ "Cannot dispatch message, unknown source " + source);
final ResponseQueue queue = ResponseQueue.getInstance();
queue.getNextResponse(source);
}
}
/**
* Run any waiting engines and return the time in milliseconds from now when
* this method needs to be called again.
*
* @return -1 never needs to run, 0 needs to run as soon as possible,
* CurrentTime + 60000 in 1 minute, etc.
*/
public synchronized long runEngines() {
long nextRuntime = -1;
Set<Integer> e = mEngineList.keySet();
Iterator<Integer> i = e.iterator();
while (i.hasNext()) {
int engineId = i.next();
BaseEngine engine = mEngineList.get(engineId);
long currentTime = System.currentTimeMillis();
long tempRuntime = engine.getNextRunTime(); // TODO: Pass
// mCurrentTime to
// getNextRunTime() to
// help with Unit
// tests
if (Settings.ENABLED_ENGINE_TRACE) {
LogUtils.logV("EngineManager.runEngines() " + "engine["
+ engine.getClass().getSimpleName() + "] " + "nextRunTime["
+ getHumanReadableTime(tempRuntime, currentTime) + "] " + "current["
+ getHumanReadableTime(nextRuntime, currentTime) + "]");
} else {
if (tempRuntime > 0 && tempRuntime < currentTime) {
LogUtils.logD("Engine[" + engine.getClass().getSimpleName() + "] run pending");
}
}
if (tempRuntime < 0) {
if (Settings.ENABLED_ENGINE_TRACE) {
LogUtils.logV("EngineManager.runEngines() Engine is off, so ignore");
}
} else if (tempRuntime <= currentTime) {
if (Settings.ENABLED_ENGINE_TRACE) {
LogUtils.logV("EngineManager.runEngines() Run Engine ["
+ engine.getClass().getSimpleName()
+ "] and make sure we check it once more before sleeping");
}
/** TODO: Consider passing mCurrentTime to mEngine.run(). **/
engine.run();
nextRuntime = 0;
final long timeForRun = System.currentTimeMillis() - currentTime;
if (timeForRun > ENGINE_RUN_TIME_THRESHOLD) {
LogUtils.logE("EngineManager.runEngines() Engine ["
+ engine.getClass().getSimpleName() + "] took " + timeForRun
+ "ms to run");
}
if (Settings.ENABLED_PROFILE_ENGINES) {
StringBuilder string = new StringBuilder();
string.append(System.currentTimeMillis());
string.append("|");
string.append(engine.getClass().getSimpleName());
string.append("|");
string.append(timeForRun);
LogUtils.profileToFile(string.toString());
}
} else {
if (nextRuntime != -1) {
nextRuntime = Math.min(nextRuntime, tempRuntime);
} else {
nextRuntime = tempRuntime;
}
if (Settings.ENABLED_ENGINE_TRACE) {
LogUtils.logV("EngineManager.runEngines() Set mNextRuntime to ["
+ getHumanReadableTime(nextRuntime, currentTime) + "]");
}
}
}
if (Settings.ENABLED_ENGINE_TRACE) {
LogUtils.logI("EngineManager.getNextRunTime() Return ["
+ getHumanReadableTime(nextRuntime, System.currentTimeMillis()) + "]");
}
return nextRuntime;
}
/***
* Display the Absolute Time in a human readable format (for testing only).
*
* @param absoluteTime Time to convert
* @param currentTime Current time, for creating all relative times
* @return Absolute time in human readable form
*/
private static String getHumanReadableTime(long absoluteTime, long currentTime) {
if (absoluteTime == -1) {
return "OFF";
} else if ((absoluteTime == 0)) {
return "NOW";
} else if (absoluteTime >= currentTime) {
return (absoluteTime - currentTime) + "ms";
} else {
return (currentTime - absoluteTime) + "ms LATE";
}
}
/**
* Resets all the engines. Note: the method will block until all the engines
* have performed the reset.
*/
public void resetAllEngines() {
LogUtils.logV("EngineManager.resetAllEngines() - begin");
synchronized (mEngineList) {
// Propagate the reset event to all engines
for (BaseEngine engine : mEngineList.values()) {
engine.onReset();
}
}
// block the thread until all engines have been reset
boolean allEngineAreReset = false;
while (!allEngineAreReset) {
synchronized (mEngineList) {
boolean engineNotReset = false;
for (BaseEngine engine : mEngineList.values()) {
if (!engine.getReset()) {
engineNotReset = true;
}
}
if (!engineNotReset) {
allEngineAreReset = true;
for (BaseEngine engine : mEngineList.values()) {
engine.clearReset();
}
}
}
Thread.yield();
}
|
360/360-Engine-for-Android
|
33ff073752d6261a17a0bc69df98bdcc8c03908b
|
- dito
|
diff --git a/tests/build.xml b/tests/build.xml
index 483aafc..e9dcd87 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,572 +1,572 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
<property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
<!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
already on your system, please do so. After setting it, create a new properties file in
build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
to it. -->
- <property file="build_property_files/${env.USERNAME_360}.properties" />
+ <property file="../build_property_files/${env.USERNAME_360}.properties" />
<echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
XMLTask is found in ${xml.task.dir}...</echo>
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
|
360/360-Engine-for-Android
|
5f655ac99efe4e3b2f9df07519a968016eca77eb
|
- altered tests/build.xml to cope with different build paths...
|
diff --git a/tests/build.xml b/tests/build.xml
index a63ee4b..483aafc 100644
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,573 +1,575 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
-
- <!-- The local.properties file is created and updated by the 'android' tool.
- It contains the path to the SDK. It should *NOT* be checked in in Version
- Control Systems. -->
- <!-- <property file="local.properties" /> Point to the SDK location manually -->
- <property name="sdk.dir" value="C:\\tools\\android-sdk-windows" />
- <property name="sdk-location" value="C:\\tools\\android-sdk-windows" />
+ <property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="build_property_files/${env.USERNAME_360}.properties" />
+ <echo>Testing for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
+ XMLTask is found in ${xml.task.dir}...</echo>
+
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="junit.out.file" value="${tested.project.absolute.dir}\output\junit-result.txt" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
|
360/360-Engine-for-Android
|
7a18f409be340aa200daaecf4b410880e5327d2b
|
Fix for PAND-1637 Crash: ConcurrentModificationException in com.vodafone360.people
|
diff --git a/src/com/vodafone360/people/service/io/RequestQueue.java b/src/com/vodafone360/people/service/io/RequestQueue.java
index ea8890c..d1dd299 100644
--- a/src/com/vodafone360/people/service/io/RequestQueue.java
+++ b/src/com/vodafone360/people/service/io/RequestQueue.java
@@ -1,474 +1,484 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.service.io;
import java.util.ArrayList;
import java.util.List;
import com.vodafone360.people.Settings;
import com.vodafone360.people.service.transport.IQueueListener;
import com.vodafone360.people.service.transport.http.HttpConnectionThread;
import com.vodafone360.people.service.utils.TimeOutWatcher;
import com.vodafone360.people.utils.LogUtils;
/**
* Holds a queue of outgoing requests. The Requester adds Requests to the queue.
* The transport layer gets one or more items from the queue when it is ready to
* send more requests to the server. When a Request is added a request id is
* generated for this request. Requests are removed from the queue on completion
* or if an error requires us to clear any outstanding requests.
*/
public class RequestQueue {
private final static int MILLIS_PER_SECOND = 1000;
/**
* The queue data, a List-array of Request items.
*/
private final List<Request> mRequests = new ArrayList<Request>();
/**
* A unique ID identifying this request
*/
private volatile int mCurrentRequestId;
/**
* Contains a list of listeners that will receive events when items are
* added to the queue.
*/
private final List<IQueueListener> mListeners = new ArrayList<IQueueListener>();
private TimeOutWatcher mTimeOutWatcher;
/**
* Constructs the request queue
*/
protected RequestQueue() {
// Generate initial request ID based on current timestamp.
mCurrentRequestId = (int)(System.currentTimeMillis() / MILLIS_PER_SECOND);
mTimeOutWatcher = new TimeOutWatcher();
}
/**
* Get instance of RequestQueue - we only have a single instance. If the
* instance of RequestQueue does not yet exist it is created.
*
* @return Instance of RequestQueue.
*/
protected static RequestQueue getInstance() {
return RequestQueueHolder.rQueue;
}
/**
* Use Initialization on demand holder pattern
*/
private static class RequestQueueHolder {
private static final RequestQueue rQueue = new RequestQueue();
}
/**
* Add listener listening for RequestQueue changes. Events are sent when
* items are added to the queue (or in the case of batching when the last
* item is added to the queue).
*
* @param listener listener to add
*/
- protected void addQueueListener(IQueueListener listener) {
- LogUtils.logW("RequestQueue.addQueueListener() listener[" + listener + "]");
- if (mListeners != null) {
- mListeners.add(listener);
- }
- }
+ protected void addQueueListener(IQueueListener listener) {
+ LogUtils.logW("RequestQueue.addQueueListener() listener[" + listener
+ + "]");
+ synchronized (mListeners) {
+ if (mListeners != null) {
+ mListeners.add(listener);
+ }
+ }
+ }
/**
* Remove RequestQueue listener
*
* @param listener listener to remove
*/
- protected void removeQueueListener(IQueueListener listener) {
- LogUtils.logW("RequestQueue.removeQueueListener() listener[" + listener + "]");
- if (mListeners != null) {
- mListeners.remove(listener);
- }
- }
+ protected void removeQueueListener(IQueueListener listener) {
+ LogUtils.logW("RequestQueue.removeQueueListener() listener[" + listener
+ + "]");
+ synchronized (mListeners) {
+ if (mListeners != null) {
+ mListeners.remove(listener);
+ }
+ }
+ }
/**
* Fire RequestQueue state changed message
*/
- protected void fireQueueStateChanged() {
- LogUtils.logW("RequestQueue.notifyOfItemInRequestQueue() listener[" + mListeners + "]");
- for (IQueueListener listener : mListeners)
- listener.notifyOfItemInRequestQueue();
- }
+ protected void fireQueueStateChanged() {
+ synchronized (mListeners) {
+ LogUtils.logW("RequestQueue.notifyOfItemInRequestQueue() listener["
+ + mListeners + "]");
+ for (IQueueListener listener : mListeners) {
+ listener.notifyOfItemInRequestQueue();
+ }
+ }
+ }
/**
* Add request to queue
*
* @param req Request to add to queue
* @return request id of new request
*/
protected int addRequestAndNotify(Request req) {
synchronized (QueueManager.getInstance().lock) {
int ret = addRequest(req);
fireQueueStateChanged();
return ret;
}
}
/**
* Adds a request to the queue without sending an event to the listeners
*
* @param req The request to add
* @return The unique request ID TODO: What is with the method naming
* convention?
*/
protected int addRequest(Request req) {
synchronized (QueueManager.getInstance().lock) {
mCurrentRequestId++;
req.setRequestId(mCurrentRequestId);
mRequests.add(req);
// add the request to the watcher thread
if (req.getTimeout() > 0 && (!req.isFireAndForget())) {
// TODO: maybe the expiry date should be calculated when the
// request is actually sent?
req.calculateExpiryDate();
mTimeOutWatcher.addRequest(req);
}
HttpConnectionThread.logV("RequestQueue.addRequest", "Adding request to queue:\n" + req.toString());
return mCurrentRequestId;
}
}
/**
* Adds requests to the queue.
*
* @param requests The requests to add.
* @return The request IDs generated in an integer array or null if the
* requests array was null. Returns NULL id requests[] is NULL.
*/
protected int[] addRequest(Request[] requests) {
synchronized (QueueManager.getInstance().lock) {
if (null == requests) {
return null;
}
int[] requestIds = new int[requests.length];
for (int i = 0; i < requests.length; i++) {
requestIds[i] = addRequest(requests[i]);
}
return requestIds;
}
}
/*
* Get number of items currently in the list of requests
* @return number of request items
*/
private int requestCount() {
return mRequests.size();
}
/**
* Returns all requests from the queue. Regardless if they need to
*
* @return List of all requests.
*/
protected List<Request> getAllRequests() {
synchronized (QueueManager.getInstance().lock) {
return mRequests;
}
}
/**
* Returns all requests from the queue needing the API or both to work.
*
* @return List of all requests needing the API or both (API or RPG) to
* function properly.
*/
protected List<Request> getApiRequests() {
synchronized (QueueManager.getInstance().lock) {
return this.getRequests(false);
}
}
/**
* Returns all requests from the queue needing the RPG or both to work.
*
* @return List of all requests needing the RPG or both (API or RPG) to
* function properly.
*/
protected List<Request> getRpgRequests() {
return this.getRequests(true);
}
/**
* Returns a list of either requests needing user authentication or requests
* not needing user authentication depending on the flag passed to this
* method.
*
* @param needsUserAuthentication If true only requests that need to have a
* valid user authentication will be returned. Otherwise methods
* requiring application authentication will be returned.
* @return A list of requests with the need for application authentication
* or user authentication.
*/
private List<Request> getRequests(boolean needsRpgForRequest) {
synchronized (QueueManager.getInstance().lock) {
List<Request> requests = new ArrayList<Request>();
if (null == mRequests) {
return requests;
}
Request request = null;
for (int i = 0; i < mRequests.size(); i++) {
request = mRequests.get(i);
if ((null == request) || (request.isActive())) {
LogUtils.logD("Skipping active or null request in request queue.");
continue;
}
HttpConnectionThread.logD("RequestQueu.getRequests()",
"Request Auth Type (USE_API=1, USE_RPG=2, USE_BOTH=3): "
+ request.getAuthenticationType());
// all api and rpg requests
if (request.getAuthenticationType() == Request.USE_BOTH) {
requests.add(request);
} else if ((!needsRpgForRequest)
&& (request.getAuthenticationType() == Request.USE_API)) {
requests.add(request);
} else if ((needsRpgForRequest)
&& (request.getAuthenticationType() == Request.USE_RPG)) {
requests.add(request); // all rpg requests
}
}
return requests;
}
}
/**
* Return Request from specified request ID. Only used for unit tests.
*
* @param requestId Request Id of required request
* @return Request with or null if request does not exist
*/
protected Request getRequest(int requestId) {
Request req = null;
int reqCount = requestCount();
for (int i = 0; i < reqCount; i++) {
Request tmp = mRequests.get(i);
if (tmp.getRequestId() == requestId) {
req = tmp;
break;
}
}
return req;
}
/**
* Removes the request for the given request ID from the queue and searches
* the queue for requests older than
* Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS and removes them as well.
*
* @param requestId The ID of the request to remove.
* @return True if the request was found and removed.
*/
protected boolean removeRequest(int requestId) {
synchronized (QueueManager.getInstance().lock) {
boolean didRemoveSearchedRequest = false;
for (int i = 0; i < requestCount(); i++) {
Request request = mRequests.get(i);
if (request.getRequestId() == requestId) { // the request we
// were looking for
mRequests.remove(i--);
// remove the request from the watcher (the request not
// necessarily times out before)
if (request.getExpiryDate() > 0) {
mTimeOutWatcher.removeRequest(request);
LogUtils
.logV("RequestQueue.removeRequest() Request expired after ["
+ (System.currentTimeMillis() - request.getAuthTimestamp())
+ "ms]");
} else {
LogUtils
.logV("RequestQueue.removeRequest() Request took ["
+ (System.currentTimeMillis() - request.getAuthTimestamp())
+ "ms]");
}
didRemoveSearchedRequest = true;
} else if ((System.currentTimeMillis() - request.getCreationTimestamp()) > Settings.REMOVE_REQUEST_FROM_QUEUE_MILLIS) { // request
// is older than 15 minutes
mRequests.remove(i--);
ResponseQueue.getInstance().addToResponseQueue(request.getRequestId(), null,
request.mEngineId);
// remove the request from the watcher (the request not
// necessarily times out before)
if (request.getExpiryDate() > 0) {
mTimeOutWatcher.removeRequest(request);
LogUtils
.logV("RequestQueue.removeRequest() Request expired after ["
+ (System.currentTimeMillis() - request.getAuthTimestamp())
+ "ms]");
} else {
LogUtils
.logV("RequestQueue.removeRequest() Request took ["
+ (System.currentTimeMillis() - request.getAuthTimestamp())
+ "ms]");
}
}
}
return didRemoveSearchedRequest;
}
}
/**
* Return the current (i.e. most recently generated) request id.
*
* @return the current request id.
*/
/*
* public synchronized int getCurrentId(){ return mCurrentRequestId; }
*/
/**
* Clear active requests (i.e add dummy response to response queue).
*
* @param rpgOnly
*/
protected void clearActiveRequests(boolean rpgOnly) {
synchronized (QueueManager.getInstance().lock) {
ResponseQueue rQ = ResponseQueue.getInstance();
for (int i = 0; i < mRequests.size(); i++) {
Request request = mRequests.get(i);
if (request.isActive() && (!rQ.responseExists(request.getRequestId()))) {
if (!rpgOnly
|| (rpgOnly && ((request.getAuthenticationType() == Request.USE_RPG) || (request
.getAuthenticationType() == Request.USE_BOTH)))) {
LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request "
+ request.getRequestId());
mRequests.remove(i);
// AA: I added the line below
// remove the request from the watcher (the request not
// necessarily times out before)
if (request.getExpiryDate() > 0) {
mTimeOutWatcher.removeRequest(request);
}
i--;
rQ.addToResponseQueue(request.getRequestId(), null, request.mEngineId);
}
}
}
}
}
/**
* Clears all requests from the queue and puts null responses on the
* response queue to tell the engines that they have been cleared. This
* should be called from the connection thread as soon as it is stopped.
*/
protected void clearAllRequests() {
synchronized (QueueManager.getInstance().lock) {
ResponseQueue responseQueue = ResponseQueue.getInstance();
for (int i = 0; i < mRequests.size(); i++) {
Request request = mRequests.get(i);
LogUtils.logE("RequestQueue.clearActiveRequests() Deleting request "
+ request.getRequestId());
mRequests.remove(i--);
// remove the request from the watcher (the request not
// necessarily times out before)
if (request.getExpiryDate() > 0) {
mTimeOutWatcher.removeRequest(request);
}
responseQueue.addToResponseQueue(request.getRequestId(), null, request.mEngineId);
}
}
}
/**
* Return handle to TimeOutWatcher.
*
* @return handle to TimeOutWatcher.
*/
protected TimeOutWatcher getTimeoutWatcher() {
return mTimeOutWatcher;
}
/**
* Removes all items that are being watched for timeouts
*/
protected void clearTheTimeOuts() {
if (mTimeOutWatcher != null) {
mTimeOutWatcher.kill();
}
}
/**
* Overrides the toString() method of Object and gives detailed infos which
* objects are on the queue and whether they are active or not.
*/
@Override
public String toString() {
if (null == mRequests) {
return "";
}
StringBuffer sb = new StringBuffer("Queue Size: " + mRequests.size()
+ "; Request method-name [isActive]: ");
for (int i = 0; i < mRequests.size(); i++) {
Request request = mRequests.get(i);
if (null == request) {
sb.append("null request");
} else {
sb.append(request.getApiMethodName() + " [" + request.isActive() + "]");
}
if (i < (mRequests.size() - 1)) {
sb.append(", ");
}
}
return sb.toString();
}
}
|
360/360-Engine-for-Android
|
23db66af9581f8619fbeb8c94a8b009349d64983
|
PAND-1546: ContactSyncEgine has wrong processor order during first time sync
|
diff --git a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
index 3b661da..a450b4d 100644
--- a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
+++ b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
@@ -717,1013 +717,1011 @@ public class ContactSyncEngine extends BaseEngine implements IContactSyncCallbac
if (mRemoveUserData) {
mFirstTimeSyncStarted = false;
mFirstTimeSyncComplete = false;
mFirstTimeNativeSyncComplete = false;
mRemoveUserData = false;
super.onReset();
}
return;
}
}
if (processTimeout()) {
return;
}
if (isUiRequestOutstanding()) {
mActiveUiRequestBackup = mActiveUiRequest;
if (processUiQueue()) {
return;
}
}
if (isCommsResponseOutstanding() && processCommsInQueue()) {
return;
}
if (readyToStartServerSync()) {
if (mThumbnailSyncRequired) {
startThumbnailSync();
return;
}
if (mFullSyncRequired) {
startFullSync();
return;
}
if (mServerSyncRequired) {
startServerSync();
return;
}
}
if (mNativeFetchSyncRequired && readyToStartFetchNativeSync()) {
startFetchNativeSync();
return;
}
if (mNativeUpdateSyncRequired && readyToStartUpdateNativeSync()) {
startUpdateNativeSync();
return;
}
}
/**
* Called by base class when a contact sync UI request has been completed.
* Not currently used.
*/
@Override
protected void onRequestComplete() {
}
/**
* Called by base class when a timeout has been completed. If there is an
* active processor the timeout event will be passed to it, otherwise the
* engine will check if it needs to schedule a new sync and set the next
* pending timeout.
*/
@Override
protected void onTimeoutEvent() {
if (mActiveProcessor != null) {
mActiveProcessor.onTimeoutEvent();
} else {
startSyncIfRequired();
setTimeoutIfRequired();
}
}
/**
* Based on current timeout values schedules a new sync if required.
*/
private void startSyncIfRequired() {
if (mFirstTimeSyncStarted && !mFirstTimeSyncComplete) {
mFullSyncRequired = true;
mFullSyncRetryCount = 0;
}
long currentTimeMs = System.currentTimeMillis();
if (mServerSyncTimeout != null && mServerSyncTimeout.longValue() < currentTimeMs) {
mServerSyncRequired = true;
mServerSyncTimeout = null;
} else if (mFetchNativeSyncTimeout != null
&& mFetchNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeFetchSyncRequired = true;
mFetchNativeSyncTimeout = null;
} else if (mUpdateNativeSyncTimeout != null
&& mUpdateNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeUpdateSyncRequired = true;
mUpdateNativeSyncTimeout = null;
}
}
/**
* Called when a response to a request or a push message is received from
* the server. Push messages are processed by the engine, responses are
* passed to the active processor.
*
* @param resp Response or push message received
*/
@Override
protected void processCommsResponse(Response resp) {
if (processPushEvent(resp)) {
return;
}
if (resp.mDataTypes != null && resp.mDataTypes.size() > 0) {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = " + resp.mDataTypes.get(0).name());
} else {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = NULL");
}
if (mActiveProcessor != null) {
mActiveProcessor.processCommsResponse(resp);
}
}
/**
* Determines if a given response is a push message and processes in this
* case TODO: we need the check for Me Profile be migrated to he new engine
*
* @param resp Response to check and process
* @return true if the response was processed
*/
private boolean processPushEvent(Response resp) {
if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) {
return false;
}
BaseDataType dataType = resp.mDataTypes.get(0);
if ((dataType == null) || !dataType.name().equals("PushEvent")) {
return false;
}
PushEvent pushEvent = (PushEvent)dataType;
LogUtils.logV("Push Event Type = " + pushEvent.mMessageType);
switch (pushEvent.mMessageType) {
case CONTACTS_CHANGE:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - Contacts changed push message received");
mServerSyncRequired = true;
EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); // fetch
// the
// newest
// groups
mEventCallback.kickWorkerThread();
break;
case SYSTEM_NOTIFICATION:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - System notification push message received");
break;
default:
// do nothing.
break;
}
return true;
}
/**
* Called by base class to process a NOWPLUSSYNC UI request. This will be
* called to process a full sync or server sync UI request.
*
* @param requestId ID of the request to process, only
* ServiceUiRequest.NOWPLUSSYNC is currently supported.
* @param data Type is determined by request ID, in case of NOWPLUSSYNC this
* is a flag which determines if a full sync is required (true =
* full sync, false = server sync).
*/
@Override
protected void processUiRequest(ServiceUiRequest requestId, Object data) {
switch (requestId) {
case NOWPLUSSYNC:
final SyncParams params = (SyncParams)data;
if (params.isFull) {
// delayed full sync is not supported currently, start it
// immediately
clearCurrentSyncAndPatchBaseEngine();
mFullSyncRetryCount = 0;
startFullSync();
} else {
if (params.delay <= 0) {
clearCurrentSyncAndPatchBaseEngine();
if (readyToStartServerSync()) {
startServerSync();
} else {
mServerSyncRequired = true;
}
} else {
startServerContactSyncTimer(params.delay);
}
}
break;
default:
// do nothing.
break;
}
}
/**
* Called by the run function when the {@link #mCancelSync} flag is set to
* true. Cancels the active processor and completes the current UI request.
*/
private void cancelSync() {
if (mActiveProcessor != null) {
mActiveProcessor.cancel();
mActiveProcessor = null;
}
completeSync(ServiceStatus.USER_CANCELLED);
}
/**
* Clears the current sync and make sure that if we cancel a previous sync,
* it doesn't notify a wrong UI request. TODO: Find another way to not have
* to hack the BaseEngine!
*/
private void clearCurrentSyncAndPatchBaseEngine() {
// Cancel background sync
if (mActiveProcessor != null) {
// the mActiveUiRequest is already the new one so if
// onCompleteUiRequest(Error) is called,
// this will reset it to null even if we didn't start to process it.
ServiceUiRequest newActiveUiRequest = mActiveUiRequest;
mActiveUiRequest = mActiveUiRequestBackup;
mActiveProcessor.cancel();
// restore the active UI request...
mActiveUiRequest = newActiveUiRequest;
mActiveProcessor = null;
}
newState(State.IDLE);
}
/**
* Checks if a server sync can be started based on network conditions and
* engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartServerSync() {
if (!Settings.ENABLE_SERVER_CONTACT_SYNC) {
return false;
}
if (!EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete()) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE || NetworkAgent.getAgentState() != AgentState.CONNECTED) {
return false;
}
return true;
}
/**
* Checks if a fetch native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartFetchNativeSync() {
if (!Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Checks if a update native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartUpdateNativeSync() {
if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Starts a full sync. If the native contacts haven't yet been fetched then
* a first time sync will be started, otherwise will start a normal full
* sync. Full syncs are always initiated from the UI (via UI request).
*/
public void startFullSync() {
mFailureList = "";
mDatabaseChanged = false;
setFirstTimeSyncStarted(true);
mServerSyncTimeout = null;
mFullSyncRequired = false;
if (mFirstTimeNativeSyncComplete) {
LogUtils.logI("ContactSyncEngine.startFullSync - user triggered sync");
mMode = Mode.FULL_SYNC;
nextTaskFullSyncNormal();
} else {
LogUtils.logI("ContactSyncEngine.startFullSync - first time sync");
mMode = Mode.FULL_SYNC_FIRST_TIME;
nextTaskFullSyncFirstTime();
}
}
/**
* Starts a server sync. This will only sync contacts with the server and
* will not include the me profile. Thumbnails are not fetched as part of
* this sync, but will be fetched as part of a background sync afterwards.
*/
private void startServerSync() {
mServerSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.SERVER_SYNC;
mServerSyncTimeout = null;
setTimeoutIfRequired();
nextTaskServerSync();
}
/**
* Starts a background thumbnail sync
*/
private void startThumbnailSync() {
mThumbnailSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.THUMBNAIL_SYNC;
nextTaskThumbnailSync();
}
/**
* Starts a background fetch native contacts sync
*/
private void startFetchNativeSync() {
mNativeFetchSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.FETCH_NATIVE_SYNC;
mFetchNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskFetchNativeContacts();
}
/**
* Starts a background update native contacts sync
*/
private void startUpdateNativeSync() {
mNativeUpdateSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.UPDATE_NATIVE_SYNC;
mUpdateNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskUpdateNativeContacts();
}
/**
* Helper function to start the fetch native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startFetchNativeContacts() {
if (Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
newState(State.FETCHING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.FETCH_NATIVE_CONTACTS, this,
mDb, mContext, mCr));
return true;
}
return false;
}
/**
* Helper function to start the update native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUpdateNativeContacts() {
if (Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
newState(State.UPDATING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPDATE_NATIVE_CONTACTS, this,
mDb, null, mCr));
return true;
}
return false;
}
/**
* Helper function to start the download server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.FETCHING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.DOWNLOAD_SERVER_CONTACTS,
this, mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the upload server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUploadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.UPDATING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPLOAD_SERVER_CONTACTS, this,
mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the download thumbnails processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerThumbnails() {
if (Settings.ENABLE_THUMBNAIL_SYNC) {
ThumbnailHandler.getInstance().downloadContactThumbnails();
return true;
}
return false;
}
/**
* Called by a processor when it has completed. Will move to the next task.
* When the active contact sync has totally finished, will complete any
* pending UI request.
*
* @param status Status of the sync from the processor, any error codes will
* stop the sync.
* @param failureList Contains a list of sync failure information which can
* be used as a summary at the end. Otherwise should be an empty
* string.
* @param data Any processor specific data to pass back to the engine. Not
* currently used.
*/
@Override
public void onProcessorComplete(ServiceStatus status, String failureList, Object data) {
if (mState == State.IDLE) {
return;
}
if (mActiveProcessor != null) {
mActiveProcessor.onComplete();
}
mActiveProcessor = null;
mFailureList += failureList;
if (status != ServiceStatus.SUCCESS) {
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Failed during " + mState
+ " with error " + status);
completeSync(status);
return;
}
if (mDbChangedByProcessor) {
switch (mState) {
case FETCHING_NATIVE_CONTACTS:
mServerSyncRequired = true;
break;
case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mNativeUpdateSyncRequired = true;
break;
default:
// Do nothing.
break;
}
}
switch (mMode) {
case FULL_SYNC_FIRST_TIME:
nextTaskFullSyncFirstTime();
break;
case FULL_SYNC:
nextTaskFullSyncNormal();
break;
case SERVER_SYNC:
nextTaskServerSync();
break;
case FETCH_NATIVE_SYNC:
nextTaskFetchNativeContacts();
break;
case UPDATE_NATIVE_SYNC:
nextTaskUpdateNativeContacts();
break;
case THUMBNAIL_SYNC:
nextTaskThumbnailSync();
break;
default:
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Unexpected mode: " + mMode);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync first time mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncFirstTime() {
+
switch (mState) {
case IDLE:
- if (startDownloadServerContacts()) {
- return;
- }
- // Fall through
- case FETCHING_SERVER_CONTACTS:
- if (startFetchNativeContacts()) {
+ if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
setFirstTimeNativeSyncComplete(true);
if (startUploadServerContacts()) {
- return;
+ return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
- // force a thumbnail sync in case nothing in the database
- // changed but we still have failing
- // thumbnails that we should retry to download
+ if (startDownloadServerContacts()) {
+ return;
+ }
+ // Fall through
+ case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncFirstTime - Unexpected state: "
- + mState);
+ + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync normal mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncNormal() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncNormal - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the fetch native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFetchNativeContacts() {
switch (mState) {
case IDLE:
if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFetchNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the update native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskUpdateNativeContacts() {
switch (mState) {
case IDLE:
if (startUpdateNativeContacts()) {
return;
}
completeSync(ServiceStatus.SUCCESS);
return;
// Fall through
case UPDATING_NATIVE_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskUpdateNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the server sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskServerSync() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskServerSync - Unexpected state: " + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the thumbnail sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskThumbnailSync() {
switch (mState) {
case IDLE:
if (startDownloadServerThumbnails()) {
return;
}
default:
LogUtils.logE("ContactSyncEngine.nextTaskThumbnailSync - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Changes the state of the engine and informs the observers.
*
* @param newState The new state
*/
private void newState(State newState) {
State oldState = mState;
synchronized (mMutex) {
if (newState == mState) {
return;
}
mState = newState;
}
LogUtils.logV("ContactSyncEngine.newState: " + oldState + " -> " + mState);
fireStateChangeEvent(mMode, oldState, mState);
}
/**
* Called when the current mode has finished all the sync tasks. Completes
* the UI request if one is pending, sends an event to the observer and a
* database change event if necessary.
*
* @param status The overall status of the contact sync.
*/
private void completeSync(ServiceStatus status) {
if (mState == State.IDLE) {
return;
}
if (mDatabaseChanged) {
LogUtils.logD("ContactSyncEngine.completeSync - Firing Db changed event");
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
mDatabaseChanged = false;
}
mActiveProcessor = null;
newState(State.IDLE);
mMode = Mode.NONE;
completeUiRequest(status, mFailureList);
mCache.setSyncStatus(new SyncStatus(status));
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mFirstTimeSyncComplete) {
fireSyncCompleteEvent(status);
}
if (ServiceStatus.SUCCESS == status) {
startSyncIfRequired();
} else {
setTimeout(SYNC_ERROR_WAIT_TIMEOUT);
}
mLastStatus = status;
setTimeoutIfRequired();
}
/**
* Sets the current timeout to the next pending timer and kicks the engine
* if necessary.
*/
private synchronized void setTimeoutIfRequired() {
Long initTimeout = mCurrentTimeout;
if (mCurrentTimeout == null
|| (mServerSyncTimeout != null && mServerSyncTimeout.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mServerSyncTimeout;
}
if (mCurrentTimeout == null
|| (mFetchNativeSyncTimeout != null && mFetchNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mFetchNativeSyncTimeout;
}
if (mCurrentTimeout == null
|| (mUpdateNativeSyncTimeout != null && mUpdateNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mUpdateNativeSyncTimeout;
}
if (mCurrentTimeout != null && !mCurrentTimeout.equals(initTimeout)) {
mEventCallback.kickWorkerThread();
}
}
/**
* Called by the active processor to indicate that the NowPlus database has
* changed.
*/
@Override
public void onDatabaseChanged() {
mDatabaseChanged = true;
mDbChangedByProcessor = true;
final long currentTime = System.nanoTime();
if (mLastDbUpdateTime == null
|| mLastDbUpdateTime.longValue() + UI_REFRESH_WAIT_TIME_NANO < currentTime) {
LogUtils.logD("ContactSyncEngine.onDatabaseChanged - Updating UI...");
mDatabaseChanged = false;
mLastDbUpdateTime = currentTime;
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
}
}
/**
* Used by processors to fetch this engine. The BaseEngine reference is
* needed to send requests to the server.
*
* @return The BaseEngine reference of this engine.
*/
@Override
public BaseEngine getEngine() {
return this;
}
/**
* Used by active processor to set a timeout.
*
* @param timeout Timeout value based on current time in milliseconds
*/
@Override
public void setTimeout(long timeout) {
super.setTimeout(timeout);
}
/**
* Used by active processor to set the current progress.
*
* @param SyncStatus Status of the processor, must not be NULL.
* @throws InvalidParameterException when SyncStatus is NULL.
*/
@Override
public void setSyncStatus(final SyncStatus syncStatus) {
if (syncStatus == null) {
throw new InvalidParameterException(
"ContactSyncEngine.setSyncStatus() SyncStatus cannot be NULL");
}
mCache.setSyncStatus(syncStatus);
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mState != State.IDLE && syncStatus.getProgress() != mCurrentProgressPercent) {
mCurrentProgressPercent = syncStatus.getProgress();
LogUtils.logI("ContactSyncEngine: Task " + mState + " is " + syncStatus.getProgress()
+ "% complete");
fireProgressEvent(mState, syncStatus.getProgress());
}
}
/**
* Called by active processor when issuing a request to store the request id
* in the base engine class.
*/
@Override
public void setActiveRequestId(int reqId) {
setReqId(reqId);
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncStarted} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been started. The flag is never set to false again by the
* engine, it will be only set to false when a remove user data
* is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncStarted(boolean value) {
if (mFirstTimeSyncStarted == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncStarted(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncStarted = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been completed. The flag is never set to false again by
* the engine, it will be only set to false when a remove user
* data is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncComplete = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeNativeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that the native fetch
* part of the first time sync has been completed. The flag is
* never set to false again by the engine, it will be only set to
* false when a remove user data is done (and the database is
* deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeNativeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeNativeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeNativeSyncComplete = value;
}
}
return status;
}
/**
* Called when a database change event is received from the DatabaseHelper.
* Only internal database change events are processed, external change
* events are generated by the contact sync engine.
*
* @param msg The message indicating the type of event
*/
private void processDbMessage(Message message) {
final ServiceUiRequest event = ServiceUiRequest.getUiEvent(message.what);
switch (event) {
case DATABASE_CHANGED_EVENT:
if (message.arg1 == DatabaseHelper.DatabaseChangeType.CONTACTS.ordinal()
&& message.arg2 == 0) {
LogUtils.logV("ContactSyncEngine.processDbMessage - Contacts have changed");
// startMeProfileSyncTimer();
startServerContactSyncTimer(SERVER_CONTACT_SYNC_TIMEOUT_MS);
startUpdateNativeContactSyncTimer();
}
break;
default:
// Do nothing.
break;
}
}
/**
* Notifies observers when a state or mode change occurs.
*
* @param mode Current mode
* @param previousState State before the change
* @param newState State after the change.
*/
private void fireStateChangeEvent(Mode mode, State previousState, State newState) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onContactSyncStateChange(mode, previousState, newState);
}
if (Settings.ENABLED_DATABASE_TRACE) {
// DatabaseHelper.trace(false, "State newState[" + newState + "]" +
// mDb.copyDatabaseToSd(""));
}
}
/**
* Notifies observers when a contact sync complete event occurs.
*
* @param status SUCCESS or a suitable error code
*/
private void fireSyncCompleteEvent(ServiceStatus status) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onSyncComplete(status);
}
}
/**
* Notifies observers when the progress value changes for the current sync.
*
* @param currentState Current sync task being processed
* @param percent Progress of task (between 0 and 100 percent)
*/
private void fireProgressEvent(State currentState, int percent) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onProgressEvent(currentState, percent);
}
}
/**
* Called by framework to warn the engine that a remove user data is about
* to start. Sets flags and kicks the engine.
*/
@Override
public void onReset() {
synchronized (this) {
mCancelSync = true;
mRemoveUserData = true;
}
mEventCallback.kickWorkerThread();
}
/**
* @see NativeContactsApi.ContactsObserver#onChange()
*/
@Override
public void onChange() {
LogUtils.logD("ContactSyncEngine.onChange(): changes detected on native side.");
// changes detected on native side, start the timer for the
// FetchNativeContacts processor.
startFetchNativeContactSyncTimer();
}
}
diff --git a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
index cded745..889d1a9 100644
--- a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
+++ b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
@@ -1,190 +1,190 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.contactsync;
import com.vodafone360.people.service.ServiceStatus;
/**
* In memory store for the current state of the Contacts sync engine.
*/
public class SyncStatus {
/** Sync tasks, each of which corresponds to a specific processor. **/
public enum Task {
- /** DownloadServerContacts is processing. */
- DOWNLOAD_SERVER_CONTACTS,
/** FetchNativeContacts is processing. */
FETCH_NATIVE_CONTACTS,
/** UploadServerContacts is processing. */
UPDATE_SERVER_CONTACTS,
+ /** DownloadServerContacts is processing. */
+ DOWNLOAD_SERVER_CONTACTS,
/** Last element is used to determine the size of the ENUM. **/
UNKNOWN
}
/** Sync task status. **/
public enum TaskStatus {
/** Sent X of Y contacts. */
SENT_CONTACTS,
/** Received X of Y contacts. */
RECEIVED_CONTACTS,
/** Sent X of Y changes. */
SENT_CHANGES,
/** Do not show task status (i.e. leave blank). */
NONE
}
/** ServiceStatus of sync outcome. **/
private ServiceStatus mServiceStatus;
/** Percentage of sync progress in current task (e.g. 53). **/
private int mProgress;
/** Current contact name (e.g. John Doe). **/
private String mTextContact;
/** Current task (e.g. Uploading server contacts). **/
private Task mTask;
/** Current task status (e.g. Sent 25 of 500 contacts). **/
private TaskStatus mTaskStatus;
/** Current task done (e.g. Sent X of 500 contacts). **/
private int mTaskStatusDone;
/** Current task total (e.g. Sent 25 of X contacts). **/
private int mTaskStatusTotal;
/**
* Construct with only the ServiceStatus of the Contacts sync engine.
*
* @param serviceStatus ServiceStatus of sync outcome.
*/
protected SyncStatus(final ServiceStatus serviceStatus) {
mServiceStatus = serviceStatus;
}
/**
* Construct with the current state of the Contacts sync engine.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
* @param taskStatus Current task status (e.g. Sent 25 of 500 contacts).
* @param taskStatusDone Current task done (e.g. Sent X of 500 contacts).
* @param taskStatusTotal Current task total (e.g. Sent 25 of X contacts).
*/
public SyncStatus(final int progress,
final String textContact, final Task task,
final TaskStatus taskStatus, final int taskStatusDone,
final int taskStatusTotal) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = taskStatus;
mTaskStatusDone = taskStatusDone;
mTaskStatusTotal = taskStatusTotal;
}
/**
* Construct with the current state of the Contacts sync engine, with the
* task status set to TaskStatus.NONE.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
*/
public SyncStatus(final int progress, final String textContact,
final Task task) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = TaskStatus.NONE;
mTaskStatusDone = 0;
mTaskStatusTotal = 0;
}
/**
* Gets the ServiceStatus of sync outcome.
*
* @return Sync outcome as a ServiceStatus object.
*/
public final ServiceStatus getServiceStatus() {
return mServiceStatus;
}
/**
* Get the current sync progress percentage for the current task.
*
* @return Current sync progress percentage.
*/
public final int getProgress() {
return mProgress;
}
/**
* Get the current contact name (e.g. John Doe).
*
* @return Current contact name.
*/
public final String getTextContact() {
return mTextContact;
}
/**
* Get the current task (e.g. Uploading server contacts)
*
* @return Current task.
*/
public final Task getTask() {
return mTask;
}
/**
* Get the current task status (e.g. Sent 25 of 500 contacts).
*
* @return Current task status.
*/
public final TaskStatus getTaskStatus() {
return mTaskStatus;
}
/**
* Get the current task done (e.g. Sent X of 500 contacts).
*
* @return Current task done.
*/
public final int getTaskStatusDone() {
return mTaskStatusDone;
}
/**
* Get the current task total (e.g. Sent 25 of X contacts).
*
* @return Current task total.
*/
public final int getTaskStatusTotal() {
return mTaskStatusTotal;
}
}
\ No newline at end of file
|
360/360-Engine-for-Android
|
57322df38c1212d1a49bb0ad3ec27c67dc03a610
|
Upgrade test project to target=android-8
|
diff --git a/tests/.classpath b/tests/.classpath
new file mode 100644
index 0000000..ccff76e
--- /dev/null
+++ b/tests/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/360-Engine-for-Android"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
|
360/360-Engine-for-Android
|
59665e27c044b206b588ebc63c696f8857da8921
|
Upgrade test project to target=android-8
|
diff --git a/tests/default.properties b/tests/default.properties
new file mode 100644
index 0000000..c5d5335
--- /dev/null
+++ b/tests/default.properties
@@ -0,0 +1,14 @@
+# This file is automatically generated by Android Tools.
+# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
+#
+# This file must be checked in Version Control Systems.
+#
+# To customize properties used by the Ant build system use,
+# "build.properties", and override values to adapt the script to your
+# project structure.
+
+# Indicates whether an apk should be generated for each density.
+split.density=false
+# Project target.
+target=android-8
+apk-configurations=
|
360/360-Engine-for-Android
|
be57bb178539433f2984dd1a51c3c35a294abfc2
|
Fixed JUnit tests
|
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
index dbc55f4..ad94b08 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
@@ -1,750 +1,750 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.database.tables.ContactDetailsTable.NativeIdInfo;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactDetailsTableTest extends NowPlusTableTestCase {
final TestModule mTestModule = new TestModule();
private int mTestStep = 0;
private static int NUM_OF_CONTACTS = 3;
private static final int MAX_MODIFY_NOWPLUS_DETAILS_COUNT = 100;
private static String LOG_TAG = "NowPlusContactsTableTest";
public NowPlusContactDetailsTableTest() {
super();
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
private void startSubTest(String function, String description) {
Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description);
mTestStep++;
}
private void createTable() {
try {
ContactDetailsTable.create(mTestDatabase.getWritableDatabase());
} catch (SQLException e) {
fail("An exception occurred when creating the table: " + e);
}
}
@SmallTest
public void testCreate() {
Log.i(LOG_TAG, "***** EXECUTING testCreate *****");
final String fnName = "testCreate";
mTestStep = 1;
startSubTest(fnName, "Creating table");
createTable();
Log.i(LOG_TAG, "*************************************");
Log.i(LOG_TAG, "testCreate has completed successfully");
Log.i(LOG_TAG, "**************************************");
}
@MediumTest
public void testAddFetchContactDetail() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
// try to add a detail before creating a table
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to fetch detail before creating a table
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
TestModule.generateRandomLong(), readableDb);
assertEquals(null, fetchedDetail);
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is null
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
detail.localContactID = TestModule.generateRandomLong();
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testDeleteContactDetail() {
final String fnName = "testDeleteContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Deltes a contact detail from the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
// try to delete contact by contact id before creating a table
ServiceStatus status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
// try to delete contact by detail id before creating a table
assertFalse(ContactDetailsTable.deleteDetailByDetailId(TestModule
.generateRandomLong(), writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// delete previously added contact
status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(null, fetchedDetail);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// try to delete contact by detail id
assertTrue(ContactDetailsTable.deleteDetailByDetailId(
detail.localDetailID, writeableDb));
// fetch deleted detail (should be null)
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(null, fetchedDetail);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testModifyContactDetail() {
final String fnName = "testModifyContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Modifies a contact detail in the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
Long serverId = TestModule.generateRandomLong();
// try to modify detail before creating a table
ServiceStatus status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
- assertFalse(ContactDetailsTable.modifyDetailServerId(TestModule
+ assertFalse(ContactDetailsTable.syncSetServerId(TestModule
.generateRandomLong(), serverId, writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to modify detail before adding it
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
mTestModule.modifyDummyDetailsData(detail);
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch modified detail
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
- assertTrue(ContactDetailsTable.modifyDetailServerId(
+ assertTrue(ContactDetailsTable.syncSetServerId(
detail.localDetailID, serverId, writeableDb));
ContactDetail modServIdDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(serverId,modServIdDetail.unique_id);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testContactsMatch() {
final String fnName = "testContactsMatch";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates doContactsMatch method");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
Contact contact = mTestModule.createDummyContactData();
contact.localContactID = TestModule.generateRandomLong();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> detailIdList = new ArrayList<NativeIdInfo>();
assertFalse(ContactDetailsTable.doContactsMatch(contact,
contact.localContactID, detailIdList, readableDb));
ServiceStatus status;
for (ContactDetail cd : contact.details) {
cd.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(cd, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
}
// assertTrue(ContactDetailsTable.doContactsMatch(contact,
// contact.localContactID, detailIdList, readableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfetchPreferredDetail() {
final String fnName = "testPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail preferredDetail = new ContactDetail();
preferredDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
preferredDetail.setTel("07967 654321", ContactDetail.DetailKeyTypes.CELL);
preferredDetail.localContactID = detail.localContactID;
preferredDetail.order = 0;
status = ContactDetailsTable.addContactDetail(preferredDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail altDetail = new ContactDetail();
assertTrue(ContactDetailsTable.fetchPreferredDetail(preferredDetail.localContactID.longValue(),
ContactDetail.DetailKeys.VCARD_PHONE.ordinal(), altDetail, readableDb));
// detail is preferred so should have the same fields
assertEquals(preferredDetail.localDetailID, altDetail.localDetailID);
assertEquals(preferredDetail.keyType, altDetail.keyType);
assertEquals(preferredDetail.value, altDetail.value);
assertEquals(preferredDetail.order, altDetail.order);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfixPreferredDetail() {
final String fnName = "testfixPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
status = ContactDetailsTable.fixPreferredValues(detail.localContactID,
writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(0, fetchedDetail.order.intValue()); // detail is now preferred
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFetchContactInfo() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = TestModule.generateRandomLong();
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
ServiceStatus status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
nameDetail.localContactID = phoneDetail.localContactID;
status = ContactDetailsTable.addContactDetail(nameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchName = new ContactDetail();
ContactDetail fetchPhone = new ContactDetail();
status = ContactDetailsTable.fetchContactInfo(number, fetchPhone, fetchName, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchPhone));
assertTrue(DatabaseHelper.doDetailsMatch(nameDetail, fetchName));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFindNativeContact() {
final String fnName = "testFindNativeContact";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create contact
Contact contact = new Contact();
contact.synctophone = true;
// add contact to to the ContactsTable
ContactsTable.create(mTestDatabase.getWritableDatabase());
ServiceStatus status = ContactsTable.addContact(contact,readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// add contact to ContactSummaryTable
ContactSummaryTable.create(mTestDatabase.getWritableDatabase());
status = ContactSummaryTable.addContact(contact, readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(emailDetail);
assertTrue(ContactDetailsTable.findNativeContact(contact, writeableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFetchContactDetailsForNative() {
final String fnName = "testFetchContactDetailsForNative";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
Contact contact = new Contact();
contact.localContactID = TestModule.generateRandomLong();
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
nicknameDetail.nativeContactId = TestModule.generateRandomInt();
ServiceStatus status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
List<ContactDetail> addedDetails = new ArrayList<ContactDetail>();
addedDetails.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
//phoneDetail.nativeContactId = mTestModule.GenerateRandomInt();
phoneDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
//emailDetail.nativeContactId = mTestModule.GenerateRandomInt();
emailDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(emailDetail);
ContactDetail.DetailKeys[] keyList = {
ContactDetail.DetailKeys.VCARD_NICKNAME,
ContactDetail.DetailKeys.VCARD_PHONE,
ContactDetail.DetailKeys.VCARD_EMAIL };
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
assertTrue(ContactDetailsTable.fetchContactDetailsForNative(detailList, keyList, false, 0,
MAX_MODIFY_NOWPLUS_DETAILS_COUNT, readableDb));
for (int i = 0; i < detailList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailList.get(i),
addedDetails.get(i)));
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFindLocalContactIdByKey() {
final String fnName = "testFindLocalContactIdByKey";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create local detail
ContactDetail localDetail = new ContactDetail();
localDetail.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail.nativeContactId = TestModule.generateRandomInt();
localDetail.nativeDetailId = TestModule.generateRandomInt();
localDetail.nativeVal1 = "nativeVal1";
localDetail.nativeVal2 = "nativeVal2";
localDetail.nativeVal3 = "nativeVal3";
localDetail.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
localDetail.alt = "google";
String imAddress = "[email protected]";
localDetail.setValue(imAddress, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status = ContactDetailsTable.addContactDetail(localDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create local detail
ContactDetail localDetail2 = new ContactDetail();
localDetail2.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail2.nativeContactId = TestModule.generateRandomInt();
localDetail2.nativeDetailId = TestModule.generateRandomInt();
localDetail2.nativeVal1 = "nativeVal1";
localDetail2.nativeVal2 = "nativeVal2";
localDetail2.nativeVal3 = "nativeVal3";
localDetail2.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
String imAddress2 = "[email protected]";
localDetail2.setValue(imAddress2, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status2 = ContactDetailsTable.addContactDetail(localDetail2, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status2);
long result = ContactDetailsTable.findLocalContactIdByKey("google", "[email protected]", ContactDetail.DetailKeys.VCARD_IMADDRESS, readableDb);
assertTrue("The contact ids don't match: expected=" + localDetail.localContactID + ", actual="+ result,result == localDetail.localContactID);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testsyncSetServerIds() {
final String fnName = "testsyncSetServerIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetServerIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ServerIdInfo> detailServerIdList = new ArrayList<ServerIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
ServerIdInfo serverInfo = new ServerIdInfo();
serverInfo.localId = detail.localDetailID;
serverInfo.serverId = TestModule.generateRandomLong();
detailServerIdList.add(serverInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetServerIds(
detailServerIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detailsList.get(i).localDetailID, readableDb);
assertNotNull(fetchedDetail);
assertEquals(detailServerIdList.get(i).serverId, fetchedDetail.unique_id);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncNativeIds
*/
public void testSyncSetNativeIds() {
final String fnName = "testSyncSetNativeIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetNativeIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> nativeIdList = new ArrayList<NativeIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
NativeIdInfo nativeIdInfo = new NativeIdInfo();
nativeIdInfo.nativeContactId = TestModule.generateRandomInt();
nativeIdInfo.localId = detail.localDetailID;
nativeIdList.add(nativeIdInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetNativeIds(
nativeIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
nativeIdList.get(i).localId, readableDb);
assertNotNull(fetchedDetail);
assertEquals(nativeIdList.get(i).nativeContactId, fetchedDetail.nativeContactId);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchContactChanges
*/
public void testSyncServerFetchContactChanges() {
final String fnName = "testSyncServerFetchContactChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
detailsList.add(detail);
}
Cursor cursor = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, true);
assertEquals(NUM_OF_CONTACTS, cursor.getCount());
Cursor cursorOldContacts = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, false);
assertEquals(0, cursorOldContacts.getCount());
cursorOldContacts.close();
List<Contact> contactList = new ArrayList<Contact>();
ContactDetailsTable.syncServerGetNextNewContactDetails(cursor, contactList, NUM_OF_CONTACTS);
for (int i = 0; i < contactList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailsList.get(i),
contactList.get(i).details.get(0)));
}
cursor.close();
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchNoOfChanges
*/
public void testSyncServerFetchNoOfChanges() {
final String fnName = "testSyncServerFetchNoOfChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
index adac32c..ffd80da 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
@@ -23,536 +23,536 @@
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
import com.vodafone360.people.MainApplication;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.datatypes.ContactSummary;
import com.vodafone360.people.engine.meprofile.SyncMeDbUtils;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactsTest extends ApplicationTestCase<MainApplication> {
private static String LOG_TAG = "NowPlusDatabaseTest";
final static int WAIT_EVENT_TIMEOUT_MS = 30000;
final static int NUM_OF_CONTACTS = 3;
private static MainApplication mApplication = null;
private static DatabaseHelper mDatabaseHelper = null;
final TestModule mTestModule = new TestModule();
private DbTestUtility mTestUtility;
public NowPlusContactsTest() {
super(MainApplication.class);
}
private boolean initialise() {
mTestUtility = new DbTestUtility(getContext());
createApplication();
mApplication = getApplication();
if(mApplication == null){
Log.e(LOG_TAG, "Unable to create main application");
return false;
}
mDatabaseHelper = mApplication.getDatabase();
if (mDatabaseHelper.getReadableDatabase() == null) {
return false;
}
mTestUtility.startEventWatcher(mDatabaseHelper);
return true;
}
private void shutdown() {
mTestUtility.stopEventWatcher();
}
/***
* Check if contact detail was added to ContactSummary.
* If contact detail is a name check if it's name in formatted state
* is the same as contact summary formatted name.
* @param cd ContactDetail
* @return boolean true if ContactDetail is in ContactSummaryTable
*/
private boolean isContactDetailInSummary(ContactDetail cd) {
//boolean result = true;
ContactSummary cs = new ContactSummary();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ServiceStatus status = ContactSummaryTable.fetchSummaryItem(
cd.localContactID, cs, db);
if (status != ServiceStatus.SUCCESS) {
return false;
} else if (ContactDetail.DetailKeys.VCARD_NAME == cd.key
&& !cd.getName().toString().equals(cs.formattedName)) {
// if ContactDetail name is different then ContactSummary name
return false;
} else {
return true;
}
}
@SmallTest
@Suppress
public void testMeProfiles() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact meProfile = mTestModule.createDummyContactData();
// assertFalse(mDatabaseHelper.getMeProfileChanged());
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(SyncMeDbUtils.getMeProfileLocalContactId(mDatabaseHelper), meProfile.localContactID);
Contact fetchedMe = new Contact();
status = SyncMeDbUtils.fetchMeProfile(mDatabaseHelper,fetchedMe);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(fetchedMe, meProfile));
// Modify me Profile
Contact meProfile2 = mTestModule.createDummyContactData();
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile2);
assertEquals(ServiceStatus.SUCCESS, status);
// assertTrue(mDatabaseHelper.getMeProfileChanged());
shutdown();
}
@SmallTest
public void testAddContactToGroup() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long groupId = 1L;
status = mDatabaseHelper.addContactToGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.deleteContactFromGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.ERROR_NOT_READY, status);
shutdown();
}
@SmallTest
public void testSyncSetServerIds() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long serverId = addedContact.localContactID + 1;
long userId = addedContact.localContactID + 2;
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = addedContact.localContactID;
info.serverId = serverId;
info.userId = userId;
serverIdList.add(info);
status = ContactsTable.syncSetServerIds(serverIdList, null, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
addedContact.contactID = serverId;
addedContact.userID = userId;
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContactByServerId(serverId, fetchedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, fetchedContact));
shutdown();
}
@SmallTest
@Suppress
public void testAddContactDetail() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
status = mDatabaseHelper.addContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchedDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
assertTrue(!DatabaseHelper.hasDetailChanged(detail, fetchedDetail));
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.deleteAllGroups());
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = fetchedDetail.localDetailID;
info.serverId = fetchedDetail.localDetailID + 1;
serverIdList.add(info);
status = ContactDetailsTable.syncSetServerIds(serverIdList, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(info.serverId, fetchedDetail.unique_id);
shutdown();
}
@MediumTest
public void testAddModifyContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddModifyContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add/modify details contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Modify contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(isContactDetailInSummary(detail));
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContactsDetails() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContactsDetails *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts details)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts detatils and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
status = mDatabaseHelper.deleteContactDetail(detail.localDetailID);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if deletion works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
// check if deletion works good
status = mDatabaseHelper.deleteContact(inputContacts[i].localContactID);
assertEquals(ServiceStatus.SUCCESS, status);
Contact removedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, removedContact);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); // contact was deleted so it shouldn't be found
}
shutdown();
}
@SmallTest
public void testSyncAddContactDetailList() {
Log.i(LOG_TAG, "***** EXECUTING testSyncAddContactDetailList *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(
WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail cd = new ContactDetail();
mTestModule.createDummyDetailsData(cd);
cd.localContactID = addedContact.localContactID;
cd.nativeContactId = TestModule.generateRandomInt();
cd.nativeDetailId = TestModule.generateRandomInt();
cd.nativeVal1 = TestModule.generateRandomString();
cd.nativeVal2 = TestModule.generateRandomString();
cd.nativeVal3 = TestModule.generateRandomString();
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
detailList.add(cd);
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.syncAddContactDetailList(detailList, false, false));
Contact modifiedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.fetchContact(addedContact.localContactID, modifiedContact));
for (ContactDetail fetchedDetail : modifiedContact.details) {
for (ContactDetail contactDetail : detailList) {
if (fetchedDetail.key == contactDetail.key) {
assertEquals(contactDetail.nativeVal1, fetchedDetail.nativeVal1);
assertEquals(contactDetail.nativeVal2, fetchedDetail.nativeVal2);
assertEquals(contactDetail.nativeVal3, fetchedDetail.nativeVal3);
}
}
}
shutdown();
}
@SmallTest
public void testFetchContactInfo() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = addedContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact c = new Contact();
ContactDetail fetchedPhoneDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactInfo(number, c, fetchedPhoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchedPhoneDetail));
shutdown();
}
@SmallTest
public void testFindNativeContact() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test Find Native Contact");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact nativeContact = new Contact();
nativeContact.synctophone = true;
status = mDatabaseHelper.addContact(nativeContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = nativeContact.localContactID;
status = mDatabaseHelper.addContactDetail(nicknameDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = nativeContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = nativeContact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = mDatabaseHelper.addContactDetail(emailDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(nativeContact.localContactID, fetchedContact);
assertTrue(mDatabaseHelper.findNativeContact(fetchedContact));
Contact c = new Contact();
assertFalse(mDatabaseHelper.findNativeContact(c));
shutdown();
}
@SmallTest
public void testModifyContactServerId() {
Log.i(LOG_TAG, "***** EXECUTING testModifyContactServerId *****");
Log.i(LOG_TAG, "Test Modify Contact ServerId");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// create and add contact
Contact c = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(c);
assertEquals(ServiceStatus.SUCCESS, status);
Long serverId = TestModule.generateRandomLong();
assertTrue(mDatabaseHelper.modifyContactServerId(c.localContactID, serverId, c.userID));
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(c.localContactID, fetchedContact);
assertEquals(serverId, fetchedContact.contactID);
shutdown();
}
@SmallTest
@Suppress
public void testModifyDetailServerId() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContactDetail(detail));
Long serverDetailId = detail.localContactID + TestModule.generateRandomLong();
- assertTrue(mDatabaseHelper.modifyContactDetailServerId(detail.localDetailID, serverDetailId));
+ assertTrue(mDatabaseHelper.syncContactDetail(detail.localDetailID, serverDetailId));
ContactDetail fetchedDetail = new ContactDetail();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail));
assertEquals(serverDetailId, fetchedDetail.unique_id);
shutdown();
}
@SmallTest
public void testOnUpgrade() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS,
DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
int oldVersion = TestModule.generateRandomInt();
int newVersion = TestModule.generateRandomInt();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
mDatabaseHelper.onUpgrade(db, oldVersion, newVersion);
shutdown();
}
}
\ No newline at end of file
diff --git a/tests/src/com/vodafone360/people/tests/service/AuthenticatorTest.java b/tests/src/com/vodafone360/people/tests/service/AuthenticatorTest.java
index 9436bd4..fac4179 100644
--- a/tests/src/com/vodafone360/people/tests/service/AuthenticatorTest.java
+++ b/tests/src/com/vodafone360/people/tests/service/AuthenticatorTest.java
@@ -1,226 +1,226 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.service;
import android.accounts.AccountManager;
import android.accounts.NetworkErrorException;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.Bundle;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Suppress;
import com.vodafone360.people.MainApplication;
import com.vodafone360.people.engine.contactsync.NativeContactsApi;
import com.vodafone360.people.service.Authenticator;
import com.vodafone360.people.tests.testutils.TestStatus;
-import com.vodafone360.people.ui.StartActivity;
/***
* Test the Authenticator class.
*/
public class AuthenticatorTest extends AndroidTestCase {
/** Instance of the Main Application. **/
private MainApplication mApplication = null;
/*
* ########## FRAMEWORK CLASSES. ##########
*/
/**
* Load and start a real MainApplication instance using the current
* context, as if it was started by the system.
*
* @throws Exception Anything related to starting the MainApplication
* class.
*/
@Override
protected final void setUp() throws Exception {
/** Setup the MainApplication. **/
mApplication = (MainApplication) Instrumentation.newApplication(MainApplication.class,
getContext());
assertNotNull("Newly created MainApplication class should not be NULL", mApplication);
mApplication.onCreate();
super.setUp();
}
/**
* Shuts down the Application under test. Also makes sure all resources
* are cleaned up and garbage collected before moving on to the next test.
* Subclasses that override this method should make sure they call
* super.tearDown() at the end of the overriding method.
*
* @throws Exception Cannot terminate the application.
*/
@Override
protected final void tearDown() throws Exception {
if (mApplication != null) {
mApplication.onTerminate();
mApplication = null;
}
super.tearDown();
}
/*
* ########## END FRAMEWORK CLASSES. ##########
*/
/***
* Test the Authenticator constructor.
*/
@SmallTest
public final void testAuthenticator() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertNotNull("Authenticator should not be NULL", authenticator);
}
/***
* Test the ACTION_ONE_ACCOUNT_ONLY_INTENT string.
*/
@SmallTest
public final void testActionOneAccountOnlyIntent() {
assertEquals("ACTION_ONE_ACCOUNT_ONLY_INTENT returns the wrong value",
"com.vodafone360.people.android.account.ONE_ONLY",
Authenticator.ACTION_ONE_ACCOUNT_ONLY_INTENT);
}
/***
* Test the getParcelable() method.
*/
@SmallTest
public final void testAddAccount() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
NativeContactsApi.createInstance(getContext());
Bundle bundle = authenticator.addAccount(null, null, null, null, null);
Intent intent = (Intent) bundle.getParcelable(AccountManager.KEY_INTENT);
assertEquals("Expected a StartActivity Intent",
- StartActivity.class.getName(), intent.getComponent().getClassName());
+ intent.getComponent().getClassName(),
+ "com.vodafone360.people.ui.StartActivity");
assertNull("Expected a ACTION_ONE_ACCOUNT_ONLY_INTENT action to be NULL",
intent.getAction());
}
/***
* Test the getAccountRemovalAllowed() method.
*/
@SmallTest
@Suppress
public final void testGetAccountRemovalAllowed() {
final TestStatus testStatus = new TestStatus();
Authenticator authenticator = new Authenticator(getContext(), new MainApplication() {
public void removeUserData() {
/*
* Test that the dummy mWakeListener.notifyOfWakeupAlarm() has
* been called, otherwise the test must fail.
*/
testStatus.setPass(true);
}
});
Bundle bundle = null;
try {
bundle = authenticator.getAccountRemovalAllowed(null, null);
} catch (NetworkErrorException e) {
fail("Unexpected NetworkErrorException");
}
/** Test if removeUserData() was called. **/
assertTrue("Expecting the removeUserData() dummy method to have "
+ "been called", testStatus.isPass());
assertEquals("Expected a KEY_BOOLEAN_RESULT boolean", true,
bundle.getBoolean(AccountManager.KEY_BOOLEAN_RESULT));
}
/***
* Test the confirmCredentials() method.
*/
@SmallTest
public final void testConfirmCredentials() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertNull("Expected confirmCredentials() to return NULL",
authenticator.confirmCredentials(null, null, null));
}
/***
* Test the editProperties() method.
*/
@SmallTest
public final void testEditProperties() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
try {
authenticator.editProperties(null, null);
fail("Expected editProperties() to throw an UnsupportedOperationException");
} catch (UnsupportedOperationException e) {
assertTrue("UnsupportedOperationException thrown as expected", true);
} catch (Exception e) {
fail("Expected editProperties() to throw an UnsupportedOperationException");
}
}
/***
* Test the getAuthToken() method.
*/
@SmallTest
public final void testGetAuthToken() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertNull("Expected getAuthToken() to return NULL",
authenticator.getAuthToken(null, null, null, null));
}
/***
* Test the getAuthTokenLabel() method.
*/
@SmallTest
public final void testGetAuthTokenLabel() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertNull("Expected getAuthTokenLabel() to return NULL",
authenticator.getAuthTokenLabel(null));
}
/***
* Test the hasFeatures() method.
*/
@SmallTest
public final void testHasFeatures() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertFalse("Expected hasFeatures() to return bundle boolean KEY_BOOLEAN_RESULT as FALSE",
authenticator.hasFeatures(null, null, null)
.getBoolean(AccountManager.KEY_BOOLEAN_RESULT));
}
/***
* Test the updateCredentials() method.
*/
@SmallTest
public final void testUpdateCredentials() {
Authenticator authenticator = new Authenticator(getContext(), mApplication);
assertNull("Expected updateCredentials() to return NULL",
authenticator.updateCredentials(null, null, null, null));
}
}
diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java
deleted file mode 100644
index be7fb59..0000000
--- a/tests/src/com/vodafone360/people/tests/ui/utils/SimNetworkTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the Common Development
- * and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at
- * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
- * http://github.com/360/360-Engine-for-Android
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each file and
- * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
- * If applicable, add the following below this CDDL HEADER, with the fields
- * enclosed by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
- * Use is subject to license terms.
- */
-
-package com.vodafone360.people.tests.ui.utils;
-
-import com.vodafone360.people.ui.utils.SimNetwork;
-import com.vodafone360.people.utils.LogUtils;
-
-import junit.framework.TestCase;
-
-public class SimNetworkTest extends TestCase {
-
- public SimNetworkTest(String name) {
- super(name);
- }
-
- protected void setUp() throws Exception {
- super.setUp();
- }
-
- protected void tearDown() throws Exception {
- super.tearDown();
- }
-
- public void testGetNetwork() {
-
- assertEquals("NULL country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork(null));
- assertEquals("Non existing country didn't return SimNetwork.UNKNOWN",SimNetwork.UNKNOWN, SimNetwork.getNetwork("non existing country"));
- assertEquals("Empty country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork(""));
- assertEquals("Blank country didn't return SimNetwork.UNKNOWN", SimNetwork.UNKNOWN, SimNetwork.getNetwork(" "));
-
- LogUtils.logV("CORRUPTED DATA TESTS FINISHED");
-
- assertEquals(SimNetwork.CH, SimNetwork.getNetwork(SimNetwork.CH.iso()));
- assertEquals(SimNetwork.DE, SimNetwork.getNetwork(SimNetwork.DE.iso()));
- assertEquals(SimNetwork.FR, SimNetwork.getNetwork(SimNetwork.FR.iso()));
- assertEquals(SimNetwork.GB, SimNetwork.getNetwork(SimNetwork.GB.iso()));
- assertEquals(SimNetwork.IE, SimNetwork.getNetwork(SimNetwork.IE.iso()));
- assertEquals(SimNetwork.IT, SimNetwork.getNetwork(SimNetwork.IT.iso()));
- assertEquals(SimNetwork.NL, SimNetwork.getNetwork(SimNetwork.NL.iso()));
- assertEquals(SimNetwork.SE, SimNetwork.getNetwork(SimNetwork.SE.iso()));
- assertEquals(SimNetwork.TR, SimNetwork.getNetwork(SimNetwork.TR.iso()));
- assertEquals(SimNetwork.TW, SimNetwork.getNetwork(SimNetwork.TW.iso()));
- assertEquals(SimNetwork.US, SimNetwork.getNetwork(SimNetwork.US.iso()));
- assertEquals(SimNetwork.ES, SimNetwork.getNetwork(SimNetwork.ES.iso()));
-
- LogUtils.logV("SETTINGS DATA TESTS FINISHED");
- }
-}
\ No newline at end of file
diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java
deleted file mode 100644
index 86eb0bc..0000000
--- a/tests/src/com/vodafone360/people/tests/ui/utils/SimUtilsTest.java
+++ /dev/null
@@ -1,68 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the Common Development
- * and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at
- * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
- * http://github.com/360/360-Engine-for-Android
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each file and
- * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
- * If applicable, add the following below this CDDL HEADER, with the fields
- * enclosed by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
- * Use is subject to license terms.
- */
-
-package com.vodafone360.people.tests.ui.utils;
-
-import junit.framework.TestCase;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.vodafone360.people.ui.utils.SimUtils;
-
-public class SimUtilsTest extends TestCase {
-
- @SmallTest
- public void testGetVerifyedMsisdn() throws Exception {
- assertEquals("", SimUtils.getVerifyedMsisdn(null, null, null, null));
- assertEquals("", SimUtils.getVerifyedMsisdn("", null, null, null));
- assertEquals("", SimUtils.getVerifyedMsisdn("1234567890", null, null, null));
- assertEquals("+1234567890", SimUtils.getVerifyedMsisdn("+1234567890", null, null, null));
- assertEquals("+4900000000", SimUtils.getVerifyedMsisdn("004900000000", null, null, null));
-
- //Real data tests
- assertEquals("", SimUtils.getVerifyedMsisdn("", "de", "Vodafone.de", "26202"));
- assertEquals("", SimUtils.getVerifyedMsisdn("", "au", "Vodafone.au", "26202"));
- assertEquals("+41700000000", SimUtils.getVerifyedMsisdn("+41700000000", "ch", "Swisscom", "22801"));
- assertEquals("+491720000000", SimUtils.getVerifyedMsisdn("01720000000", "de", "Vodafone.de", "26202"));
- assertEquals("+447960000000", SimUtils.getVerifyedMsisdn("07960000000", "gb", "Orange", "23433"));
- assertEquals("+31600000000", SimUtils.getVerifyedMsisdn("+31600000000", "nl", "vodafone NL", "20404"));
- assertEquals("+46700000000", SimUtils.getVerifyedMsisdn("+46700000000", "se", "Sweden3G", "24005"));
- assertEquals("+886988000000", SimUtils.getVerifyedMsisdn("0988000000", "tw", "????", "46692"));
- assertEquals("+15550000000", SimUtils.getVerifyedMsisdn("15550000000", "us", "Android", "310260")); //Emulator
- assertEquals("+15500000000", SimUtils.getVerifyedMsisdn("+15500000000", "us", "Android", "310260")); //Emulator
- }
-
- @SmallTest
- public void testGetAnonymisedMsisdn() throws Exception {
- assertEquals("", SimUtils.getAnonymisedMsisdn(null));
- assertEquals("", SimUtils.getAnonymisedMsisdn(""));
- assertEquals("1", SimUtils.getAnonymisedMsisdn("1"));
- assertEquals("12", SimUtils.getAnonymisedMsisdn("12"));
- assertEquals("123", SimUtils.getAnonymisedMsisdn("123"));
- assertEquals("1234", SimUtils.getAnonymisedMsisdn("1234"));
- assertEquals("12340", SimUtils.getAnonymisedMsisdn("12345"));
- assertEquals("1234000000", SimUtils.getAnonymisedMsisdn("1234567890"));
- assertEquals("+1230000000", SimUtils.getAnonymisedMsisdn("+1234567890"));
- }
-}
\ No newline at end of file
diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java
deleted file mode 100644
index bc16b55..0000000
--- a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/DialogEventTest.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the Common Development
- * and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at
- * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
- * http://github.com/360/360-Engine-for-Android
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each file and
- * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
- * If applicable, add the following below this CDDL HEADER, with the fields
- * enclosed by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
- * Use is subject to license terms.
- */
-
-package com.vodafone360.people.tests.ui.utils.interfaces;
-
-import junit.framework.TestCase;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.vodafone360.people.service.ServiceUiRequest;
-import com.vodafone360.people.ui.utils.interfaces.DialogEvent;
-
-public class DialogEventTest extends TestCase {
-
- @SmallTest
- public void testGetUiEvent() throws Exception {
-
- // Normal use
- assertEquals(DialogEvent.DIALOG_UPGRADE, DialogEvent
- .getDialogEvent(DialogEvent.DIALOG_UPGRADE.ordinal()));
- assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(DialogEvent.UNKNOWN.ordinal()));
-
- // Border conditions
- assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(-100));
- assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(-1));
- assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(ServiceUiRequest.UNKNOWN
- .ordinal() + 1));
- assertEquals(DialogEvent.UNKNOWN, DialogEvent.getDialogEvent(100));
- }
-}
diff --git a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java b/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java
deleted file mode 100644
index 504270a..0000000
--- a/tests/src/com/vodafone360/people/tests/ui/utils/interfaces/UiEventTest.java
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * CDDL HEADER START
- *
- * The contents of this file are subject to the terms of the Common Development
- * and Distribution License (the "License").
- * You may not use this file except in compliance with the License.
- *
- * You can obtain a copy of the license at
- * src/com/vodafone360/people/VODAFONE.LICENSE.txt or
- * http://github.com/360/360-Engine-for-Android
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * When distributing Covered Code, include this CDDL HEADER in each file and
- * include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
- * If applicable, add the following below this CDDL HEADER, with the fields
- * enclosed by brackets "[]" replaced with your own identifying information:
- * Portions Copyright [yyyy] [name of copyright owner]
- *
- * CDDL HEADER END
- *
- * Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
- * Use is subject to license terms.
- */
-
-package com.vodafone360.people.tests.ui.utils.interfaces;
-
-import junit.framework.TestCase;
-import android.test.suitebuilder.annotation.SmallTest;
-
-import com.vodafone360.people.service.ServiceUiRequest;
-
-public class UiEventTest extends TestCase {
-
- @SmallTest
- public void testGetUiEvent() throws Exception {
-
- // Normal use
- assertEquals(ServiceUiRequest.UI_REQUEST_COMPLETE, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UI_REQUEST_COMPLETE.ordinal()));
- assertEquals(ServiceUiRequest.DATABASE_CHANGED_EVENT, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.DATABASE_CHANGED_EVENT.ordinal()));
- assertEquals(ServiceUiRequest.SETTING_CHANGED_EVENT, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.SETTING_CHANGED_EVENT.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_CHAT, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_PRESENCE, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_PRESENCE.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_GO_TO_LANDING_PAGE.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_CHAT_ERROR, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT_ERROR.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_CHAT_ERROR_REFRESH.ordinal()));
- assertEquals(ServiceUiRequest.UNSOLICITED_PRESENCE_ERROR, ServiceUiRequest
- .getUiEvent(ServiceUiRequest.UNSOLICITED_PRESENCE_ERROR.ordinal()));
- assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(ServiceUiRequest.UNKNOWN
- .ordinal()));
-
- // Border conditions
- assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(-100));
- assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(-1));
- assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(ServiceUiRequest.UNKNOWN
- .ordinal() + 1));
- assertEquals(ServiceUiRequest.UNKNOWN, ServiceUiRequest.getUiEvent(100));
- }
-}
|
360/360-Engine-for-Android
|
9727ff89eb70010588ebdb469886c0bdbed2e433
|
Upgrade test project to target=android-8
|
diff --git a/tests/.classpath b/tests/.classpath
new file mode 100644
index 0000000..ccff76e
--- /dev/null
+++ b/tests/.classpath
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<classpath>
+ <classpathentry kind="src" path="src"/>
+ <classpathentry kind="src" path="gen"/>
+ <classpathentry kind="con" path="com.android.ide.eclipse.adt.ANDROID_FRAMEWORK"/>
+ <classpathentry combineaccessrules="false" kind="src" path="/360-Engine-for-Android"/>
+ <classpathentry kind="output" path="bin"/>
+</classpath>
|
360/360-Engine-for-Android
|
1752990f9d66944169ec8c1a2f98f8c90d6b62fd
|
PAND-1600: In status tab, 360 people status is duplicated
|
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
index dbc55f4..ad94b08 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
@@ -1,750 +1,750 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.database.tables.ContactDetailsTable.NativeIdInfo;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactDetailsTableTest extends NowPlusTableTestCase {
final TestModule mTestModule = new TestModule();
private int mTestStep = 0;
private static int NUM_OF_CONTACTS = 3;
private static final int MAX_MODIFY_NOWPLUS_DETAILS_COUNT = 100;
private static String LOG_TAG = "NowPlusContactsTableTest";
public NowPlusContactDetailsTableTest() {
super();
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
private void startSubTest(String function, String description) {
Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description);
mTestStep++;
}
private void createTable() {
try {
ContactDetailsTable.create(mTestDatabase.getWritableDatabase());
} catch (SQLException e) {
fail("An exception occurred when creating the table: " + e);
}
}
@SmallTest
public void testCreate() {
Log.i(LOG_TAG, "***** EXECUTING testCreate *****");
final String fnName = "testCreate";
mTestStep = 1;
startSubTest(fnName, "Creating table");
createTable();
Log.i(LOG_TAG, "*************************************");
Log.i(LOG_TAG, "testCreate has completed successfully");
Log.i(LOG_TAG, "**************************************");
}
@MediumTest
public void testAddFetchContactDetail() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
// try to add a detail before creating a table
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to fetch detail before creating a table
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
TestModule.generateRandomLong(), readableDb);
assertEquals(null, fetchedDetail);
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is null
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
detail.localContactID = TestModule.generateRandomLong();
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testDeleteContactDetail() {
final String fnName = "testDeleteContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Deltes a contact detail from the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
// try to delete contact by contact id before creating a table
ServiceStatus status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
// try to delete contact by detail id before creating a table
assertFalse(ContactDetailsTable.deleteDetailByDetailId(TestModule
.generateRandomLong(), writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// delete previously added contact
status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(null, fetchedDetail);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// try to delete contact by detail id
assertTrue(ContactDetailsTable.deleteDetailByDetailId(
detail.localDetailID, writeableDb));
// fetch deleted detail (should be null)
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(null, fetchedDetail);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testModifyContactDetail() {
final String fnName = "testModifyContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Modifies a contact detail in the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
Long serverId = TestModule.generateRandomLong();
// try to modify detail before creating a table
ServiceStatus status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
- assertFalse(ContactDetailsTable.modifyDetailServerId(TestModule
+ assertFalse(ContactDetailsTable.syncSetServerId(TestModule
.generateRandomLong(), serverId, writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to modify detail before adding it
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
mTestModule.modifyDummyDetailsData(detail);
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch modified detail
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
- assertTrue(ContactDetailsTable.modifyDetailServerId(
+ assertTrue(ContactDetailsTable.syncSetServerId(
detail.localDetailID, serverId, writeableDb));
ContactDetail modServIdDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(serverId,modServIdDetail.unique_id);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testContactsMatch() {
final String fnName = "testContactsMatch";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates doContactsMatch method");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
Contact contact = mTestModule.createDummyContactData();
contact.localContactID = TestModule.generateRandomLong();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> detailIdList = new ArrayList<NativeIdInfo>();
assertFalse(ContactDetailsTable.doContactsMatch(contact,
contact.localContactID, detailIdList, readableDb));
ServiceStatus status;
for (ContactDetail cd : contact.details) {
cd.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(cd, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
}
// assertTrue(ContactDetailsTable.doContactsMatch(contact,
// contact.localContactID, detailIdList, readableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfetchPreferredDetail() {
final String fnName = "testPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail preferredDetail = new ContactDetail();
preferredDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
preferredDetail.setTel("07967 654321", ContactDetail.DetailKeyTypes.CELL);
preferredDetail.localContactID = detail.localContactID;
preferredDetail.order = 0;
status = ContactDetailsTable.addContactDetail(preferredDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail altDetail = new ContactDetail();
assertTrue(ContactDetailsTable.fetchPreferredDetail(preferredDetail.localContactID.longValue(),
ContactDetail.DetailKeys.VCARD_PHONE.ordinal(), altDetail, readableDb));
// detail is preferred so should have the same fields
assertEquals(preferredDetail.localDetailID, altDetail.localDetailID);
assertEquals(preferredDetail.keyType, altDetail.keyType);
assertEquals(preferredDetail.value, altDetail.value);
assertEquals(preferredDetail.order, altDetail.order);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfixPreferredDetail() {
final String fnName = "testfixPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
status = ContactDetailsTable.fixPreferredValues(detail.localContactID,
writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(0, fetchedDetail.order.intValue()); // detail is now preferred
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFetchContactInfo() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = TestModule.generateRandomLong();
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
ServiceStatus status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
nameDetail.localContactID = phoneDetail.localContactID;
status = ContactDetailsTable.addContactDetail(nameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchName = new ContactDetail();
ContactDetail fetchPhone = new ContactDetail();
status = ContactDetailsTable.fetchContactInfo(number, fetchPhone, fetchName, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchPhone));
assertTrue(DatabaseHelper.doDetailsMatch(nameDetail, fetchName));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFindNativeContact() {
final String fnName = "testFindNativeContact";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create contact
Contact contact = new Contact();
contact.synctophone = true;
// add contact to to the ContactsTable
ContactsTable.create(mTestDatabase.getWritableDatabase());
ServiceStatus status = ContactsTable.addContact(contact,readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// add contact to ContactSummaryTable
ContactSummaryTable.create(mTestDatabase.getWritableDatabase());
status = ContactSummaryTable.addContact(contact, readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(emailDetail);
assertTrue(ContactDetailsTable.findNativeContact(contact, writeableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFetchContactDetailsForNative() {
final String fnName = "testFetchContactDetailsForNative";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
Contact contact = new Contact();
contact.localContactID = TestModule.generateRandomLong();
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
nicknameDetail.nativeContactId = TestModule.generateRandomInt();
ServiceStatus status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
List<ContactDetail> addedDetails = new ArrayList<ContactDetail>();
addedDetails.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
//phoneDetail.nativeContactId = mTestModule.GenerateRandomInt();
phoneDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
//emailDetail.nativeContactId = mTestModule.GenerateRandomInt();
emailDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(emailDetail);
ContactDetail.DetailKeys[] keyList = {
ContactDetail.DetailKeys.VCARD_NICKNAME,
ContactDetail.DetailKeys.VCARD_PHONE,
ContactDetail.DetailKeys.VCARD_EMAIL };
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
assertTrue(ContactDetailsTable.fetchContactDetailsForNative(detailList, keyList, false, 0,
MAX_MODIFY_NOWPLUS_DETAILS_COUNT, readableDb));
for (int i = 0; i < detailList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailList.get(i),
addedDetails.get(i)));
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFindLocalContactIdByKey() {
final String fnName = "testFindLocalContactIdByKey";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create local detail
ContactDetail localDetail = new ContactDetail();
localDetail.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail.nativeContactId = TestModule.generateRandomInt();
localDetail.nativeDetailId = TestModule.generateRandomInt();
localDetail.nativeVal1 = "nativeVal1";
localDetail.nativeVal2 = "nativeVal2";
localDetail.nativeVal3 = "nativeVal3";
localDetail.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
localDetail.alt = "google";
String imAddress = "[email protected]";
localDetail.setValue(imAddress, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status = ContactDetailsTable.addContactDetail(localDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create local detail
ContactDetail localDetail2 = new ContactDetail();
localDetail2.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail2.nativeContactId = TestModule.generateRandomInt();
localDetail2.nativeDetailId = TestModule.generateRandomInt();
localDetail2.nativeVal1 = "nativeVal1";
localDetail2.nativeVal2 = "nativeVal2";
localDetail2.nativeVal3 = "nativeVal3";
localDetail2.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
String imAddress2 = "[email protected]";
localDetail2.setValue(imAddress2, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status2 = ContactDetailsTable.addContactDetail(localDetail2, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status2);
long result = ContactDetailsTable.findLocalContactIdByKey("google", "[email protected]", ContactDetail.DetailKeys.VCARD_IMADDRESS, readableDb);
assertTrue("The contact ids don't match: expected=" + localDetail.localContactID + ", actual="+ result,result == localDetail.localContactID);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testsyncSetServerIds() {
final String fnName = "testsyncSetServerIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetServerIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ServerIdInfo> detailServerIdList = new ArrayList<ServerIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
ServerIdInfo serverInfo = new ServerIdInfo();
serverInfo.localId = detail.localDetailID;
serverInfo.serverId = TestModule.generateRandomLong();
detailServerIdList.add(serverInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetServerIds(
detailServerIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detailsList.get(i).localDetailID, readableDb);
assertNotNull(fetchedDetail);
assertEquals(detailServerIdList.get(i).serverId, fetchedDetail.unique_id);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncNativeIds
*/
public void testSyncSetNativeIds() {
final String fnName = "testSyncSetNativeIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetNativeIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> nativeIdList = new ArrayList<NativeIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
NativeIdInfo nativeIdInfo = new NativeIdInfo();
nativeIdInfo.nativeContactId = TestModule.generateRandomInt();
nativeIdInfo.localId = detail.localDetailID;
nativeIdList.add(nativeIdInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetNativeIds(
nativeIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
nativeIdList.get(i).localId, readableDb);
assertNotNull(fetchedDetail);
assertEquals(nativeIdList.get(i).nativeContactId, fetchedDetail.nativeContactId);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchContactChanges
*/
public void testSyncServerFetchContactChanges() {
final String fnName = "testSyncServerFetchContactChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
detailsList.add(detail);
}
Cursor cursor = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, true);
assertEquals(NUM_OF_CONTACTS, cursor.getCount());
Cursor cursorOldContacts = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, false);
assertEquals(0, cursorOldContacts.getCount());
cursorOldContacts.close();
List<Contact> contactList = new ArrayList<Contact>();
ContactDetailsTable.syncServerGetNextNewContactDetails(cursor, contactList, NUM_OF_CONTACTS);
for (int i = 0; i < contactList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailsList.get(i),
contactList.get(i).details.get(0)));
}
cursor.close();
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchNoOfChanges
*/
public void testSyncServerFetchNoOfChanges() {
final String fnName = "testSyncServerFetchNoOfChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
index adac32c..ffd80da 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
@@ -23,536 +23,536 @@
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
import com.vodafone360.people.MainApplication;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.datatypes.ContactSummary;
import com.vodafone360.people.engine.meprofile.SyncMeDbUtils;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactsTest extends ApplicationTestCase<MainApplication> {
private static String LOG_TAG = "NowPlusDatabaseTest";
final static int WAIT_EVENT_TIMEOUT_MS = 30000;
final static int NUM_OF_CONTACTS = 3;
private static MainApplication mApplication = null;
private static DatabaseHelper mDatabaseHelper = null;
final TestModule mTestModule = new TestModule();
private DbTestUtility mTestUtility;
public NowPlusContactsTest() {
super(MainApplication.class);
}
private boolean initialise() {
mTestUtility = new DbTestUtility(getContext());
createApplication();
mApplication = getApplication();
if(mApplication == null){
Log.e(LOG_TAG, "Unable to create main application");
return false;
}
mDatabaseHelper = mApplication.getDatabase();
if (mDatabaseHelper.getReadableDatabase() == null) {
return false;
}
mTestUtility.startEventWatcher(mDatabaseHelper);
return true;
}
private void shutdown() {
mTestUtility.stopEventWatcher();
}
/***
* Check if contact detail was added to ContactSummary.
* If contact detail is a name check if it's name in formatted state
* is the same as contact summary formatted name.
* @param cd ContactDetail
* @return boolean true if ContactDetail is in ContactSummaryTable
*/
private boolean isContactDetailInSummary(ContactDetail cd) {
//boolean result = true;
ContactSummary cs = new ContactSummary();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ServiceStatus status = ContactSummaryTable.fetchSummaryItem(
cd.localContactID, cs, db);
if (status != ServiceStatus.SUCCESS) {
return false;
} else if (ContactDetail.DetailKeys.VCARD_NAME == cd.key
&& !cd.getName().toString().equals(cs.formattedName)) {
// if ContactDetail name is different then ContactSummary name
return false;
} else {
return true;
}
}
@SmallTest
@Suppress
public void testMeProfiles() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact meProfile = mTestModule.createDummyContactData();
// assertFalse(mDatabaseHelper.getMeProfileChanged());
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(SyncMeDbUtils.getMeProfileLocalContactId(mDatabaseHelper), meProfile.localContactID);
Contact fetchedMe = new Contact();
status = SyncMeDbUtils.fetchMeProfile(mDatabaseHelper,fetchedMe);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(fetchedMe, meProfile));
// Modify me Profile
Contact meProfile2 = mTestModule.createDummyContactData();
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile2);
assertEquals(ServiceStatus.SUCCESS, status);
// assertTrue(mDatabaseHelper.getMeProfileChanged());
shutdown();
}
@SmallTest
public void testAddContactToGroup() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long groupId = 1L;
status = mDatabaseHelper.addContactToGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.deleteContactFromGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.ERROR_NOT_READY, status);
shutdown();
}
@SmallTest
public void testSyncSetServerIds() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long serverId = addedContact.localContactID + 1;
long userId = addedContact.localContactID + 2;
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = addedContact.localContactID;
info.serverId = serverId;
info.userId = userId;
serverIdList.add(info);
status = ContactsTable.syncSetServerIds(serverIdList, null, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
addedContact.contactID = serverId;
addedContact.userID = userId;
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContactByServerId(serverId, fetchedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, fetchedContact));
shutdown();
}
@SmallTest
@Suppress
public void testAddContactDetail() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
status = mDatabaseHelper.addContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchedDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
assertTrue(!DatabaseHelper.hasDetailChanged(detail, fetchedDetail));
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.deleteAllGroups());
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = fetchedDetail.localDetailID;
info.serverId = fetchedDetail.localDetailID + 1;
serverIdList.add(info);
status = ContactDetailsTable.syncSetServerIds(serverIdList, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(info.serverId, fetchedDetail.unique_id);
shutdown();
}
@MediumTest
public void testAddModifyContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddModifyContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add/modify details contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Modify contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(isContactDetailInSummary(detail));
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContactsDetails() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContactsDetails *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts details)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts detatils and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
status = mDatabaseHelper.deleteContactDetail(detail.localDetailID);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if deletion works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
// check if deletion works good
status = mDatabaseHelper.deleteContact(inputContacts[i].localContactID);
assertEquals(ServiceStatus.SUCCESS, status);
Contact removedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, removedContact);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); // contact was deleted so it shouldn't be found
}
shutdown();
}
@SmallTest
public void testSyncAddContactDetailList() {
Log.i(LOG_TAG, "***** EXECUTING testSyncAddContactDetailList *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(
WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail cd = new ContactDetail();
mTestModule.createDummyDetailsData(cd);
cd.localContactID = addedContact.localContactID;
cd.nativeContactId = TestModule.generateRandomInt();
cd.nativeDetailId = TestModule.generateRandomInt();
cd.nativeVal1 = TestModule.generateRandomString();
cd.nativeVal2 = TestModule.generateRandomString();
cd.nativeVal3 = TestModule.generateRandomString();
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
detailList.add(cd);
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.syncAddContactDetailList(detailList, false, false));
Contact modifiedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.fetchContact(addedContact.localContactID, modifiedContact));
for (ContactDetail fetchedDetail : modifiedContact.details) {
for (ContactDetail contactDetail : detailList) {
if (fetchedDetail.key == contactDetail.key) {
assertEquals(contactDetail.nativeVal1, fetchedDetail.nativeVal1);
assertEquals(contactDetail.nativeVal2, fetchedDetail.nativeVal2);
assertEquals(contactDetail.nativeVal3, fetchedDetail.nativeVal3);
}
}
}
shutdown();
}
@SmallTest
public void testFetchContactInfo() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = addedContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact c = new Contact();
ContactDetail fetchedPhoneDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactInfo(number, c, fetchedPhoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchedPhoneDetail));
shutdown();
}
@SmallTest
public void testFindNativeContact() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test Find Native Contact");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact nativeContact = new Contact();
nativeContact.synctophone = true;
status = mDatabaseHelper.addContact(nativeContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = nativeContact.localContactID;
status = mDatabaseHelper.addContactDetail(nicknameDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = nativeContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = nativeContact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = mDatabaseHelper.addContactDetail(emailDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(nativeContact.localContactID, fetchedContact);
assertTrue(mDatabaseHelper.findNativeContact(fetchedContact));
Contact c = new Contact();
assertFalse(mDatabaseHelper.findNativeContact(c));
shutdown();
}
@SmallTest
public void testModifyContactServerId() {
Log.i(LOG_TAG, "***** EXECUTING testModifyContactServerId *****");
Log.i(LOG_TAG, "Test Modify Contact ServerId");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// create and add contact
Contact c = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(c);
assertEquals(ServiceStatus.SUCCESS, status);
Long serverId = TestModule.generateRandomLong();
assertTrue(mDatabaseHelper.modifyContactServerId(c.localContactID, serverId, c.userID));
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(c.localContactID, fetchedContact);
assertEquals(serverId, fetchedContact.contactID);
shutdown();
}
@SmallTest
@Suppress
public void testModifyDetailServerId() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContactDetail(detail));
Long serverDetailId = detail.localContactID + TestModule.generateRandomLong();
- assertTrue(mDatabaseHelper.modifyContactDetailServerId(detail.localDetailID, serverDetailId));
+ assertTrue(mDatabaseHelper.syncContactDetail(detail.localDetailID, serverDetailId));
ContactDetail fetchedDetail = new ContactDetail();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail));
assertEquals(serverDetailId, fetchedDetail.unique_id);
shutdown();
}
@SmallTest
public void testOnUpgrade() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS,
DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
int oldVersion = TestModule.generateRandomInt();
int newVersion = TestModule.generateRandomInt();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
mDatabaseHelper.onUpgrade(db, oldVersion, newVersion);
shutdown();
}
}
\ No newline at end of file
|
360/360-Engine-for-Android
|
49bb2a3fd87f384e649267dd63924c170697b726
|
PAND-1546: ContactSyncEgine has wrong processor order during first time sync
|
diff --git a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
index 3b661da..a450b4d 100644
--- a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
+++ b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
@@ -717,1013 +717,1011 @@ public class ContactSyncEngine extends BaseEngine implements IContactSyncCallbac
if (mRemoveUserData) {
mFirstTimeSyncStarted = false;
mFirstTimeSyncComplete = false;
mFirstTimeNativeSyncComplete = false;
mRemoveUserData = false;
super.onReset();
}
return;
}
}
if (processTimeout()) {
return;
}
if (isUiRequestOutstanding()) {
mActiveUiRequestBackup = mActiveUiRequest;
if (processUiQueue()) {
return;
}
}
if (isCommsResponseOutstanding() && processCommsInQueue()) {
return;
}
if (readyToStartServerSync()) {
if (mThumbnailSyncRequired) {
startThumbnailSync();
return;
}
if (mFullSyncRequired) {
startFullSync();
return;
}
if (mServerSyncRequired) {
startServerSync();
return;
}
}
if (mNativeFetchSyncRequired && readyToStartFetchNativeSync()) {
startFetchNativeSync();
return;
}
if (mNativeUpdateSyncRequired && readyToStartUpdateNativeSync()) {
startUpdateNativeSync();
return;
}
}
/**
* Called by base class when a contact sync UI request has been completed.
* Not currently used.
*/
@Override
protected void onRequestComplete() {
}
/**
* Called by base class when a timeout has been completed. If there is an
* active processor the timeout event will be passed to it, otherwise the
* engine will check if it needs to schedule a new sync and set the next
* pending timeout.
*/
@Override
protected void onTimeoutEvent() {
if (mActiveProcessor != null) {
mActiveProcessor.onTimeoutEvent();
} else {
startSyncIfRequired();
setTimeoutIfRequired();
}
}
/**
* Based on current timeout values schedules a new sync if required.
*/
private void startSyncIfRequired() {
if (mFirstTimeSyncStarted && !mFirstTimeSyncComplete) {
mFullSyncRequired = true;
mFullSyncRetryCount = 0;
}
long currentTimeMs = System.currentTimeMillis();
if (mServerSyncTimeout != null && mServerSyncTimeout.longValue() < currentTimeMs) {
mServerSyncRequired = true;
mServerSyncTimeout = null;
} else if (mFetchNativeSyncTimeout != null
&& mFetchNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeFetchSyncRequired = true;
mFetchNativeSyncTimeout = null;
} else if (mUpdateNativeSyncTimeout != null
&& mUpdateNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeUpdateSyncRequired = true;
mUpdateNativeSyncTimeout = null;
}
}
/**
* Called when a response to a request or a push message is received from
* the server. Push messages are processed by the engine, responses are
* passed to the active processor.
*
* @param resp Response or push message received
*/
@Override
protected void processCommsResponse(Response resp) {
if (processPushEvent(resp)) {
return;
}
if (resp.mDataTypes != null && resp.mDataTypes.size() > 0) {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = " + resp.mDataTypes.get(0).name());
} else {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = NULL");
}
if (mActiveProcessor != null) {
mActiveProcessor.processCommsResponse(resp);
}
}
/**
* Determines if a given response is a push message and processes in this
* case TODO: we need the check for Me Profile be migrated to he new engine
*
* @param resp Response to check and process
* @return true if the response was processed
*/
private boolean processPushEvent(Response resp) {
if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) {
return false;
}
BaseDataType dataType = resp.mDataTypes.get(0);
if ((dataType == null) || !dataType.name().equals("PushEvent")) {
return false;
}
PushEvent pushEvent = (PushEvent)dataType;
LogUtils.logV("Push Event Type = " + pushEvent.mMessageType);
switch (pushEvent.mMessageType) {
case CONTACTS_CHANGE:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - Contacts changed push message received");
mServerSyncRequired = true;
EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); // fetch
// the
// newest
// groups
mEventCallback.kickWorkerThread();
break;
case SYSTEM_NOTIFICATION:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - System notification push message received");
break;
default:
// do nothing.
break;
}
return true;
}
/**
* Called by base class to process a NOWPLUSSYNC UI request. This will be
* called to process a full sync or server sync UI request.
*
* @param requestId ID of the request to process, only
* ServiceUiRequest.NOWPLUSSYNC is currently supported.
* @param data Type is determined by request ID, in case of NOWPLUSSYNC this
* is a flag which determines if a full sync is required (true =
* full sync, false = server sync).
*/
@Override
protected void processUiRequest(ServiceUiRequest requestId, Object data) {
switch (requestId) {
case NOWPLUSSYNC:
final SyncParams params = (SyncParams)data;
if (params.isFull) {
// delayed full sync is not supported currently, start it
// immediately
clearCurrentSyncAndPatchBaseEngine();
mFullSyncRetryCount = 0;
startFullSync();
} else {
if (params.delay <= 0) {
clearCurrentSyncAndPatchBaseEngine();
if (readyToStartServerSync()) {
startServerSync();
} else {
mServerSyncRequired = true;
}
} else {
startServerContactSyncTimer(params.delay);
}
}
break;
default:
// do nothing.
break;
}
}
/**
* Called by the run function when the {@link #mCancelSync} flag is set to
* true. Cancels the active processor and completes the current UI request.
*/
private void cancelSync() {
if (mActiveProcessor != null) {
mActiveProcessor.cancel();
mActiveProcessor = null;
}
completeSync(ServiceStatus.USER_CANCELLED);
}
/**
* Clears the current sync and make sure that if we cancel a previous sync,
* it doesn't notify a wrong UI request. TODO: Find another way to not have
* to hack the BaseEngine!
*/
private void clearCurrentSyncAndPatchBaseEngine() {
// Cancel background sync
if (mActiveProcessor != null) {
// the mActiveUiRequest is already the new one so if
// onCompleteUiRequest(Error) is called,
// this will reset it to null even if we didn't start to process it.
ServiceUiRequest newActiveUiRequest = mActiveUiRequest;
mActiveUiRequest = mActiveUiRequestBackup;
mActiveProcessor.cancel();
// restore the active UI request...
mActiveUiRequest = newActiveUiRequest;
mActiveProcessor = null;
}
newState(State.IDLE);
}
/**
* Checks if a server sync can be started based on network conditions and
* engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartServerSync() {
if (!Settings.ENABLE_SERVER_CONTACT_SYNC) {
return false;
}
if (!EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete()) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE || NetworkAgent.getAgentState() != AgentState.CONNECTED) {
return false;
}
return true;
}
/**
* Checks if a fetch native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartFetchNativeSync() {
if (!Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Checks if a update native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartUpdateNativeSync() {
if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Starts a full sync. If the native contacts haven't yet been fetched then
* a first time sync will be started, otherwise will start a normal full
* sync. Full syncs are always initiated from the UI (via UI request).
*/
public void startFullSync() {
mFailureList = "";
mDatabaseChanged = false;
setFirstTimeSyncStarted(true);
mServerSyncTimeout = null;
mFullSyncRequired = false;
if (mFirstTimeNativeSyncComplete) {
LogUtils.logI("ContactSyncEngine.startFullSync - user triggered sync");
mMode = Mode.FULL_SYNC;
nextTaskFullSyncNormal();
} else {
LogUtils.logI("ContactSyncEngine.startFullSync - first time sync");
mMode = Mode.FULL_SYNC_FIRST_TIME;
nextTaskFullSyncFirstTime();
}
}
/**
* Starts a server sync. This will only sync contacts with the server and
* will not include the me profile. Thumbnails are not fetched as part of
* this sync, but will be fetched as part of a background sync afterwards.
*/
private void startServerSync() {
mServerSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.SERVER_SYNC;
mServerSyncTimeout = null;
setTimeoutIfRequired();
nextTaskServerSync();
}
/**
* Starts a background thumbnail sync
*/
private void startThumbnailSync() {
mThumbnailSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.THUMBNAIL_SYNC;
nextTaskThumbnailSync();
}
/**
* Starts a background fetch native contacts sync
*/
private void startFetchNativeSync() {
mNativeFetchSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.FETCH_NATIVE_SYNC;
mFetchNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskFetchNativeContacts();
}
/**
* Starts a background update native contacts sync
*/
private void startUpdateNativeSync() {
mNativeUpdateSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.UPDATE_NATIVE_SYNC;
mUpdateNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskUpdateNativeContacts();
}
/**
* Helper function to start the fetch native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startFetchNativeContacts() {
if (Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
newState(State.FETCHING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.FETCH_NATIVE_CONTACTS, this,
mDb, mContext, mCr));
return true;
}
return false;
}
/**
* Helper function to start the update native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUpdateNativeContacts() {
if (Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
newState(State.UPDATING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPDATE_NATIVE_CONTACTS, this,
mDb, null, mCr));
return true;
}
return false;
}
/**
* Helper function to start the download server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.FETCHING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.DOWNLOAD_SERVER_CONTACTS,
this, mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the upload server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUploadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.UPDATING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPLOAD_SERVER_CONTACTS, this,
mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the download thumbnails processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerThumbnails() {
if (Settings.ENABLE_THUMBNAIL_SYNC) {
ThumbnailHandler.getInstance().downloadContactThumbnails();
return true;
}
return false;
}
/**
* Called by a processor when it has completed. Will move to the next task.
* When the active contact sync has totally finished, will complete any
* pending UI request.
*
* @param status Status of the sync from the processor, any error codes will
* stop the sync.
* @param failureList Contains a list of sync failure information which can
* be used as a summary at the end. Otherwise should be an empty
* string.
* @param data Any processor specific data to pass back to the engine. Not
* currently used.
*/
@Override
public void onProcessorComplete(ServiceStatus status, String failureList, Object data) {
if (mState == State.IDLE) {
return;
}
if (mActiveProcessor != null) {
mActiveProcessor.onComplete();
}
mActiveProcessor = null;
mFailureList += failureList;
if (status != ServiceStatus.SUCCESS) {
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Failed during " + mState
+ " with error " + status);
completeSync(status);
return;
}
if (mDbChangedByProcessor) {
switch (mState) {
case FETCHING_NATIVE_CONTACTS:
mServerSyncRequired = true;
break;
case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mNativeUpdateSyncRequired = true;
break;
default:
// Do nothing.
break;
}
}
switch (mMode) {
case FULL_SYNC_FIRST_TIME:
nextTaskFullSyncFirstTime();
break;
case FULL_SYNC:
nextTaskFullSyncNormal();
break;
case SERVER_SYNC:
nextTaskServerSync();
break;
case FETCH_NATIVE_SYNC:
nextTaskFetchNativeContacts();
break;
case UPDATE_NATIVE_SYNC:
nextTaskUpdateNativeContacts();
break;
case THUMBNAIL_SYNC:
nextTaskThumbnailSync();
break;
default:
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Unexpected mode: " + mMode);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync first time mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncFirstTime() {
+
switch (mState) {
case IDLE:
- if (startDownloadServerContacts()) {
- return;
- }
- // Fall through
- case FETCHING_SERVER_CONTACTS:
- if (startFetchNativeContacts()) {
+ if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
setFirstTimeNativeSyncComplete(true);
if (startUploadServerContacts()) {
- return;
+ return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
- // force a thumbnail sync in case nothing in the database
- // changed but we still have failing
- // thumbnails that we should retry to download
+ if (startDownloadServerContacts()) {
+ return;
+ }
+ // Fall through
+ case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncFirstTime - Unexpected state: "
- + mState);
+ + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync normal mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncNormal() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncNormal - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the fetch native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFetchNativeContacts() {
switch (mState) {
case IDLE:
if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFetchNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the update native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskUpdateNativeContacts() {
switch (mState) {
case IDLE:
if (startUpdateNativeContacts()) {
return;
}
completeSync(ServiceStatus.SUCCESS);
return;
// Fall through
case UPDATING_NATIVE_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskUpdateNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the server sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskServerSync() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskServerSync - Unexpected state: " + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the thumbnail sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskThumbnailSync() {
switch (mState) {
case IDLE:
if (startDownloadServerThumbnails()) {
return;
}
default:
LogUtils.logE("ContactSyncEngine.nextTaskThumbnailSync - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Changes the state of the engine and informs the observers.
*
* @param newState The new state
*/
private void newState(State newState) {
State oldState = mState;
synchronized (mMutex) {
if (newState == mState) {
return;
}
mState = newState;
}
LogUtils.logV("ContactSyncEngine.newState: " + oldState + " -> " + mState);
fireStateChangeEvent(mMode, oldState, mState);
}
/**
* Called when the current mode has finished all the sync tasks. Completes
* the UI request if one is pending, sends an event to the observer and a
* database change event if necessary.
*
* @param status The overall status of the contact sync.
*/
private void completeSync(ServiceStatus status) {
if (mState == State.IDLE) {
return;
}
if (mDatabaseChanged) {
LogUtils.logD("ContactSyncEngine.completeSync - Firing Db changed event");
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
mDatabaseChanged = false;
}
mActiveProcessor = null;
newState(State.IDLE);
mMode = Mode.NONE;
completeUiRequest(status, mFailureList);
mCache.setSyncStatus(new SyncStatus(status));
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mFirstTimeSyncComplete) {
fireSyncCompleteEvent(status);
}
if (ServiceStatus.SUCCESS == status) {
startSyncIfRequired();
} else {
setTimeout(SYNC_ERROR_WAIT_TIMEOUT);
}
mLastStatus = status;
setTimeoutIfRequired();
}
/**
* Sets the current timeout to the next pending timer and kicks the engine
* if necessary.
*/
private synchronized void setTimeoutIfRequired() {
Long initTimeout = mCurrentTimeout;
if (mCurrentTimeout == null
|| (mServerSyncTimeout != null && mServerSyncTimeout.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mServerSyncTimeout;
}
if (mCurrentTimeout == null
|| (mFetchNativeSyncTimeout != null && mFetchNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mFetchNativeSyncTimeout;
}
if (mCurrentTimeout == null
|| (mUpdateNativeSyncTimeout != null && mUpdateNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mUpdateNativeSyncTimeout;
}
if (mCurrentTimeout != null && !mCurrentTimeout.equals(initTimeout)) {
mEventCallback.kickWorkerThread();
}
}
/**
* Called by the active processor to indicate that the NowPlus database has
* changed.
*/
@Override
public void onDatabaseChanged() {
mDatabaseChanged = true;
mDbChangedByProcessor = true;
final long currentTime = System.nanoTime();
if (mLastDbUpdateTime == null
|| mLastDbUpdateTime.longValue() + UI_REFRESH_WAIT_TIME_NANO < currentTime) {
LogUtils.logD("ContactSyncEngine.onDatabaseChanged - Updating UI...");
mDatabaseChanged = false;
mLastDbUpdateTime = currentTime;
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
}
}
/**
* Used by processors to fetch this engine. The BaseEngine reference is
* needed to send requests to the server.
*
* @return The BaseEngine reference of this engine.
*/
@Override
public BaseEngine getEngine() {
return this;
}
/**
* Used by active processor to set a timeout.
*
* @param timeout Timeout value based on current time in milliseconds
*/
@Override
public void setTimeout(long timeout) {
super.setTimeout(timeout);
}
/**
* Used by active processor to set the current progress.
*
* @param SyncStatus Status of the processor, must not be NULL.
* @throws InvalidParameterException when SyncStatus is NULL.
*/
@Override
public void setSyncStatus(final SyncStatus syncStatus) {
if (syncStatus == null) {
throw new InvalidParameterException(
"ContactSyncEngine.setSyncStatus() SyncStatus cannot be NULL");
}
mCache.setSyncStatus(syncStatus);
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mState != State.IDLE && syncStatus.getProgress() != mCurrentProgressPercent) {
mCurrentProgressPercent = syncStatus.getProgress();
LogUtils.logI("ContactSyncEngine: Task " + mState + " is " + syncStatus.getProgress()
+ "% complete");
fireProgressEvent(mState, syncStatus.getProgress());
}
}
/**
* Called by active processor when issuing a request to store the request id
* in the base engine class.
*/
@Override
public void setActiveRequestId(int reqId) {
setReqId(reqId);
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncStarted} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been started. The flag is never set to false again by the
* engine, it will be only set to false when a remove user data
* is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncStarted(boolean value) {
if (mFirstTimeSyncStarted == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncStarted(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncStarted = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been completed. The flag is never set to false again by
* the engine, it will be only set to false when a remove user
* data is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncComplete = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeNativeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that the native fetch
* part of the first time sync has been completed. The flag is
* never set to false again by the engine, it will be only set to
* false when a remove user data is done (and the database is
* deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeNativeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeNativeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeNativeSyncComplete = value;
}
}
return status;
}
/**
* Called when a database change event is received from the DatabaseHelper.
* Only internal database change events are processed, external change
* events are generated by the contact sync engine.
*
* @param msg The message indicating the type of event
*/
private void processDbMessage(Message message) {
final ServiceUiRequest event = ServiceUiRequest.getUiEvent(message.what);
switch (event) {
case DATABASE_CHANGED_EVENT:
if (message.arg1 == DatabaseHelper.DatabaseChangeType.CONTACTS.ordinal()
&& message.arg2 == 0) {
LogUtils.logV("ContactSyncEngine.processDbMessage - Contacts have changed");
// startMeProfileSyncTimer();
startServerContactSyncTimer(SERVER_CONTACT_SYNC_TIMEOUT_MS);
startUpdateNativeContactSyncTimer();
}
break;
default:
// Do nothing.
break;
}
}
/**
* Notifies observers when a state or mode change occurs.
*
* @param mode Current mode
* @param previousState State before the change
* @param newState State after the change.
*/
private void fireStateChangeEvent(Mode mode, State previousState, State newState) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onContactSyncStateChange(mode, previousState, newState);
}
if (Settings.ENABLED_DATABASE_TRACE) {
// DatabaseHelper.trace(false, "State newState[" + newState + "]" +
// mDb.copyDatabaseToSd(""));
}
}
/**
* Notifies observers when a contact sync complete event occurs.
*
* @param status SUCCESS or a suitable error code
*/
private void fireSyncCompleteEvent(ServiceStatus status) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onSyncComplete(status);
}
}
/**
* Notifies observers when the progress value changes for the current sync.
*
* @param currentState Current sync task being processed
* @param percent Progress of task (between 0 and 100 percent)
*/
private void fireProgressEvent(State currentState, int percent) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onProgressEvent(currentState, percent);
}
}
/**
* Called by framework to warn the engine that a remove user data is about
* to start. Sets flags and kicks the engine.
*/
@Override
public void onReset() {
synchronized (this) {
mCancelSync = true;
mRemoveUserData = true;
}
mEventCallback.kickWorkerThread();
}
/**
* @see NativeContactsApi.ContactsObserver#onChange()
*/
@Override
public void onChange() {
LogUtils.logD("ContactSyncEngine.onChange(): changes detected on native side.");
// changes detected on native side, start the timer for the
// FetchNativeContacts processor.
startFetchNativeContactSyncTimer();
}
}
diff --git a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
index cded745..889d1a9 100644
--- a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
+++ b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
@@ -1,190 +1,190 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.contactsync;
import com.vodafone360.people.service.ServiceStatus;
/**
* In memory store for the current state of the Contacts sync engine.
*/
public class SyncStatus {
/** Sync tasks, each of which corresponds to a specific processor. **/
public enum Task {
- /** DownloadServerContacts is processing. */
- DOWNLOAD_SERVER_CONTACTS,
/** FetchNativeContacts is processing. */
FETCH_NATIVE_CONTACTS,
/** UploadServerContacts is processing. */
UPDATE_SERVER_CONTACTS,
+ /** DownloadServerContacts is processing. */
+ DOWNLOAD_SERVER_CONTACTS,
/** Last element is used to determine the size of the ENUM. **/
UNKNOWN
}
/** Sync task status. **/
public enum TaskStatus {
/** Sent X of Y contacts. */
SENT_CONTACTS,
/** Received X of Y contacts. */
RECEIVED_CONTACTS,
/** Sent X of Y changes. */
SENT_CHANGES,
/** Do not show task status (i.e. leave blank). */
NONE
}
/** ServiceStatus of sync outcome. **/
private ServiceStatus mServiceStatus;
/** Percentage of sync progress in current task (e.g. 53). **/
private int mProgress;
/** Current contact name (e.g. John Doe). **/
private String mTextContact;
/** Current task (e.g. Uploading server contacts). **/
private Task mTask;
/** Current task status (e.g. Sent 25 of 500 contacts). **/
private TaskStatus mTaskStatus;
/** Current task done (e.g. Sent X of 500 contacts). **/
private int mTaskStatusDone;
/** Current task total (e.g. Sent 25 of X contacts). **/
private int mTaskStatusTotal;
/**
* Construct with only the ServiceStatus of the Contacts sync engine.
*
* @param serviceStatus ServiceStatus of sync outcome.
*/
protected SyncStatus(final ServiceStatus serviceStatus) {
mServiceStatus = serviceStatus;
}
/**
* Construct with the current state of the Contacts sync engine.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
* @param taskStatus Current task status (e.g. Sent 25 of 500 contacts).
* @param taskStatusDone Current task done (e.g. Sent X of 500 contacts).
* @param taskStatusTotal Current task total (e.g. Sent 25 of X contacts).
*/
public SyncStatus(final int progress,
final String textContact, final Task task,
final TaskStatus taskStatus, final int taskStatusDone,
final int taskStatusTotal) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = taskStatus;
mTaskStatusDone = taskStatusDone;
mTaskStatusTotal = taskStatusTotal;
}
/**
* Construct with the current state of the Contacts sync engine, with the
* task status set to TaskStatus.NONE.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
*/
public SyncStatus(final int progress, final String textContact,
final Task task) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = TaskStatus.NONE;
mTaskStatusDone = 0;
mTaskStatusTotal = 0;
}
/**
* Gets the ServiceStatus of sync outcome.
*
* @return Sync outcome as a ServiceStatus object.
*/
public final ServiceStatus getServiceStatus() {
return mServiceStatus;
}
/**
* Get the current sync progress percentage for the current task.
*
* @return Current sync progress percentage.
*/
public final int getProgress() {
return mProgress;
}
/**
* Get the current contact name (e.g. John Doe).
*
* @return Current contact name.
*/
public final String getTextContact() {
return mTextContact;
}
/**
* Get the current task (e.g. Uploading server contacts)
*
* @return Current task.
*/
public final Task getTask() {
return mTask;
}
/**
* Get the current task status (e.g. Sent 25 of 500 contacts).
*
* @return Current task status.
*/
public final TaskStatus getTaskStatus() {
return mTaskStatus;
}
/**
* Get the current task done (e.g. Sent X of 500 contacts).
*
* @return Current task done.
*/
public final int getTaskStatusDone() {
return mTaskStatusDone;
}
/**
* Get the current task total (e.g. Sent 25 of X contacts).
*
* @return Current task total.
*/
public final int getTaskStatusTotal() {
return mTaskStatusTotal;
}
}
\ No newline at end of file
|
360/360-Engine-for-Android
|
9b4fe55fb4845656f25d604864fb728a43670b75
|
PAND-1600: In status tab, 360 people status is duplicated
|
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
index dbc55f4..ad94b08 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactDetailsTableTest.java
@@ -1,750 +1,750 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.database.tables.ContactDetailsTable.NativeIdInfo;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactDetailsTableTest extends NowPlusTableTestCase {
final TestModule mTestModule = new TestModule();
private int mTestStep = 0;
private static int NUM_OF_CONTACTS = 3;
private static final int MAX_MODIFY_NOWPLUS_DETAILS_COUNT = 100;
private static String LOG_TAG = "NowPlusContactsTableTest";
public NowPlusContactDetailsTableTest() {
super();
}
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
private void startSubTest(String function, String description) {
Log.i(LOG_TAG, function + " - step " + mTestStep + ": " + description);
mTestStep++;
}
private void createTable() {
try {
ContactDetailsTable.create(mTestDatabase.getWritableDatabase());
} catch (SQLException e) {
fail("An exception occurred when creating the table: " + e);
}
}
@SmallTest
public void testCreate() {
Log.i(LOG_TAG, "***** EXECUTING testCreate *****");
final String fnName = "testCreate";
mTestStep = 1;
startSubTest(fnName, "Creating table");
createTable();
Log.i(LOG_TAG, "*************************************");
Log.i(LOG_TAG, "testCreate has completed successfully");
Log.i(LOG_TAG, "**************************************");
}
@MediumTest
public void testAddFetchContactDetail() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
// try to add a detail before creating a table
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to fetch detail before creating a table
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
TestModule.generateRandomLong(), readableDb);
assertEquals(null, fetchedDetail);
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is null
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
detail.localContactID = TestModule.generateRandomLong();
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testDeleteContactDetail() {
final String fnName = "testDeleteContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Deltes a contact detail from the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
// try to delete contact by contact id before creating a table
ServiceStatus status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
// try to delete contact by detail id before creating a table
assertFalse(ContactDetailsTable.deleteDetailByDetailId(TestModule
.generateRandomLong(), writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// delete previously added contact
status = ContactDetailsTable.deleteDetailByContactId(
detail.localContactID, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(null, fetchedDetail);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// try to delete contact by detail id
assertTrue(ContactDetailsTable.deleteDetailByDetailId(
detail.localDetailID, writeableDb));
// fetch deleted detail (should be null)
fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(null, fetchedDetail);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testModifyContactDetail() {
final String fnName = "testModifyContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Modifies a contact detail in the contacts detail table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = TestModule.generateRandomLong();
Long serverId = TestModule.generateRandomLong();
// try to modify detail before creating a table
ServiceStatus status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_DATABASE_CORRUPT, status);
- assertFalse(ContactDetailsTable.modifyDetailServerId(TestModule
+ assertFalse(ContactDetailsTable.syncSetServerId(TestModule
.generateRandomLong(), serverId, writeableDb));
startSubTest(fnName, "Creating table");
createTable();
// try to modify detail before adding it
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status);
// try to add detail with localContactID that is set
status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
mTestModule.modifyDummyDetailsData(detail);
status = ContactDetailsTable.modifyDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch modified detail
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
- assertTrue(ContactDetailsTable.modifyDetailServerId(
+ assertTrue(ContactDetailsTable.syncSetServerId(
detail.localDetailID, serverId, writeableDb));
ContactDetail modServIdDetail = ContactDetailsTable.fetchDetail(
detail.localDetailID, readableDb);
assertEquals(serverId,modServIdDetail.unique_id);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testContactsMatch() {
final String fnName = "testContactsMatch";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates doContactsMatch method");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
Contact contact = mTestModule.createDummyContactData();
contact.localContactID = TestModule.generateRandomLong();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> detailIdList = new ArrayList<NativeIdInfo>();
assertFalse(ContactDetailsTable.doContactsMatch(contact,
contact.localContactID, detailIdList, readableDb));
ServiceStatus status;
for (ContactDetail cd : contact.details) {
cd.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(cd, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
}
// assertTrue(ContactDetailsTable.doContactsMatch(contact,
// contact.localContactID, detailIdList, readableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfetchPreferredDetail() {
final String fnName = "testPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail preferredDetail = new ContactDetail();
preferredDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
preferredDetail.setTel("07967 654321", ContactDetail.DetailKeyTypes.CELL);
preferredDetail.localContactID = detail.localContactID;
preferredDetail.order = 0;
status = ContactDetailsTable.addContactDetail(preferredDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail altDetail = new ContactDetail();
assertTrue(ContactDetailsTable.fetchPreferredDetail(preferredDetail.localContactID.longValue(),
ContactDetail.DetailKeys.VCARD_PHONE.ordinal(), altDetail, readableDb));
// detail is preferred so should have the same fields
assertEquals(preferredDetail.localDetailID, altDetail.localDetailID);
assertEquals(preferredDetail.keyType, altDetail.keyType);
assertEquals(preferredDetail.value, altDetail.value);
assertEquals(preferredDetail.order, altDetail.order);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testfixPreferredDetail() {
final String fnName = "testfixPreferredDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
startSubTest(fnName, "Creating table");
createTable();
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
ContactDetail detail = new ContactDetail();
detail.key = ContactDetail.DetailKeys.VCARD_PHONE;
detail.setTel("07967 123456", ContactDetail.DetailKeyTypes.CELL);
detail.order = 50; // not preferred detail
detail.localContactID = TestModule.generateRandomLong();
ServiceStatus status = ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
status = ContactDetailsTable.fixPreferredValues(detail.localContactID,
writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// fetch deleted detail (should be null)
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(detail.localDetailID,
readableDb);
assertEquals(0, fetchedDetail.order.intValue()); // detail is now preferred
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFetchContactInfo() {
final String fnName = "testAddFetchContactDetail";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG,
"Adds a contact details to the contacts details table, validating all the way");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = TestModule.generateRandomLong();
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
ServiceStatus status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
nameDetail.localContactID = phoneDetail.localContactID;
status = ContactDetailsTable.addContactDetail(nameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchName = new ContactDetail();
ContactDetail fetchPhone = new ContactDetail();
status = ContactDetailsTable.fetchContactInfo(number, fetchPhone, fetchName, readableDb);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchPhone));
assertTrue(DatabaseHelper.doDetailsMatch(nameDetail, fetchName));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testFindNativeContact() {
final String fnName = "testFindNativeContact";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create contact
Contact contact = new Contact();
contact.synctophone = true;
// add contact to to the ContactsTable
ContactsTable.create(mTestDatabase.getWritableDatabase());
ServiceStatus status = ContactsTable.addContact(contact,readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// add contact to ContactSummaryTable
ContactSummaryTable.create(mTestDatabase.getWritableDatabase());
status = ContactSummaryTable.addContact(contact, readableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
contact.details.add(emailDetail);
assertTrue(ContactDetailsTable.findNativeContact(contact, writeableDb));
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFetchContactDetailsForNative() {
final String fnName = "testFetchContactDetailsForNative";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
Contact contact = new Contact();
contact.localContactID = TestModule.generateRandomLong();
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = contact.localContactID;
nicknameDetail.nativeContactId = TestModule.generateRandomInt();
ServiceStatus status = ContactDetailsTable.addContactDetail(nicknameDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
List<ContactDetail> addedDetails = new ArrayList<ContactDetail>();
addedDetails.add(nicknameDetail);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = contact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
//phoneDetail.nativeContactId = mTestModule.GenerateRandomInt();
phoneDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(phoneDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(phoneDetail);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = contact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
//emailDetail.nativeContactId = mTestModule.GenerateRandomInt();
emailDetail.nativeContactId = nicknameDetail.nativeContactId;
status = ContactDetailsTable.addContactDetail(emailDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
addedDetails.add(emailDetail);
ContactDetail.DetailKeys[] keyList = {
ContactDetail.DetailKeys.VCARD_NICKNAME,
ContactDetail.DetailKeys.VCARD_PHONE,
ContactDetail.DetailKeys.VCARD_EMAIL };
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
assertTrue(ContactDetailsTable.fetchContactDetailsForNative(detailList, keyList, false, 0,
MAX_MODIFY_NOWPLUS_DETAILS_COUNT, readableDb));
for (int i = 0; i < detailList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailList.get(i),
addedDetails.get(i)));
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
public void testFindLocalContactIdByKey() {
final String fnName = "testFindLocalContactIdByKey";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
// create local detail
ContactDetail localDetail = new ContactDetail();
localDetail.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail.nativeContactId = TestModule.generateRandomInt();
localDetail.nativeDetailId = TestModule.generateRandomInt();
localDetail.nativeVal1 = "nativeVal1";
localDetail.nativeVal2 = "nativeVal2";
localDetail.nativeVal3 = "nativeVal3";
localDetail.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
localDetail.alt = "google";
String imAddress = "[email protected]";
localDetail.setValue(imAddress, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status = ContactDetailsTable.addContactDetail(localDetail, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
// create local detail
ContactDetail localDetail2 = new ContactDetail();
localDetail2.localContactID = TestModule.generateRandomLong();
// populate native data
localDetail2.nativeContactId = TestModule.generateRandomInt();
localDetail2.nativeDetailId = TestModule.generateRandomInt();
localDetail2.nativeVal1 = "nativeVal1";
localDetail2.nativeVal2 = "nativeVal2";
localDetail2.nativeVal3 = "nativeVal3";
localDetail2.key = ContactDetail.DetailKeys.VCARD_IMADDRESS;
String imAddress2 = "[email protected]";
localDetail2.setValue(imAddress2, ContactDetail.DetailKeys.VCARD_IMADDRESS, null);
ServiceStatus status2 = ContactDetailsTable.addContactDetail(localDetail2, true, true, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status2);
long result = ContactDetailsTable.findLocalContactIdByKey("google", "[email protected]", ContactDetail.DetailKeys.VCARD_IMADDRESS, readableDb);
assertTrue("The contact ids don't match: expected=" + localDetail.localContactID + ", actual="+ result,result == localDetail.localContactID);
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
@MediumTest
public void testsyncSetServerIds() {
final String fnName = "testsyncSetServerIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetServerIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ServerIdInfo> detailServerIdList = new ArrayList<ServerIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
ServerIdInfo serverInfo = new ServerIdInfo();
serverInfo.localId = detail.localDetailID;
serverInfo.serverId = TestModule.generateRandomLong();
detailServerIdList.add(serverInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetServerIds(
detailServerIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
detailsList.get(i).localDetailID, readableDb);
assertNotNull(fetchedDetail);
assertEquals(detailServerIdList.get(i).serverId, fetchedDetail.unique_id);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncNativeIds
*/
public void testSyncSetNativeIds() {
final String fnName = "testSyncSetNativeIds";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncSetNativeIds details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<NativeIdInfo> nativeIdList = new ArrayList<NativeIdInfo>();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
NativeIdInfo nativeIdInfo = new NativeIdInfo();
nativeIdInfo.nativeContactId = TestModule.generateRandomInt();
nativeIdInfo.localId = detail.localDetailID;
nativeIdList.add(nativeIdInfo);
detailsList.add(detail);
}
ServiceStatus status = ContactDetailsTable.syncSetNativeIds(
nativeIdList, writeableDb);
assertEquals(ServiceStatus.SUCCESS, status);
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail fetchedDetail = ContactDetailsTable.fetchDetail(
nativeIdList.get(i).localId, readableDb);
assertNotNull(fetchedDetail);
assertEquals(nativeIdList.get(i).nativeContactId, fetchedDetail.nativeContactId);
}
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchContactChanges
*/
public void testSyncServerFetchContactChanges() {
final String fnName = "testSyncServerFetchContactChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
createTable();
List<ContactDetail> detailsList = new ArrayList<ContactDetail>();
for (int i = 0; i < NUM_OF_CONTACTS; i++) {
ContactDetail detail = new ContactDetail();
detail.localContactID = TestModule.generateRandomLong();
mTestModule.createDummyDetailsData(detail);
ContactDetailsTable.addContactDetail(detail, true, true, writeableDb);
detailsList.add(detail);
}
Cursor cursor = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, true);
assertEquals(NUM_OF_CONTACTS, cursor.getCount());
Cursor cursorOldContacts = ContactDetailsTable.syncServerFetchContactChanges(
readableDb, false);
assertEquals(0, cursorOldContacts.getCount());
cursorOldContacts.close();
List<Contact> contactList = new ArrayList<Contact>();
ContactDetailsTable.syncServerGetNextNewContactDetails(cursor, contactList, NUM_OF_CONTACTS);
for (int i = 0; i < contactList.size(); i++) {
assertTrue(DatabaseHelper.doDetailsMatch(detailsList.get(i),
contactList.get(i).details.get(0)));
}
cursor.close();
Log.i(LOG_TAG, "***********************************************");
Log.i(LOG_TAG, fnName + " has completed successfully");
Log.i(LOG_TAG, "***********************************************");
}
/*
* test syncServerFetchNoOfChanges
*/
public void testSyncServerFetchNoOfChanges() {
final String fnName = "testSyncServerFetchNoOfChanges";
mTestStep = 1;
Log.i(LOG_TAG, "***** EXECUTING " + fnName + "*****");
Log.i(LOG_TAG, "Validates syncServerFetchContactChanges details");
SQLiteDatabase writeableDb = mTestDatabase.getWritableDatabase();
SQLiteDatabase readableDb = mTestDatabase.getReadableDatabase();
startSubTest(fnName, "Creating table");
diff --git a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
index adac32c..ffd80da 100644
--- a/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
+++ b/tests/src/com/vodafone360/people/tests/database/NowPlusContactsTest.java
@@ -23,536 +23,536 @@
* Use is subject to license terms.
*/
package com.vodafone360.people.tests.database;
import java.util.ArrayList;
import java.util.List;
import android.database.sqlite.SQLiteDatabase;
import android.test.ApplicationTestCase;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.Suppress;
import android.util.Log;
import com.vodafone360.people.MainApplication;
import com.vodafone360.people.database.DatabaseHelper;
import com.vodafone360.people.database.DatabaseHelper.ServerIdInfo;
import com.vodafone360.people.database.tables.ContactDetailsTable;
import com.vodafone360.people.database.tables.ContactSummaryTable;
import com.vodafone360.people.database.tables.ContactsTable;
import com.vodafone360.people.datatypes.Contact;
import com.vodafone360.people.datatypes.ContactDetail;
import com.vodafone360.people.datatypes.ContactSummary;
import com.vodafone360.people.engine.meprofile.SyncMeDbUtils;
import com.vodafone360.people.service.ServiceStatus;
import com.vodafone360.people.tests.TestModule;
public class NowPlusContactsTest extends ApplicationTestCase<MainApplication> {
private static String LOG_TAG = "NowPlusDatabaseTest";
final static int WAIT_EVENT_TIMEOUT_MS = 30000;
final static int NUM_OF_CONTACTS = 3;
private static MainApplication mApplication = null;
private static DatabaseHelper mDatabaseHelper = null;
final TestModule mTestModule = new TestModule();
private DbTestUtility mTestUtility;
public NowPlusContactsTest() {
super(MainApplication.class);
}
private boolean initialise() {
mTestUtility = new DbTestUtility(getContext());
createApplication();
mApplication = getApplication();
if(mApplication == null){
Log.e(LOG_TAG, "Unable to create main application");
return false;
}
mDatabaseHelper = mApplication.getDatabase();
if (mDatabaseHelper.getReadableDatabase() == null) {
return false;
}
mTestUtility.startEventWatcher(mDatabaseHelper);
return true;
}
private void shutdown() {
mTestUtility.stopEventWatcher();
}
/***
* Check if contact detail was added to ContactSummary.
* If contact detail is a name check if it's name in formatted state
* is the same as contact summary formatted name.
* @param cd ContactDetail
* @return boolean true if ContactDetail is in ContactSummaryTable
*/
private boolean isContactDetailInSummary(ContactDetail cd) {
//boolean result = true;
ContactSummary cs = new ContactSummary();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
ServiceStatus status = ContactSummaryTable.fetchSummaryItem(
cd.localContactID, cs, db);
if (status != ServiceStatus.SUCCESS) {
return false;
} else if (ContactDetail.DetailKeys.VCARD_NAME == cd.key
&& !cd.getName().toString().equals(cs.formattedName)) {
// if ContactDetail name is different then ContactSummary name
return false;
} else {
return true;
}
}
@SmallTest
@Suppress
public void testMeProfiles() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact meProfile = mTestModule.createDummyContactData();
// assertFalse(mDatabaseHelper.getMeProfileChanged());
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(SyncMeDbUtils.getMeProfileLocalContactId(mDatabaseHelper), meProfile.localContactID);
Contact fetchedMe = new Contact();
status = SyncMeDbUtils.fetchMeProfile(mDatabaseHelper,fetchedMe);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(fetchedMe, meProfile));
// Modify me Profile
Contact meProfile2 = mTestModule.createDummyContactData();
status = SyncMeDbUtils.setMeProfile(mDatabaseHelper,meProfile2);
assertEquals(ServiceStatus.SUCCESS, status);
// assertTrue(mDatabaseHelper.getMeProfileChanged());
shutdown();
}
@SmallTest
public void testAddContactToGroup() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long groupId = 1L;
status = mDatabaseHelper.addContactToGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.deleteContactFromGroup(addedContact.localContactID.longValue(), groupId);
assertEquals(ServiceStatus.ERROR_NOT_READY, status);
shutdown();
}
@SmallTest
public void testSyncSetServerIds() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
long serverId = addedContact.localContactID + 1;
long userId = addedContact.localContactID + 2;
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = addedContact.localContactID;
info.serverId = serverId;
info.userId = userId;
serverIdList.add(info);
status = ContactsTable.syncSetServerIds(serverIdList, null, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
addedContact.contactID = serverId;
addedContact.userID = userId;
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContactByServerId(serverId, fetchedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, fetchedContact));
shutdown();
}
@SmallTest
@Suppress
public void testAddContactDetail() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
status = mDatabaseHelper.addContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
ContactDetail fetchedDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(detail, fetchedDetail));
assertTrue(!DatabaseHelper.hasDetailChanged(detail, fetchedDetail));
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.deleteAllGroups());
List<ServerIdInfo> serverIdList = new ArrayList<ServerIdInfo>();
ServerIdInfo info = new ServerIdInfo();
info.localId = fetchedDetail.localDetailID;
info.serverId = fetchedDetail.localDetailID + 1;
serverIdList.add(info);
status = ContactDetailsTable.syncSetServerIds(serverIdList, mDatabaseHelper.getWritableDatabase());
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertEquals(info.serverId, fetchedDetail.unique_id);
shutdown();
}
@MediumTest
public void testAddModifyContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddModifyContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add/modify details contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Modify contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(isContactDetailInSummary(detail));
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: contacts and check if modification was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
mTestModule.modifyDummyDetailsData(detail);
status = mDatabaseHelper.modifyContactDetail(detail);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if modifyContactDatail works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContactsDetails() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContactsDetails *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts details)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts detatils and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
for (int j = 0; j < inputContacts[i].details.size() ; j++) {
ContactDetail detail = inputContacts[i].details.get(j);
status = mDatabaseHelper.deleteContactDetail(detail.localDetailID);
assertEquals(ServiceStatus.SUCCESS, status);
}
// check if deletion works good
Contact modifiedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, modifiedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(modifiedContact, inputContacts[i]));
}
shutdown();
}
@MediumTest
public void testAddDeleteContacts() {
Log.i(LOG_TAG, "***** EXECUTING testAddDeleteContacts *****");
Log.i(LOG_TAG, "Test contact functionality (add delete contacts)");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
Log.i(LOG_TAG, "Test 1c: Add " + NUM_OF_CONTACTS + " random contacts");
// add contacts and check if added contacts are the same as fetched
Contact [] inputContacts = new Contact[NUM_OF_CONTACTS];
Contact addedContact = new Contact();
for (int i = 0 ; i < NUM_OF_CONTACTS; i++) {
inputContacts[i] = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(inputContacts[i]);
assertEquals(ServiceStatus.SUCCESS, status);
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(TestModule.doContactsMatch(addedContact, inputContacts[i]));
}
Log.i(LOG_TAG, "Test 1d: Delete contacts and check if deletion was correct");
for (int i = 0; i < inputContacts.length; i++) {
// check if deletion works good
status = mDatabaseHelper.deleteContact(inputContacts[i].localContactID);
assertEquals(ServiceStatus.SUCCESS, status);
Contact removedContact = new Contact();
status = mDatabaseHelper.fetchContact(inputContacts[i].localContactID, removedContact);
assertEquals(ServiceStatus.ERROR_NOT_FOUND, status); // contact was deleted so it shouldn't be found
}
shutdown();
}
@SmallTest
public void testSyncAddContactDetailList() {
Log.i(LOG_TAG, "***** EXECUTING testSyncAddContactDetailList *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(
WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail cd = new ContactDetail();
mTestModule.createDummyDetailsData(cd);
cd.localContactID = addedContact.localContactID;
cd.nativeContactId = TestModule.generateRandomInt();
cd.nativeDetailId = TestModule.generateRandomInt();
cd.nativeVal1 = TestModule.generateRandomString();
cd.nativeVal2 = TestModule.generateRandomString();
cd.nativeVal3 = TestModule.generateRandomString();
List<ContactDetail> detailList = new ArrayList<ContactDetail>();
detailList.add(cd);
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.syncAddContactDetailList(detailList, false, false));
Contact modifiedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS,
mDatabaseHelper.fetchContact(addedContact.localContactID, modifiedContact));
for (ContactDetail fetchedDetail : modifiedContact.details) {
for (ContactDetail contactDetail : detailList) {
if (fetchedDetail.key == contactDetail.key) {
assertEquals(contactDetail.nativeVal1, fetchedDetail.nativeVal1);
assertEquals(contactDetail.nativeVal2, fetchedDetail.nativeVal2);
assertEquals(contactDetail.nativeVal3, fetchedDetail.nativeVal3);
}
}
}
shutdown();
}
@SmallTest
public void testFetchContactInfo() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test contact add sync contact detail list");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact addedContact = new Contact();
status = mDatabaseHelper.addContact(addedContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = addedContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact c = new Contact();
ContactDetail fetchedPhoneDetail = new ContactDetail();
status = mDatabaseHelper.fetchContactInfo(number, c, fetchedPhoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
assertTrue(DatabaseHelper.doDetailsMatch(phoneDetail, fetchedPhoneDetail));
shutdown();
}
@SmallTest
public void testFindNativeContact() {
Log.i(LOG_TAG, "***** EXECUTING testFetchContactInfo *****");
Log.i(LOG_TAG, "Test Find Native Contact");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// add contacts and check if added contacts are the same as fetched
Contact nativeContact = new Contact();
nativeContact.synctophone = true;
status = mDatabaseHelper.addContact(nativeContact);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add NameDetail
ContactDetail nameDetail = mTestModule.createDummyDetailsName();
ContactDetail nicknameDetail = mTestModule.createDummyDetailsNickname(nameDetail);
nicknameDetail.localContactID = nativeContact.localContactID;
status = mDatabaseHelper.addContactDetail(nicknameDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail phoneDetail = new ContactDetail();
phoneDetail.localContactID = nativeContact.localContactID;
phoneDetail.key = ContactDetail.DetailKeys.VCARD_PHONE;
String number = "07967 123456";
phoneDetail.setTel(number, ContactDetail.DetailKeyTypes.CELL);
status = mDatabaseHelper.addContactDetail(phoneDetail);
assertEquals(ServiceStatus.SUCCESS, status);
// create and add phoneDetail
ContactDetail emailDetail = new ContactDetail();
emailDetail.localContactID = nativeContact.localContactID;
emailDetail.key = ContactDetail.DetailKeys.VCARD_EMAIL;
emailDetail.setEmail(
TestModule.generateRandomString() + "@mail.co.uk",
ContactDetail.DetailKeyTypes.HOME);
status = mDatabaseHelper.addContactDetail(emailDetail);
assertEquals(ServiceStatus.SUCCESS, status);
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(nativeContact.localContactID, fetchedContact);
assertTrue(mDatabaseHelper.findNativeContact(fetchedContact));
Contact c = new Contact();
assertFalse(mDatabaseHelper.findNativeContact(c));
shutdown();
}
@SmallTest
public void testModifyContactServerId() {
Log.i(LOG_TAG, "***** EXECUTING testModifyContactServerId *****");
Log.i(LOG_TAG, "Test Modify Contact ServerId");
Log.i(LOG_TAG, "Test 1a: Initialise test environment and load database");
assertTrue(initialise());
Log.i(LOG_TAG, "Test 1b: Remove user data");
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK);
// create and add contact
Contact c = mTestModule.createDummyContactData();
status = mDatabaseHelper.addContact(c);
assertEquals(ServiceStatus.SUCCESS, status);
Long serverId = TestModule.generateRandomLong();
assertTrue(mDatabaseHelper.modifyContactServerId(c.localContactID, serverId, c.userID));
Contact fetchedContact = new Contact();
status = mDatabaseHelper.fetchContact(c.localContactID, fetchedContact);
assertEquals(serverId, fetchedContact.contactID);
shutdown();
}
@SmallTest
@Suppress
public void testModifyDetailServerId() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
assertEquals(ServiceStatus.SUCCESS, mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS, DbTestUtility.CONTACTS_INT_EVENT_MASK));
Contact addedContact = new Contact();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContact(addedContact));
ContactDetail detail = new ContactDetail();
mTestModule.createDummyDetailsData(detail);
detail.localContactID = addedContact.localContactID;
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.addContactDetail(detail));
Long serverDetailId = detail.localContactID + TestModule.generateRandomLong();
- assertTrue(mDatabaseHelper.modifyContactDetailServerId(detail.localDetailID, serverDetailId));
+ assertTrue(mDatabaseHelper.syncContactDetail(detail.localDetailID, serverDetailId));
ContactDetail fetchedDetail = new ContactDetail();
assertEquals(ServiceStatus.SUCCESS, mDatabaseHelper.fetchContactDetail(detail.localDetailID, fetchedDetail));
assertEquals(serverDetailId, fetchedDetail.unique_id);
shutdown();
}
@SmallTest
public void testOnUpgrade() {
assertTrue(initialise());
mDatabaseHelper.removeUserData();
ServiceStatus status = mTestUtility.waitForEvent(WAIT_EVENT_TIMEOUT_MS,
DbTestUtility.CONTACTS_INT_EVENT_MASK);
assertEquals(ServiceStatus.SUCCESS, status);
int oldVersion = TestModule.generateRandomInt();
int newVersion = TestModule.generateRandomInt();
SQLiteDatabase db = mDatabaseHelper.getWritableDatabase();
mDatabaseHelper.onUpgrade(db, oldVersion, newVersion);
shutdown();
}
}
\ No newline at end of file
|
360/360-Engine-for-Android
|
1342141fa81443b932c32dcc6af2c8a084235661
|
PAND-1546: ContactSyncEgine has wrong processor order during first time sync
|
diff --git a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
index 3b661da..a450b4d 100644
--- a/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
+++ b/src/com/vodafone360/people/engine/contactsync/ContactSyncEngine.java
@@ -717,1013 +717,1011 @@ public class ContactSyncEngine extends BaseEngine implements IContactSyncCallbac
if (mRemoveUserData) {
mFirstTimeSyncStarted = false;
mFirstTimeSyncComplete = false;
mFirstTimeNativeSyncComplete = false;
mRemoveUserData = false;
super.onReset();
}
return;
}
}
if (processTimeout()) {
return;
}
if (isUiRequestOutstanding()) {
mActiveUiRequestBackup = mActiveUiRequest;
if (processUiQueue()) {
return;
}
}
if (isCommsResponseOutstanding() && processCommsInQueue()) {
return;
}
if (readyToStartServerSync()) {
if (mThumbnailSyncRequired) {
startThumbnailSync();
return;
}
if (mFullSyncRequired) {
startFullSync();
return;
}
if (mServerSyncRequired) {
startServerSync();
return;
}
}
if (mNativeFetchSyncRequired && readyToStartFetchNativeSync()) {
startFetchNativeSync();
return;
}
if (mNativeUpdateSyncRequired && readyToStartUpdateNativeSync()) {
startUpdateNativeSync();
return;
}
}
/**
* Called by base class when a contact sync UI request has been completed.
* Not currently used.
*/
@Override
protected void onRequestComplete() {
}
/**
* Called by base class when a timeout has been completed. If there is an
* active processor the timeout event will be passed to it, otherwise the
* engine will check if it needs to schedule a new sync and set the next
* pending timeout.
*/
@Override
protected void onTimeoutEvent() {
if (mActiveProcessor != null) {
mActiveProcessor.onTimeoutEvent();
} else {
startSyncIfRequired();
setTimeoutIfRequired();
}
}
/**
* Based on current timeout values schedules a new sync if required.
*/
private void startSyncIfRequired() {
if (mFirstTimeSyncStarted && !mFirstTimeSyncComplete) {
mFullSyncRequired = true;
mFullSyncRetryCount = 0;
}
long currentTimeMs = System.currentTimeMillis();
if (mServerSyncTimeout != null && mServerSyncTimeout.longValue() < currentTimeMs) {
mServerSyncRequired = true;
mServerSyncTimeout = null;
} else if (mFetchNativeSyncTimeout != null
&& mFetchNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeFetchSyncRequired = true;
mFetchNativeSyncTimeout = null;
} else if (mUpdateNativeSyncTimeout != null
&& mUpdateNativeSyncTimeout.longValue() < currentTimeMs) {
mNativeUpdateSyncRequired = true;
mUpdateNativeSyncTimeout = null;
}
}
/**
* Called when a response to a request or a push message is received from
* the server. Push messages are processed by the engine, responses are
* passed to the active processor.
*
* @param resp Response or push message received
*/
@Override
protected void processCommsResponse(Response resp) {
if (processPushEvent(resp)) {
return;
}
if (resp.mDataTypes != null && resp.mDataTypes.size() > 0) {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = " + resp.mDataTypes.get(0).name());
} else {
LogUtils.logD("ContactSyncEngine.processCommsResponse: Req ID = " + resp.mReqId
+ ", type = NULL");
}
if (mActiveProcessor != null) {
mActiveProcessor.processCommsResponse(resp);
}
}
/**
* Determines if a given response is a push message and processes in this
* case TODO: we need the check for Me Profile be migrated to he new engine
*
* @param resp Response to check and process
* @return true if the response was processed
*/
private boolean processPushEvent(Response resp) {
if (resp.mDataTypes == null || resp.mDataTypes.size() == 0) {
return false;
}
BaseDataType dataType = resp.mDataTypes.get(0);
if ((dataType == null) || !dataType.name().equals("PushEvent")) {
return false;
}
PushEvent pushEvent = (PushEvent)dataType;
LogUtils.logV("Push Event Type = " + pushEvent.mMessageType);
switch (pushEvent.mMessageType) {
case CONTACTS_CHANGE:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - Contacts changed push message received");
mServerSyncRequired = true;
EngineManager.getInstance().getGroupsEngine().addUiGetGroupsRequest(); // fetch
// the
// newest
// groups
mEventCallback.kickWorkerThread();
break;
case SYSTEM_NOTIFICATION:
LogUtils
.logI("ContactSyncEngine.processCommsResponse - System notification push message received");
break;
default:
// do nothing.
break;
}
return true;
}
/**
* Called by base class to process a NOWPLUSSYNC UI request. This will be
* called to process a full sync or server sync UI request.
*
* @param requestId ID of the request to process, only
* ServiceUiRequest.NOWPLUSSYNC is currently supported.
* @param data Type is determined by request ID, in case of NOWPLUSSYNC this
* is a flag which determines if a full sync is required (true =
* full sync, false = server sync).
*/
@Override
protected void processUiRequest(ServiceUiRequest requestId, Object data) {
switch (requestId) {
case NOWPLUSSYNC:
final SyncParams params = (SyncParams)data;
if (params.isFull) {
// delayed full sync is not supported currently, start it
// immediately
clearCurrentSyncAndPatchBaseEngine();
mFullSyncRetryCount = 0;
startFullSync();
} else {
if (params.delay <= 0) {
clearCurrentSyncAndPatchBaseEngine();
if (readyToStartServerSync()) {
startServerSync();
} else {
mServerSyncRequired = true;
}
} else {
startServerContactSyncTimer(params.delay);
}
}
break;
default:
// do nothing.
break;
}
}
/**
* Called by the run function when the {@link #mCancelSync} flag is set to
* true. Cancels the active processor and completes the current UI request.
*/
private void cancelSync() {
if (mActiveProcessor != null) {
mActiveProcessor.cancel();
mActiveProcessor = null;
}
completeSync(ServiceStatus.USER_CANCELLED);
}
/**
* Clears the current sync and make sure that if we cancel a previous sync,
* it doesn't notify a wrong UI request. TODO: Find another way to not have
* to hack the BaseEngine!
*/
private void clearCurrentSyncAndPatchBaseEngine() {
// Cancel background sync
if (mActiveProcessor != null) {
// the mActiveUiRequest is already the new one so if
// onCompleteUiRequest(Error) is called,
// this will reset it to null even if we didn't start to process it.
ServiceUiRequest newActiveUiRequest = mActiveUiRequest;
mActiveUiRequest = mActiveUiRequestBackup;
mActiveProcessor.cancel();
// restore the active UI request...
mActiveUiRequest = newActiveUiRequest;
mActiveProcessor = null;
}
newState(State.IDLE);
}
/**
* Checks if a server sync can be started based on network conditions and
* engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartServerSync() {
if (!Settings.ENABLE_SERVER_CONTACT_SYNC) {
return false;
}
if (!EngineManager.getInstance().getSyncMeEngine().isFirstTimeMeSyncComplete()) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE || NetworkAgent.getAgentState() != AgentState.CONNECTED) {
return false;
}
return true;
}
/**
* Checks if a fetch native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartFetchNativeSync() {
if (!Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Checks if a update native sync can be started based on network conditions
* and engine state
*
* @return true if a sync can be started, false otherwise.
*/
private boolean readyToStartUpdateNativeSync() {
if (!Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
return false;
}
if (!mFirstTimeSyncStarted) {
return false;
}
if (mState != State.IDLE) {
return false;
}
return true;
}
/**
* Starts a full sync. If the native contacts haven't yet been fetched then
* a first time sync will be started, otherwise will start a normal full
* sync. Full syncs are always initiated from the UI (via UI request).
*/
public void startFullSync() {
mFailureList = "";
mDatabaseChanged = false;
setFirstTimeSyncStarted(true);
mServerSyncTimeout = null;
mFullSyncRequired = false;
if (mFirstTimeNativeSyncComplete) {
LogUtils.logI("ContactSyncEngine.startFullSync - user triggered sync");
mMode = Mode.FULL_SYNC;
nextTaskFullSyncNormal();
} else {
LogUtils.logI("ContactSyncEngine.startFullSync - first time sync");
mMode = Mode.FULL_SYNC_FIRST_TIME;
nextTaskFullSyncFirstTime();
}
}
/**
* Starts a server sync. This will only sync contacts with the server and
* will not include the me profile. Thumbnails are not fetched as part of
* this sync, but will be fetched as part of a background sync afterwards.
*/
private void startServerSync() {
mServerSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.SERVER_SYNC;
mServerSyncTimeout = null;
setTimeoutIfRequired();
nextTaskServerSync();
}
/**
* Starts a background thumbnail sync
*/
private void startThumbnailSync() {
mThumbnailSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.THUMBNAIL_SYNC;
nextTaskThumbnailSync();
}
/**
* Starts a background fetch native contacts sync
*/
private void startFetchNativeSync() {
mNativeFetchSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.FETCH_NATIVE_SYNC;
mFetchNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskFetchNativeContacts();
}
/**
* Starts a background update native contacts sync
*/
private void startUpdateNativeSync() {
mNativeUpdateSyncRequired = false;
mFailureList = "";
mDatabaseChanged = false;
mMode = Mode.UPDATE_NATIVE_SYNC;
mUpdateNativeSyncTimeout = null;
setTimeoutIfRequired();
nextTaskUpdateNativeContacts();
}
/**
* Helper function to start the fetch native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startFetchNativeContacts() {
if (Settings.ENABLE_FETCH_NATIVE_CONTACTS) {
newState(State.FETCHING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.FETCH_NATIVE_CONTACTS, this,
mDb, mContext, mCr));
return true;
}
return false;
}
/**
* Helper function to start the update native contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUpdateNativeContacts() {
if (Settings.ENABLE_UPDATE_NATIVE_CONTACTS) {
newState(State.UPDATING_NATIVE_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPDATE_NATIVE_CONTACTS, this,
mDb, null, mCr));
return true;
}
return false;
}
/**
* Helper function to start the download server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.FETCHING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.DOWNLOAD_SERVER_CONTACTS,
this, mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the upload server contacts processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startUploadServerContacts() {
if (Settings.ENABLE_SERVER_CONTACT_SYNC) {
newState(State.UPDATING_SERVER_CONTACTS);
startProcessor(mProcessorFactory.create(ProcessorFactory.UPLOAD_SERVER_CONTACTS, this,
mDb, mContext, null));
return true;
}
return false;
}
/**
* Helper function to start the download thumbnails processor
*
* @return if this type of sync is enabled in the settings, false otherwise.
*/
private boolean startDownloadServerThumbnails() {
if (Settings.ENABLE_THUMBNAIL_SYNC) {
ThumbnailHandler.getInstance().downloadContactThumbnails();
return true;
}
return false;
}
/**
* Called by a processor when it has completed. Will move to the next task.
* When the active contact sync has totally finished, will complete any
* pending UI request.
*
* @param status Status of the sync from the processor, any error codes will
* stop the sync.
* @param failureList Contains a list of sync failure information which can
* be used as a summary at the end. Otherwise should be an empty
* string.
* @param data Any processor specific data to pass back to the engine. Not
* currently used.
*/
@Override
public void onProcessorComplete(ServiceStatus status, String failureList, Object data) {
if (mState == State.IDLE) {
return;
}
if (mActiveProcessor != null) {
mActiveProcessor.onComplete();
}
mActiveProcessor = null;
mFailureList += failureList;
if (status != ServiceStatus.SUCCESS) {
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Failed during " + mState
+ " with error " + status);
completeSync(status);
return;
}
if (mDbChangedByProcessor) {
switch (mState) {
case FETCHING_NATIVE_CONTACTS:
mServerSyncRequired = true;
break;
case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mNativeUpdateSyncRequired = true;
break;
default:
// Do nothing.
break;
}
}
switch (mMode) {
case FULL_SYNC_FIRST_TIME:
nextTaskFullSyncFirstTime();
break;
case FULL_SYNC:
nextTaskFullSyncNormal();
break;
case SERVER_SYNC:
nextTaskServerSync();
break;
case FETCH_NATIVE_SYNC:
nextTaskFetchNativeContacts();
break;
case UPDATE_NATIVE_SYNC:
nextTaskUpdateNativeContacts();
break;
case THUMBNAIL_SYNC:
nextTaskThumbnailSync();
break;
default:
LogUtils.logE("ContactSyncEngine.onProcessorComplete - Unexpected mode: " + mMode);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync first time mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncFirstTime() {
+
switch (mState) {
case IDLE:
- if (startDownloadServerContacts()) {
- return;
- }
- // Fall through
- case FETCHING_SERVER_CONTACTS:
- if (startFetchNativeContacts()) {
+ if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
setFirstTimeNativeSyncComplete(true);
if (startUploadServerContacts()) {
- return;
+ return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
- // force a thumbnail sync in case nothing in the database
- // changed but we still have failing
- // thumbnails that we should retry to download
+ if (startDownloadServerContacts()) {
+ return;
+ }
+ // Fall through
+ case FETCHING_SERVER_CONTACTS:
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncFirstTime - Unexpected state: "
- + mState);
+ + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the full sync normal mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFullSyncNormal() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
setFirstTimeSyncComplete(true);
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFullSyncNormal - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the fetch native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskFetchNativeContacts() {
switch (mState) {
case IDLE:
if (startFetchNativeContacts()) {
return;
}
// Fall through
case FETCHING_NATIVE_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskFetchNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the update native contacts mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskUpdateNativeContacts() {
switch (mState) {
case IDLE:
if (startUpdateNativeContacts()) {
return;
}
completeSync(ServiceStatus.SUCCESS);
return;
// Fall through
case UPDATING_NATIVE_CONTACTS:
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskUpdateNativeContacts - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the server sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskServerSync() {
switch (mState) {
case IDLE:
if (startDownloadServerContacts()) {
return;
}
// Fall through
case FETCHING_SERVER_CONTACTS:
if (startUploadServerContacts()) {
return;
}
// Fall through
case UPDATING_SERVER_CONTACTS:
// force a thumbnail sync in case nothing in the database
// changed but we still have failing
// thumbnails that we should retry to download
mThumbnailSyncRequired = true;
mLastServerSyncTime = System.currentTimeMillis();
completeSync(ServiceStatus.SUCCESS);
return;
default:
LogUtils.logE("ContactSyncEngine.nextTaskServerSync - Unexpected state: " + mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Moves to the next state for the thumbnail sync mode, and runs the
* appropriate processor. Completes the UI request when the sync is complete
* (if one is pending).
*/
private void nextTaskThumbnailSync() {
switch (mState) {
case IDLE:
if (startDownloadServerThumbnails()) {
return;
}
default:
LogUtils.logE("ContactSyncEngine.nextTaskThumbnailSync - Unexpected state: "
+ mState);
completeSync(ServiceStatus.ERROR_SYNC_FAILED);
}
}
/**
* Changes the state of the engine and informs the observers.
*
* @param newState The new state
*/
private void newState(State newState) {
State oldState = mState;
synchronized (mMutex) {
if (newState == mState) {
return;
}
mState = newState;
}
LogUtils.logV("ContactSyncEngine.newState: " + oldState + " -> " + mState);
fireStateChangeEvent(mMode, oldState, mState);
}
/**
* Called when the current mode has finished all the sync tasks. Completes
* the UI request if one is pending, sends an event to the observer and a
* database change event if necessary.
*
* @param status The overall status of the contact sync.
*/
private void completeSync(ServiceStatus status) {
if (mState == State.IDLE) {
return;
}
if (mDatabaseChanged) {
LogUtils.logD("ContactSyncEngine.completeSync - Firing Db changed event");
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
mDatabaseChanged = false;
}
mActiveProcessor = null;
newState(State.IDLE);
mMode = Mode.NONE;
completeUiRequest(status, mFailureList);
mCache.setSyncStatus(new SyncStatus(status));
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mFirstTimeSyncComplete) {
fireSyncCompleteEvent(status);
}
if (ServiceStatus.SUCCESS == status) {
startSyncIfRequired();
} else {
setTimeout(SYNC_ERROR_WAIT_TIMEOUT);
}
mLastStatus = status;
setTimeoutIfRequired();
}
/**
* Sets the current timeout to the next pending timer and kicks the engine
* if necessary.
*/
private synchronized void setTimeoutIfRequired() {
Long initTimeout = mCurrentTimeout;
if (mCurrentTimeout == null
|| (mServerSyncTimeout != null && mServerSyncTimeout.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mServerSyncTimeout;
}
if (mCurrentTimeout == null
|| (mFetchNativeSyncTimeout != null && mFetchNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mFetchNativeSyncTimeout;
}
if (mCurrentTimeout == null
|| (mUpdateNativeSyncTimeout != null && mUpdateNativeSyncTimeout
.compareTo(mCurrentTimeout) < 0)) {
mCurrentTimeout = mUpdateNativeSyncTimeout;
}
if (mCurrentTimeout != null && !mCurrentTimeout.equals(initTimeout)) {
mEventCallback.kickWorkerThread();
}
}
/**
* Called by the active processor to indicate that the NowPlus database has
* changed.
*/
@Override
public void onDatabaseChanged() {
mDatabaseChanged = true;
mDbChangedByProcessor = true;
final long currentTime = System.nanoTime();
if (mLastDbUpdateTime == null
|| mLastDbUpdateTime.longValue() + UI_REFRESH_WAIT_TIME_NANO < currentTime) {
LogUtils.logD("ContactSyncEngine.onDatabaseChanged - Updating UI...");
mDatabaseChanged = false;
mLastDbUpdateTime = currentTime;
mDb.fireDatabaseChangedEvent(DatabaseChangeType.CONTACTS, true);
}
}
/**
* Used by processors to fetch this engine. The BaseEngine reference is
* needed to send requests to the server.
*
* @return The BaseEngine reference of this engine.
*/
@Override
public BaseEngine getEngine() {
return this;
}
/**
* Used by active processor to set a timeout.
*
* @param timeout Timeout value based on current time in milliseconds
*/
@Override
public void setTimeout(long timeout) {
super.setTimeout(timeout);
}
/**
* Used by active processor to set the current progress.
*
* @param SyncStatus Status of the processor, must not be NULL.
* @throws InvalidParameterException when SyncStatus is NULL.
*/
@Override
public void setSyncStatus(final SyncStatus syncStatus) {
if (syncStatus == null) {
throw new InvalidParameterException(
"ContactSyncEngine.setSyncStatus() SyncStatus cannot be NULL");
}
mCache.setSyncStatus(syncStatus);
mUiAgent.sendUnsolicitedUiEvent(ServiceUiRequest.UPDATE_SYNC_STATE, null);
if (mState != State.IDLE && syncStatus.getProgress() != mCurrentProgressPercent) {
mCurrentProgressPercent = syncStatus.getProgress();
LogUtils.logI("ContactSyncEngine: Task " + mState + " is " + syncStatus.getProgress()
+ "% complete");
fireProgressEvent(mState, syncStatus.getProgress());
}
}
/**
* Called by active processor when issuing a request to store the request id
* in the base engine class.
*/
@Override
public void setActiveRequestId(int reqId) {
setReqId(reqId);
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncStarted} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been started. The flag is never set to false again by the
* engine, it will be only set to false when a remove user data
* is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncStarted(boolean value) {
if (mFirstTimeSyncStarted == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncStarted(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncStarted = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that first time sync
* has been completed. The flag is never set to false again by
* the engine, it will be only set to false when a remove user
* data is done (and the database is deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeSyncComplete = value;
}
}
return status;
}
/**
* Helper function to update the database when the state of the
* {@link #mFirstTimeNativeSyncComplete} flag changes.
*
* @param value New value to the flag. True indicates that the native fetch
* part of the first time sync has been completed. The flag is
* never set to false again by the engine, it will be only set to
* false when a remove user data is done (and the database is
* deleted).
* @return SUCCESS or a suitable error code if the database could not be
* updated.
*/
private ServiceStatus setFirstTimeNativeSyncComplete(boolean value) {
if (mFirstTimeSyncComplete == value) {
return ServiceStatus.SUCCESS;
}
PersistSettings setting = new PersistSettings();
setting.putFirstTimeNativeSyncComplete(value);
ServiceStatus status = mDb.setOption(setting);
if (ServiceStatus.SUCCESS == status) {
synchronized (this) {
mFirstTimeNativeSyncComplete = value;
}
}
return status;
}
/**
* Called when a database change event is received from the DatabaseHelper.
* Only internal database change events are processed, external change
* events are generated by the contact sync engine.
*
* @param msg The message indicating the type of event
*/
private void processDbMessage(Message message) {
final ServiceUiRequest event = ServiceUiRequest.getUiEvent(message.what);
switch (event) {
case DATABASE_CHANGED_EVENT:
if (message.arg1 == DatabaseHelper.DatabaseChangeType.CONTACTS.ordinal()
&& message.arg2 == 0) {
LogUtils.logV("ContactSyncEngine.processDbMessage - Contacts have changed");
// startMeProfileSyncTimer();
startServerContactSyncTimer(SERVER_CONTACT_SYNC_TIMEOUT_MS);
startUpdateNativeContactSyncTimer();
}
break;
default:
// Do nothing.
break;
}
}
/**
* Notifies observers when a state or mode change occurs.
*
* @param mode Current mode
* @param previousState State before the change
* @param newState State after the change.
*/
private void fireStateChangeEvent(Mode mode, State previousState, State newState) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onContactSyncStateChange(mode, previousState, newState);
}
if (Settings.ENABLED_DATABASE_TRACE) {
// DatabaseHelper.trace(false, "State newState[" + newState + "]" +
// mDb.copyDatabaseToSd(""));
}
}
/**
* Notifies observers when a contact sync complete event occurs.
*
* @param status SUCCESS or a suitable error code
*/
private void fireSyncCompleteEvent(ServiceStatus status) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onSyncComplete(status);
}
}
/**
* Notifies observers when the progress value changes for the current sync.
*
* @param currentState Current sync task being processed
* @param percent Progress of task (between 0 and 100 percent)
*/
private void fireProgressEvent(State currentState, int percent) {
ArrayList<IContactSyncObserver> tempList = new ArrayList<IContactSyncObserver>();
synchronized (this) {
tempList.addAll(mEventCallbackList);
}
for (IContactSyncObserver observer : tempList) {
observer.onProgressEvent(currentState, percent);
}
}
/**
* Called by framework to warn the engine that a remove user data is about
* to start. Sets flags and kicks the engine.
*/
@Override
public void onReset() {
synchronized (this) {
mCancelSync = true;
mRemoveUserData = true;
}
mEventCallback.kickWorkerThread();
}
/**
* @see NativeContactsApi.ContactsObserver#onChange()
*/
@Override
public void onChange() {
LogUtils.logD("ContactSyncEngine.onChange(): changes detected on native side.");
// changes detected on native side, start the timer for the
// FetchNativeContacts processor.
startFetchNativeContactSyncTimer();
}
}
diff --git a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
index cded745..889d1a9 100644
--- a/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
+++ b/src/com/vodafone360/people/engine/contactsync/SyncStatus.java
@@ -1,190 +1,190 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.contactsync;
import com.vodafone360.people.service.ServiceStatus;
/**
* In memory store for the current state of the Contacts sync engine.
*/
public class SyncStatus {
/** Sync tasks, each of which corresponds to a specific processor. **/
public enum Task {
- /** DownloadServerContacts is processing. */
- DOWNLOAD_SERVER_CONTACTS,
/** FetchNativeContacts is processing. */
FETCH_NATIVE_CONTACTS,
/** UploadServerContacts is processing. */
UPDATE_SERVER_CONTACTS,
+ /** DownloadServerContacts is processing. */
+ DOWNLOAD_SERVER_CONTACTS,
/** Last element is used to determine the size of the ENUM. **/
UNKNOWN
}
/** Sync task status. **/
public enum TaskStatus {
/** Sent X of Y contacts. */
SENT_CONTACTS,
/** Received X of Y contacts. */
RECEIVED_CONTACTS,
/** Sent X of Y changes. */
SENT_CHANGES,
/** Do not show task status (i.e. leave blank). */
NONE
}
/** ServiceStatus of sync outcome. **/
private ServiceStatus mServiceStatus;
/** Percentage of sync progress in current task (e.g. 53). **/
private int mProgress;
/** Current contact name (e.g. John Doe). **/
private String mTextContact;
/** Current task (e.g. Uploading server contacts). **/
private Task mTask;
/** Current task status (e.g. Sent 25 of 500 contacts). **/
private TaskStatus mTaskStatus;
/** Current task done (e.g. Sent X of 500 contacts). **/
private int mTaskStatusDone;
/** Current task total (e.g. Sent 25 of X contacts). **/
private int mTaskStatusTotal;
/**
* Construct with only the ServiceStatus of the Contacts sync engine.
*
* @param serviceStatus ServiceStatus of sync outcome.
*/
protected SyncStatus(final ServiceStatus serviceStatus) {
mServiceStatus = serviceStatus;
}
/**
* Construct with the current state of the Contacts sync engine.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
* @param taskStatus Current task status (e.g. Sent 25 of 500 contacts).
* @param taskStatusDone Current task done (e.g. Sent X of 500 contacts).
* @param taskStatusTotal Current task total (e.g. Sent 25 of X contacts).
*/
public SyncStatus(final int progress,
final String textContact, final Task task,
final TaskStatus taskStatus, final int taskStatusDone,
final int taskStatusTotal) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = taskStatus;
mTaskStatusDone = taskStatusDone;
mTaskStatusTotal = taskStatusTotal;
}
/**
* Construct with the current state of the Contacts sync engine, with the
* task status set to TaskStatus.NONE.
*
* @param progress Percentage of sync progress in current task (e.g. 53).
* @param textContact Current contact name (e.g. John Doe).
* @param task Current task (e.g. Uploading server contacts).
*/
public SyncStatus(final int progress, final String textContact,
final Task task) {
mProgress = progress;
mTextContact = textContact;
mTask = task;
mTaskStatus = TaskStatus.NONE;
mTaskStatusDone = 0;
mTaskStatusTotal = 0;
}
/**
* Gets the ServiceStatus of sync outcome.
*
* @return Sync outcome as a ServiceStatus object.
*/
public final ServiceStatus getServiceStatus() {
return mServiceStatus;
}
/**
* Get the current sync progress percentage for the current task.
*
* @return Current sync progress percentage.
*/
public final int getProgress() {
return mProgress;
}
/**
* Get the current contact name (e.g. John Doe).
*
* @return Current contact name.
*/
public final String getTextContact() {
return mTextContact;
}
/**
* Get the current task (e.g. Uploading server contacts)
*
* @return Current task.
*/
public final Task getTask() {
return mTask;
}
/**
* Get the current task status (e.g. Sent 25 of 500 contacts).
*
* @return Current task status.
*/
public final TaskStatus getTaskStatus() {
return mTaskStatus;
}
/**
* Get the current task done (e.g. Sent X of 500 contacts).
*
* @return Current task done.
*/
public final int getTaskStatusDone() {
return mTaskStatusDone;
}
/**
* Get the current task total (e.g. Sent 25 of X contacts).
*
* @return Current task total.
*/
public final int getTaskStatusTotal() {
return mTaskStatusTotal;
}
}
\ No newline at end of file
|
360/360-Engine-for-Android
|
b2557bf4a94b9133883c5cfcdf89f5023f77357d
|
- suited tests/build.xml to comply with new build server
|
diff --git a/tests/build.xml b/tests/build.xml
index ec720ca..fb8c3ce 100755
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,669 +1,669 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
<property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
<!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
already on your system, please do so. After setting it, create a new properties file in
build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
to it. -->
<property file="../build_property_files/${env.USERNAME_360}.properties" />
<echo>Building for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
XMLTask is found in ${xml.task.dir}...</echo>
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
- <src path="../../${ui.project.name}/src" />
+ <src path="../../../Android_subtask_upstream_checkout_ui/workspace/src" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests ...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
<property name="sdk-location" location="${sdk.dir}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
</project>
\ No newline at end of file
|
360/360-Engine-for-Android
|
995e5ef2cbd05e2c5c10e6797bf4a7afd2f522fd
|
altered build path
|
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties
index ca1c663..20d27de 100644
--- a/build_property_files/buildserver.properties
+++ b/build_property_files/buildserver.properties
@@ -1,11 +1,11 @@
# The directory that points to the Android SDK file on your machine
-sdk.dir=/Applications/android
+sdk.dir=/opt/local/android
# The directory that points to the XMLTask (ant task) on your machine
-xml.task.dir=/Applications/android/xmltask.jar
+xml.task.dir=/opt/local/android/xmltask.jar
# The default emulator AVD to use for unit testing
default.avd=2_1_device_HVGA
# Name of the directory of the UI Project TODO move to generic properties file
ui.project.name=360-UI-for-Android
\ No newline at end of file
|
360/360-Engine-for-Android
|
36d3e21844b424177802a2a5950bd4437c8dd372
|
- altered the sdk path of the buildserver a bit
|
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties
index 7a4a29c..ca1c663 100644
--- a/build_property_files/buildserver.properties
+++ b/build_property_files/buildserver.properties
@@ -1,11 +1,11 @@
# The directory that points to the Android SDK file on your machine
-sdk.dir=/Applications/android-sdk-mac_86
+sdk.dir=/Applications/android
# The directory that points to the XMLTask (ant task) on your machine
xml.task.dir=/Applications/android/xmltask.jar
# The default emulator AVD to use for unit testing
default.avd=2_1_device_HVGA
# Name of the directory of the UI Project TODO move to generic properties file
ui.project.name=360-UI-for-Android
\ No newline at end of file
|
360/360-Engine-for-Android
|
7f8c77e9086bd22ba48828acd2a9dd500da061fc
|
- altered buildserver.properties
|
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties
index e174cf6..7a4a29c 100644
--- a/build_property_files/buildserver.properties
+++ b/build_property_files/buildserver.properties
@@ -1,11 +1,11 @@
# The directory that points to the Android SDK file on your machine
sdk.dir=/Applications/android-sdk-mac_86
# The directory that points to the XMLTask (ant task) on your machine
-xml.task.dir=/Applications/android-sdk-mac_86/xmltask.jar
+xml.task.dir=/Applications/android/xmltask.jar
# The default emulator AVD to use for unit testing
default.avd=2_1_device_HVGA
# Name of the directory of the UI Project TODO move to generic properties file
ui.project.name=360-UI-for-Android
\ No newline at end of file
|
360/360-Engine-for-Android
|
5380a3adeb4f2bb69f8a650d5c0f22ee286d6f52
|
Added buildserver properties file. The build server can now compile the project (hopefully).
|
diff --git a/build_property_files/buildserver.properties b/build_property_files/buildserver.properties
new file mode 100644
index 0000000..e174cf6
--- /dev/null
+++ b/build_property_files/buildserver.properties
@@ -0,0 +1,11 @@
+# The directory that points to the Android SDK file on your machine
+sdk.dir=/Applications/android-sdk-mac_86
+
+# The directory that points to the XMLTask (ant task) on your machine
+xml.task.dir=/Applications/android-sdk-mac_86/xmltask.jar
+
+# The default emulator AVD to use for unit testing
+default.avd=2_1_device_HVGA
+
+# Name of the directory of the UI Project TODO move to generic properties file
+ui.project.name=360-UI-for-Android
\ No newline at end of file
|
360/360-Engine-for-Android
|
b4a45fe58ca5d6161e7fd882eb61bf210e0652b8
|
added build files to git
|
diff --git a/build_auto.xml b/build_auto.xml
new file mode 100644
index 0000000..e125388
--- /dev/null
+++ b/build_auto.xml
@@ -0,0 +1,651 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- CDDL HEADER START
+ The contents of this file are subject to the terms of the Common Development
+ and Distribution License (the "License").
+ You may not use this file except in compliance with the License.
+
+ You can obtain a copy of the license at
+ src/com/vodafone360/people/VODAFONE.LICENSE.txt or
+ http://github.com/360/360-Engine-for-Android
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ When distributing Covered Code, include this CDDL HEADER in each file and
+ include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
+ If applicable, add the following below this CDDL HEADER, with the fields
+ enclosed by brackets "[]" replaced with your own identifying information:
+ Portions Copyright [yyyy] [name of copyright owner]
+
+ CDDL HEADER END
+
+ Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
+ Use is subject to license terms.
+-->
+
+<project name="VodafonePeople" default="all">
+ <property environment="env"/>
+
+ <!-- The local.properties file is created and updated by the 'android' tool.
+ It contain the path to the SDK. It should *NOT* be checked in in Version
+ Control Systems. -->
+ <property file="local.properties"/>
+
+ <!-- The build.properties file can be created by you and is never touched
+ by the 'android' tool. This is the place to change some of the default property values
+ used by the Ant rules.
+ Here are some properties you may want to change/update:
+
+ application-package
+ the name of your application package as defined in the manifest. Used by the
+ 'uninstall' rule.
+ source-folder
+ the name of the source folder. Default is 'src'.
+ out-folder
+ the name of the output folder. Default is 'bin'.
+
+ Properties related to the SDK location or the project target should be updated
+ using the 'android' tool with the 'update' action.
+
+ This file is an integral part of the build system for your application and
+ should be checked in in Version Control Systems.
+ -->
+ <property file="build.properties"/>
+
+ <!-- The default.properties file is created and updated by the 'android' tool, as well
+ as ADT.
+ This file is an integral part of the build system for your application and
+ should be checked in in Version Control Systems. -->
+ <property file="default.properties"/>
+
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="build_property_files/${env.USERNAME_360}.properties" />
+
+ <echo>Building for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
+ XMLTask is found in ${xml.task.dir}...</echo>
+
+ <!-- Custom Android task to deal with the project target, and import the proper rules.
+ This requires ant 1.6.0 or above. -->
+ <path id="android.antlibs">
+ <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
+ </path>
+
+ <taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"
+ classpath="${xml.task.dir}"/>
+
+ <taskdef name="setup"
+ classname="com.android.ant.SetupTask"
+ classpathref="android.antlibs"/>
+
+ <!-- Execute the Android Setup task that will setup some properties specific to the target,
+ and import the rules files.
+ To customize the rules, copy/paste them below the task, and disable import by setting
+ the import attribute to false:
+ <setup import="false" />
+
+ This will ensure that the properties are setup correctly but that your customized
+ targets are used.
+ -->
+ <setup import="false" />
+
+ <!-- Custom tasks -->
+ <taskdef name="aaptexec"
+ classname="com.android.ant.AaptExecLoopTask"
+ classpathref="android.antlibs"/>
+
+ <taskdef name="apkbuilder"
+ classname="com.android.ant.ApkBuilderTask"
+ classpathref="android.antlibs"/>
+
+ <!-- Properties -->
+ <property environment="os"/>
+ <property name="android-tools" value="${sdk.dir}/tools" />
+
+ <!-- Set Version code -->
+ <xmltask source="AndroidManifest.xml">
+ <copy path="/manifest/@android:versionCode" property="versionCode"/>
+ </xmltask>
+
+ <!-- Input directories -->
+ <property name="source-folder" value="src" />
+ <property name="gen-folder" value="gen" />
+ <property name="resource-folder" value="res" />
+ <property name="resource-config-folder" value="${resource-folder}/raw" />
+ <property name="asset-folder" value="assets" />
+ <property name="source-location" value="${basedir}/${source-folder}" />
+
+ <property name="avd-name" value="testavd" />
+ <property name="avd-port" value="5554" />
+
+ <!-- folder for the 3rd party java libraries -->
+ <property name="external-libs-folder" value="extlibs" />
+
+ <!-- folder for the native libraries -->
+ <property name="native-libs-folder" value="libs" />
+
+ <!-- Output directories -->
+ <property name="gen-folder" value="gen" />
+ <property name="out-folder" value="output" />
+ <property name="out-classes" value="${out-folder}/classes" />
+ <property name="out-classes-location" value="${basedir}/${out-classes}"/>
+
+ <property name="apk-dev-file-name" value="360people_r${revision}" />
+ <property name="apk-beta-file-name" value="360people_v${versionCode}" />
+ <property name="apk-market-file-name" value="360people_v${versionCode}" />
+
+ <property name="apk-folder" value="${out-folder}/apk" />
+ <property name="apk-dev-folder" value="${apk-folder}/dev/r${revision}" />
+ <property name="apk-beta-folder" value="${apk-folder}/beta/v${versionCode}" />
+ <property name="apk-market-folder" value="${apk-folder}/market/v${versionCode}" />
+
+ <!-- out folders for a parent project if this project is an instrumentation project -->
+ <property name="main-out-folder" value="../${out-folder}" />
+ <property name="main-out-classes" value="${main-out-folder}/classes"/>
+ <property name="javadocs-folder" value="${out-folder}/javadocs" />
+
+ <!-- Intermediate files -->
+ <property name="dex-file" value="classes.dex" />
+ <property name="intermediate-dex" value="${out-folder}/${dex-file}" />
+ <!-- dx does not properly support incorrect / or \ based on the platform
+ and Ant cannot convert them because the parameter is not a valid path.
+ Because of this we have to compute different paths depending on the platform. -->
+ <condition property="intermediate-dex-location"
+ value="${basedir}\${intermediate-dex}"
+ else="${basedir}/${intermediate-dex}" >
+ <os family="windows"/>
+ </condition>
+ <property name="config.file" value="${resource-config-folder}/config.properties" />
+
+ <!-- The final package file to generate -->
+ <property name="application-package" value="com.vodafone360.people"/>
+
+ <!-- Signing information -->
+ <property name="sign-password" value="vodsigning64"/>
+
+ <!-- Tools -->
+ <condition property="exe" value=".exe" else=""><os family="windows"/></condition>
+ <property name="adb" value="${android-tools}/adb${exe}"/>
+
+ <!-- cleanup before we start -->
+ <target name="clean">
+ <delete dir="output"/>
+ </target>
+
+ <!-- Create the output directories if they don't exist yet. -->
+ <target name="dirs">
+ <echo>Creating output directories if needed...</echo>
+ <mkdir dir="${resource-folder}" />
+ <mkdir dir="${resource-config-folder}" />
+ <mkdir dir="${external-libs-folder}" />
+ <mkdir dir="${gen-folder}" />
+ <mkdir dir="${out-folder}" />
+ <mkdir dir="${out-classes}" />
+ <mkdir dir="${javadocs-folder}" />
+ <mkdir dir="${apk-folder}"/>
+ <mkdir dir="${apk-dev-folder}"/>
+ </target>
+
+ <!-- Generate the R.java file for this project's resources. -->
+ <target name="resource-src" depends="dirs">
+ <echo>Generating R.java / Manifest.java from the resources...</echo>
+ <exec executable="${aapt}" failonerror="true">
+ <arg value="package" />
+ <arg value="-m" />
+ <arg value="-J" />
+ <arg path="${gen-folder}" />
+ <arg value="-M" />
+ <arg path="AndroidManifest.xml" />
+ <arg value="-S" />
+ <arg path="${resource-folder}" />
+ <arg value="-I" />
+ <arg path="${android.jar}" />
+ </exec>
+ </target>
+
+ <!-- Generate java classes from .aidl files. -->
+ <target name="aidl" depends="dirs">
+ <echo>Compiling aidl files into Java classes...</echo>
+ <apply executable="${aidl}" failonerror="true">
+ <arg value="-p${android-aidl}" />
+ <arg value="-I${source-folder}" />
+ <arg value="-o${gen-folder}" />
+ <fileset dir="${source-folder}">
+ <include name="**/*.aidl"/>
+ </fileset>
+ </apply>
+ </target>
+
+ <!-- Compile this project's .java files into .class files. -->
+ <target name="compile" depends="resource-src, aidl">
+ <javac encoding="utf8" target="1.5" debug="$(debug-build)" extdirs=""
+ destdir="${out-classes}"
+ bootclasspathref="android.target.classpath">
+ <src path="${source-folder}" />
+ <src path="../${ui.project.name}/${source-folder}" />
+ <src path="${gen-folder}" />
+ <classpath>
+ <pathelement path="${main-out-classes}"/>
+ </classpath>
+ </javac>
+ </target>
+
+ <!-- Convert this project's .class files into .dex files. -->
+ <target name="dex" depends="compile">
+ <echo>Converting compiled files and external libraries into ${out-folder}/${dex-file}...</echo>
+ <apply executable="${dx}" failonerror="true" parallel="true">
+ <arg value="--dex" />
+ <arg value="--no-locals" />
+ <arg value="--output=${intermediate-dex-location}" />
+ <arg path="${out-classes-location}" />
+ <!-- <fileset dir="${external-libs-folder}" includes="FlurryAgent.jar"/> -->
+ <fileset dir="${external-libs-folder}"/>
+ </apply>
+ </target>
+
+ <!-- Put the project's resources into the output package file
+ This actually can create multiple resource package in case
+ Some custom apk with specific configuration have been
+ declared in default.properties.
+ -->
+ <target name="package-resources">
+ <echo>Packaging resources</echo>
+ <aaptexec executable="${aapt}"
+ command="package"
+ manifest="AndroidManifest.xml"
+ resources="${resource-folder}"
+ assets="${asset-folder}"
+ androidjar="${android.jar}"
+ outfolder="${resources.output.folder}"
+ basename="${fileName}_${environment}" />
+ </target>
+
+ <!-- Package the application and sign it with a debug key.
+ This is the default target when building. It is used for debug. -->
+ <target name="debug">
+ <apkbuilder
+ outfolder="${release.output.folder}"
+ basename="${fileName}_${environment}"
+ signed="true"
+ verbose="false">
+ <file path="${intermediate-dex}" />
+ <sourcefolder path="${source-folder}" />
+ <nativefolder path="${native-libs-folder}" />
+ </apkbuilder>
+ </target>
+
+ <!-- Package the application without signing it.
+ This allows for the application to be signed later with an official publishing key. -->
+ <target name="release">
+ <echo> source-folder ${source-folder}</echo>
+
+ <apkbuilder
+ outfolder="${release.output.folder}"
+ basename="${fileName}_${environment}"
+ signed="false"
+ verbose="false">
+ <file path="${intermediate-dex}" />
+ <sourcefolder path="src" />
+ <nativefolder path="${native-libs-folder}" />
+ </apkbuilder>
+
+
+ <!-- <apkbuilder
+ outfolder="${release.output.folder}"
+ basename="${fileName}_${environment}"
+ signed="false"
+ verbose="false">
+ <file path="${intermediate-dex}" />
+ <sourcefolder path="${source-folder}" />
+ <nativefolder path="${native-libs-folder}" />
+ </apkbuilder> -->
+ </target>
+
+ <target name="sign-release-apk">
+ <!-- jarsigner -keystore NPKEYSTORE -storepass vodsigning64 -keypass vodsigning64 bin\.NowPlus-unsigned.apk mykey -->
+ <echo>Signing release apk with our (temp) key. </echo>
+ <signjar jar="${out-unsigned-package}"
+ keystore="NPKEYSTORE"
+ alias="NPKEYALIAS"
+ storepass="vodsigning64"
+ signedjar="${out-package}"
+ />
+ </target>
+
+ <!-- Install the package on the default emulator -->
+ <target name="install-debug">
+ <echo>Installing ${out-debug-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg path="${out-debug-package}" />
+ </exec>
+ </target>
+
+ <!-- Install the package on the default emulator -->
+ <target name="install">
+ <!--target name="install" depends="release,doc,sign-release-apk,uninstall"-->
+ <echo>Installing ${out-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg path="${out-package}" />
+ </exec>
+ </target>
+
+ <!-- Reinstall the package on the default emulator -->
+ <target name="reinstall-debug">
+ <!--target name="reinstall-debug" depends="debug,doc"-->
+ <echo>Installing ${out-debug-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg value="-r" />
+ <arg path="${out-debug-package}" />
+ </exec>
+ </target>
+
+ <!-- Reinstall the package on the default emulator -->
+ <!--target name="reinstall" depends="release,doc,sign-release-apk"-->
+ <target name="reinstall">
+ <echo>Installing ${out-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg value="-r" />
+ <arg path="${out-package}" />
+ </exec>
+ </target>
+
+ <!-- Uninstall the package from the default emulator -->
+ <target name="uninstall">
+ <echo>Uninstalling ${application-package} from the default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="uninstall" />
+ <arg value="com.vodafone360.people" />
+ </exec>
+ </target>
+
+ <!-- Build debug test package -->
+ <target name="test-debug">
+ <echo>Build test debug...</echo>
+ <ant target="debug" dir="tests"/>
+ </target>
+
+ <!-- Build release test package -->
+ <target name="test-release">
+ <echo>Build test release...</echo>
+ <ant target="release" dir="tests"/>
+ </target>
+
+ <!-- Pull code from Subversion. -->
+ <target name="checkout-build" description="Pulls code from Subversion into the build directory">
+ <exec executable="svn">
+ <arg line="co --force ${svn.projecturl} -r ${svn.revision} ."/>
+ </exec>
+ </target>
+
+ <!--
+ Before running the tests, please setup the following test emulators.
+
+ [Required]
+ android create avd -n TEST_AVD_2.1 -t android-7 -c 256M
+
+ [Optional]
+ android create avd -n TEST_AVD_1.5 -t android-3 -c 256M
+ android create avd -n TEST_AVD_1.6 -t android-4 -c 256M
+ android create avd -n TEST_AVD_2.0 -t android-5 -c 256M
+ android create avd -n TEST_AVD_2.0.1 -t android-6 -c 256M
+
+ [Run the emulator before starting the tests]
+ emulator -avd TEST_AVD_2.1 -wipe-data
+ -->
+
+ <target name="start.emulator">
+ <echo>Start ${test-avd} emulator</echo>
+ <parallel>
+ <daemons>
+ <exec executable="${emulator}">
+ <arg value="-avd"/>
+ <arg value="${test-avd}"/>
+ <arg value="-wipe-data"/>
+ <!-- TODO Parms:
+ <arg value="-no-window"/>
+ -->
+ </exec>
+ </daemons>
+ </parallel>
+ <exec executable="adb wait-for-device"/>
+ </target>
+
+ <target name="test_emma">
+ <!-- Choose emulator (EMMA requires 2.x or higher) -->
+ <property name="test-avd" value="TEST_AVD_2.1" />
+
+ <!-- <antcall target="start.emulator"/> -->
+
+ <echo>Run all tests on the ${test-avd} emulator</echo>
+ <ant antfile="tests/build.xml"
+ target="emma-coverage-interface"
+ inheritAll="false"/>
+
+ <echo>Copy coverage results to output folder.</echo>
+ <mkdir dir="output\apk\dev\r${revision}\coverage"/>
+ <copy todir="output\apk\dev\r${revision}\coverage">
+ <fileset dir="coverage\"/>
+ </copy>
+
+ <!-- TODO Kill Emulator -->
+ </target>
+
+ <target name="test_junit">
+ <!-- Choose emulator (EMMA requires 2.x or higher) -->
+ <property name="test-avd" value="TEST_AVD_2.1" />
+
+ <echo>Run all Junit tests on the ${test-avd} emulator</echo>
+ <ant antfile="tests/build.xml"
+ target="run-tests-interface"
+ inheritAll="false"/>
+ </target>
+
+
+ <!-- Run all the tests, logging the output. -->
+ <target name="run-tests" description="Run tests">
+
+ <echo>Clear the log - ADB path info: ${adb}</echo>
+
+ <!-- Clear the log. -->
+ <exec executable="${adb}" failonerror="true">
+ <arg line="logcat -c"/>
+ </exec>
+
+ <echo>Run the tests, logging output to file</echo>
+ <!-- Run the tests, logging output to file. -->
+ <exec executable="cmd" failonerror="true">
+ <arg value="/C"/>
+ <arg value="adb shell am instrument -w com.vodafone360.people.tests/android.test.InstrumentationTestRunner > output/results.txt"/>
+ </exec>
+
+ <echo>Save TestRunner output to file</echo>
+ <!-- Save TestRunner output to file. -->
+ <exec executable="cmd" spawn="true">
+ <arg value="/C"/>
+ <arg value="adb logcat TestRunner:I *:S > tests/output/test_runner_output.txt"/>
+ </exec>
+
+ <echo>Save all output to file</echo>
+ <!-- Save all output to file. -->
+ <exec executable="cmd" spawn="true">
+ <arg value="/C"/>
+ <arg value="adb logcat > tests/output/logcat_output.txt"/>
+ </exec>
+ <echo>Tests have run, see log files for results......</echo>
+ </target>
+
+ <!-- Pause to make sure that the emulator has really started. -->
+ <target name="pause">
+ <sleep seconds="30"/>
+ </target>
+
+ <!-- Start the emulator using ANT, as part of a workaround to Hudson defect 3105. -->
+ <target name="startEmu">
+ <exec executable="emulator" spawn="true" dir=".">
+ <arg value="/c"/>
+ <arg value="-avd testavd"/>
+ </exec>
+ <sleep seconds="3"/>
+ </target>
+
+ <target name="init_app">
+ <property name="environment.file.name" value="build/environment.${environment}.properties"/>
+ <property name="lifecycle.file.name" value="build/lifecycle.${lifecycle}.properties"/>
+ <property name="resources.output.folder" value="${outputFolder}"/>
+ <property name="release.output.folder" value="${outputFolder}"/>
+ <property name="out-unsigned-package" value="${outputFolder}/${fileName}_${environment}-unsigned.apk"/>
+ <property name="out-package" value="${outputFolder}/${fileName}_${environment}.apk"/>
+ <property name="out-debug-package" value="${outputFolder}/${fileName}_${environment}-debug.apk"/>
+
+ <!-- Make and label build folder -->
+ <mkdir dir="${outputFolder}"/>
+ <copy file="build/index_${lifecycle}.html" tofile="${outputFolder}/index.html">
+ <filterchain>
+ <replacetokens>
+ <token key="BUILD_NAME" value="${fileName}"/>
+ <token key="DEV_BUILD" value="${fileName}_dev.apk"/>
+ <token key="QA_BUILD" value="${fileName}_qat.apk"/>
+ <token key="ELLER_BUILD" value="${fileName}_eller.apk"/>
+ <token key="PRE_BUILD" value="${fileName}_preprod.apk"/>
+ <token key="PRO_BUILD" value="${fileName}_prod.apk"/>
+ </replacetokens>
+ </filterchain>
+ </copy>
+ <copy file="release_notes.txt" tofile="${outputFolder}/release_notes.txt"/>
+ </target>
+
+ <target name="make_config_file" >
+ <echo file="${config.file}" append="false">#configuration properties: environment${line.separator}</echo>
+ <!-- update properties with Environment Mapping-->
+ <concat destfile="${config.file}" append="true">
+ <fileset file="${environment.file.name}"/>
+ </concat>
+ <echo file="${config.file}" append="true">${line.separator}${line.separator}#configuration properties: lifecycle${line.separator}</echo>
+ <!-- update properties with Lifecycle Mapping-->
+ <concat destfile="${config.file}" append="true">
+ <fileset file="${lifecycle.file.name}"/>
+ </concat>
+ </target>
+
+ <!-- cleanup before we start -->
+ <target name="cleanConfigFolder">
+ <delete file="${config.file}"/>
+ </target>
+
+ <target name="manifest-release">
+ <echo>Set AndroidManifest.xml to Release mode</echo>
+ <delete file="AndroidManifest.xml"/>
+ <copy file="AndroidManifest-edit.xml" tofile="AndroidManifest.xml"/>
+ <replaceregexp match="android:debuggable="true"" replace="android:debuggable="false"" flags="g" byline="true">
+ <fileset file="AndroidManifest.xml"/>
+ </replaceregexp>
+ <replaceregexp match="%%%%%%%%[^%]*%%%%%%%%" replace="REMOVED" flags="g" byline="false">
+ <fileset file="AndroidManifest.xml"/>
+ </replaceregexp>
+ </target>
+
+ <target name="manifest-logcat">
+ <echo>Set AndroidManifest.xml to LogCat mode</echo>
+ <delete file="AndroidManifest.xml"/>
+ <copy file="AndroidManifest-edit.xml" tofile="AndroidManifest.xml"/>
+ </target>
+
+ <target name="-dex-filter">
+ <echo>Remove unused classes from production build</echo>
+ <delete dir="${out-classes}\com\vodafone\people\ui\debug"/>
+ </target>
+
+ <target name="allProcessStart" depends="clean,dirs,resource-src,aidl,compile" />
+ <target name="allProcess" depends="init_app,make_config_file,package-resources,debug,release,sign-release-apk" />
+ <target name="testOnDevice" depends="allProcess,uninstall,install-debug,test-debug,run-tests" />
+
+ <!-- <target name="allProcessFinalDebug" depends="init_app,uninstall,install-debug,test-debug" /> -->
+ <!-- <target name="allProcessFinalRelease" depends="init_app,uninstall,install,test-release,run-tests" /> -->
+
+ <target name="all" depends="test_junit,all-dev-lifecycle,publish" />
+
+ <target name="all-nightly" depends="all-dev-lifecycle,checkstyle,test_emma,publish" />
+ <target name="all-dev-lifecycle" depends="allProcessStart,dex,DevPro,DevPre,DevQAT,DevEller,DevDev" />
+
+ <!-- START Dev Lifecycle -->
+ <target name="DevPro">
+ <echo>DEV Lifecycle + Pro Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-dev-folder}"/>
+ <param name="fileName" value="${apk-dev-file-name}"/>
+ <param name="environment" value="prod"/>
+ <param name="lifecycle" value="dev"/>
+ </antcall>
+ </target>
+ <target name="DevPre">
+ <echo>Dev Lifecycle + Pre Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-dev-folder}"/>
+ <param name="fileName" value="${apk-dev-file-name}"/>
+ <param name="environment" value="preprod"/>
+ <param name="lifecycle" value="dev"/>
+ </antcall>
+ </target>
+ <target name="DevQAT">
+ <echo>Dev Lifecycle + QAT Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-dev-folder}"/>
+ <param name="fileName" value="${apk-dev-file-name}"/>
+ <param name="environment" value="qat"/>
+ <param name="lifecycle" value="dev"/>
+ </antcall>
+ </target>
+ <target name="DevEller">
+ <echo>Dev Lifecycle + Eller Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-dev-folder}"/>
+ <param name="fileName" value="${apk-dev-file-name}"/>
+ <param name="environment" value="eller"/>
+ <param name="lifecycle" value="dev"/>
+ </antcall>
+ </target>
+ <target name="DevDev">
+ <echo>Dev Lifecycle + Dev Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-dev-folder}"/>
+ <param name="fileName" value="${apk-dev-file-name}"/>
+ <param name="environment" value="dev"/>
+ <param name="lifecycle" value="dev"/>
+ </antcall>
+ </target>
+ <!-- END Dev Lifecycle -->
+
+ <!-- Check style -->
+ <import file="build_checkstyle.xml" />
+ <target name="checkstyle">
+ <echo>Checkstyle</echo>
+ <antcall target="allChecks">
+ <param name="checkstyle_dir" value="${apk-dev-folder}/checkstyle"/>
+ </antcall>
+ </target>
+
+ <target name="publish">
+ <copy file="build/redirect.html" tofile="output\apk\dev\redirect.html">
+ <filterchain>
+ <replacetokens>
+ <token key="PATH" value="r${revision}/index.html"/>
+ </replacetokens>
+ </filterchain>
+ </copy>
+
+ <echo>FTP into sftp.zyb.com with user[${ftpuser}] pass[${ftppassword}].</echo>
+ <scp sftp="true" trust="true"
+ todir="${ftpuser}:${ftppassword}@sftp.zyb.com:/nowplus/android/download/people_client/dev/">
+ <fileset dir="output\apk\dev\"/>
+ </scp>
+ </target>
+</project>
\ No newline at end of file
diff --git a/build_checkstyle.xml b/build_checkstyle.xml
new file mode 100644
index 0000000..a5fd76a
--- /dev/null
+++ b/build_checkstyle.xml
@@ -0,0 +1,417 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- CDDL HEADER START
+ The contents of this file are subject to the terms of the Common Development
+ and Distribution License (the "License").
+ You may not use this file except in compliance with the License.
+
+ You can obtain a copy of the license at
+ src/com/vodafone360/people/VODAFONE.LICENSE.txt or
+ http://github.com/360/360-Engine-for-Android
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ When distributing Covered Code, include this CDDL HEADER in each file and
+ include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
+ If applicable, add the following below this CDDL HEADER, with the fields
+ enclosed by brackets "[]" replaced with your own identifying information:
+ Portions Copyright [yyyy] [name of copyright owner]
+
+ CDDL HEADER END
+
+ Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
+ Use is subject to license terms.
+-->
+
+<project name="VodafonePeopleCheckStyle" default="allChecks">
+ <!-- The local.properties file is created and updated by the 'android' tool.
+ It contain the path to the SDK. It should *NOT* be checked in in Version
+ Control Systems. -->
+ <property file="local.properties"/>
+ <property file="build.properties"/>
+
+ <!-- Set a default checkstyle directory, which is overridden by the build_auto script -->
+ <property name="checkstyle_dir" value="output/checkstyle" />
+
+ <!-- The default.properties file is created and updated by the 'android' tool, as well
+ as ADT.
+ This file is an integral part of the build system for your application and
+ should be checked in in Version Control Systems. -->
+ <property file="default.properties"/>
+
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="${env.USERNAME_360}.properties" />
+
+ <!-- Custom Android task to deal with the project target, and import the proper rules.
+ This requires ant 1.6.0 or above. -->
+ <path id="android.antlibs">
+ <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
+ </path>
+
+
+ <taskdef name="setup"
+ classname="com.android.ant.SetupTask"
+ classpathref="android.antlibs"/>
+
+ <!-- Execute the Android Setup task that will setup some properties specific to the target,
+ and import the rules files.
+ To customize the rules, copy/paste them below the task, and disable import by setting
+ the import attribute to false:
+ <setup import="false" />
+
+ This will ensure that the properties are setup correctly but that your customized
+ targets are used.
+ -->
+ <setup import="false" />
+
+ <!-- Custom tasks -->
+ <taskdef name="aaptexec"
+ classname="com.android.ant.AaptExecLoopTask"
+ classpathref="android.antlibs"/>
+
+ <taskdef resource="checkstyletask.properties"
+ classpath="build/checkstyle/checkstyle-all-5.0.jar"/>
+
+ <!-- Input directories-->
+ <property name="sources-folder" value="src"/>
+ <property name="checkstyle-stylesheet-noframes-sorted" location="build/checkstyle/checkstyle-noframes-sorted.xsl"/>
+
+ <target name="checkEngine" depends="checkStyleEngineUpgrade,checkStyleEngines,checkStyleEngineActivity,checkStyleEngineContacts,checkStyleEngineIdentities,checkStyleEngineLogin,checkStyleEnginePresence" />
+ <target name="checkService" depends="checkStyleServiceInterfaces,checkStyleService,checkStyleServiceAgent,checkStyleServiceIO,checkStyleServiceUtils,checkStyleServiceTransport,checkStyleServiceTransportHttpAuth,checkStyleServiceTransportTcp,checkStyleServiceReceivers" />
+ <target name="checkDatabase" depends="checkStyleDatabaseHelper,checkStyleDatabaseUtils"/> <!--,checkStyleDatabase-->
+ <target name="checkUI" depends="checkStyleUI,checkStyleUI3rdParty,checkStyleUIContacts,checkStyleUISettings,checkStyleUIStartup,checkStyleUITabs,checkStyleUITimeLine,checkStyleUIUtils"/>
+ <target name="checkDatatypes" depends="checkStyleDataTypes" />
+ <target name="checkUtils" depends="checkStyleUtils" />
+ <target name="checkMainApp" depends="checkStyleMainApp" />
+
+ <target name="processChecks" depends="checkOutputDirs,checkDatabase,checkService,checkMainApp,checkEngine,checkDatatypes,checkUI,checkUtils"/>
+ <target name="processChecksForAllClasses" depends="checkOutputDirs,checkStyleAllClasses"/>
+
+ <!-- ###########################Create the output directories if they don't exist yet########################### -->
+ <target name="checkOutputDirs">
+ <echo>Creating output directories if needed...</echo>
+ <mkdir dir="${outputs-folder}" />
+ </target>
+
+ <!-- ###########################GENERATE REPORTS BY PACKAGES######################## -->
+ <target name="allChecks" description="Generates a report of code convention violations including formatting issues" >
+ <antcall target="processChecks">
+ <param name="rules" value="build/checkstyle/andcooperant_checks.xml"/>
+ <param name="outputs-folder" value="${checkstyle_dir}"/>
+ </antcall>
+
+ <delete>
+ <fileset dir="${checkstyle_dir}" includes="*.xml"/>
+ </delete>
+ </target>
+
+ <!-- ###########################GENERATE AN OVERALL REPORT FOR ALL PACKAGES######################## -->
+ <target name="allChecksInOneReport" description="Generates a report of code convention violations including formatting issues in one file" >
+ <antcall target="processChecksForAllClasses">
+ <param name="rules" value="build/checkstyle/andcooperant_checks.xml"/>
+ <param name="outputs-folder" value="${checkstyle_dir}/all"/>
+ </antcall>
+ </target>
+
+ <!-- ###########################ALL CHECKS IN ONE REPORT######################## -->
+ <target name="checkStyleAllClasses" description="Generates a report of code convention violations for all code." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_all.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_all.xml" out="${outputs-folder}/checkstyle_errors_android_all.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################ENGINES CHECKS######################## -->
+ <target name="checkStyleEngineActivity" description="Generates a report of code convention violations for Activities Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/activities" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_activities.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_activities.xml" out="${outputs-folder}/checkstyle_errors_android_engine_activities.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEngineContacts" description="Generates a report of code convention violations for Contacts Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/contactsync" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_contactsync.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_contactsync.xml" out="${outputs-folder}/checkstyle_errors_android_engine_contactsync.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEngineIdentities" description="Generates a report of code convention violations for Identities Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/identities" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_identities.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_identities.xml" out="${outputs-folder}/checkstyle_errors_android_engine_identities.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEngineLogin" description="Generates a report of code convention violations for Login Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/login" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_login.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_login.xml" out="${outputs-folder}/checkstyle_errors_android_engine_login.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEnginePresence" description="Generates a report of code convention violations for Presence Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/presence" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_presence.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_presence.xml" out="${outputs-folder}/checkstyle_errors_android_engine_presence.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEngines" description="Generates a report of code convention violations for Engines." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engines.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engines.xml" out="${outputs-folder}/checkstyle_errors_android_engines.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleEngineUpgrade" description="Generates a report of code convention violations for Upgrade Engine." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/engine/upgrade" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_engine_upgrade.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_engine_upgrade.xml" out="${outputs-folder}/checkstyle_errors_android_engine_upgrade.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################SERVICE CHECKS######################## -->
+ <target name="checkStyleServiceInterfaces" description="Generates a report of code convention violations for Service." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/interfaces" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_interfaces.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_interfaces.xml" out="${outputs-folder}/checkstyle_errors_android_service_interfaces.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceAgent" description="Generates a report of code convention violations for Service Agent." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/agent" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_agent.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_agent.xml" out="${outputs-folder}/checkstyle_errors_android_service_agent.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceIO" description="Generates a report of code convention violations for Service IO." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/io" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_io.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_io.xml" out="${outputs-folder}/checkstyle_errors_android_service_io.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceReceivers" description="Generates a report of code convention violations for Service Receivers." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/receivers" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_receivers.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_receivers.xml" out="${outputs-folder}/checkstyle_errors_android_service_receivers.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceTransport" description="Generates a report of code convention violations for Service Transport." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/transport" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_transport.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_transport.xml" out="${outputs-folder}/checkstyle_errors_android_service_transport.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceTransportHttpAuth" description="Generates a report of code convention violations for Service Transport http." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/transport/http/authentication" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_transport_http_auth.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_transport_http_auth.xml" out="${outputs-folder}/checkstyle_errors_android_service_transport_http_auth.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceTransportHttp" description="Generates a report of code convention violations for Service Transport http." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/transport/http" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_transport_http.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_transport_http.xml" out="${outputs-folder}/checkstyle_errors_android_service_transport_http.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceTransportTcp" description="Generates a report of code convention violations for Service Transport http." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/transport/tcp" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_transport_tcp.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_transport_tcp.xml" out="${outputs-folder}/checkstyle_errors_android_service_transport_tcp.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleServiceUtils" description="Generates a report of code convention violations for Service Utils." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service/utils" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service_utils.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service_utils.xml" out="${outputs-folder}/checkstyle_errors_android_service_utils.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleService" description="Generates a report of code convention violations for Service." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/service" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_service.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_service.xml" out="${outputs-folder}/checkstyle_errors_android_service.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################UI CHECKS######################## -->
+ <target name="checkStyleUI" description="Generates a report of code convention violations for UI." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui.xml" out="${outputs-folder}/checkstyle_errors_android_ui.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUIContacts" description="Generates a report of code convention violations for UI Contacts." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/contacts" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_contacts.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_contacts.xml" out="${outputs-folder}/checkstyle_errors_android_ui_contacts.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUISettings" description="Generates a report of code convention violations for UI Settings." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/settings" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_settings.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_settings.xml" out="${outputs-folder}/checkstyle_errors_android_ui_settings.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUIStartup" description="Generates a report of code convention violations for UI Startup." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/startup" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_startup.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_startup.xml" out="${outputs-folder}/checkstyle_errors_android_ui_startup.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUITabs" description="Generates a report of code convention violations for UI Tabs." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/tabs" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_tabs.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_tabs.xml" out="${outputs-folder}/checkstyle_errors_android_ui_tabs.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUI3rdParty" description="Generates a report of code convention violations for UI 3rdparty." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/thirdparty" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_3rdparty.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_3rdparty.xml" out="${outputs-folder}/checkstyle_errors_android_ui_3rdparty.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUITimeLine" description="Generates a report of code convention violations for UI timeline." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/timeline" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_timeline.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_timeline.xml" out="${outputs-folder}/checkstyle_errors_android_ui_timeline.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <target name="checkStyleUIUtils" description="Generates a report of code convention violations for UI Utils." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/ui/utils" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_ui_utils.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_ui_utils.xml" out="${outputs-folder}/checkstyle_errors_android_ui_utils.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################DB CHECKS######################## -->
+ <target name="checkStyleDatabaseHelper" description="Generates a report of code convention violations for DB Helper." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/database" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_db_helper.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_db_helper.xml" out="${outputs-folder}/checkstyle_errors_android_db_helper.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+ <target name="checkStyleDatabaseUtils" description="Generates a report of code convention violations for DB and Service Interfaces." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/database/utils" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_db_utils.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_db_utils.xml" out="${outputs-folder}/checkstyle_errors_android_db_utils.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+ <target name="checkStyleDatabase" description="Generates a report of code convention violations for DB and Service Interfaces." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/database/tables" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_db_tables.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_db_tables.xml" out="${outputs-folder}/checkstyle_errors_android_db_tables.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################UTILS CHECKS######################## -->
+ <target name="checkStyleUtils" description="Generates a report of code convention violations for Utils." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/utils" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_utils.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_utils.xml" out="${outputs-folder}/checkstyle_errors_android_utils.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+ <!-- ###########################MAINAPP CHECKS######################## -->
+ <target name="checkStyleMainApp" description="Generates a report of code convention violations for MainApp." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people" includes="*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_mainapp.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_mainapp.xml" out="${outputs-folder}/checkstyle_errors_android_mainapp.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+
+ <!-- ###########################DATATYPES CHECKS######################## -->
+ <target name="checkStyleDataTypes" description="Generates a report of code convention violations for Data types." >
+ <checkstyle config="${rules}">
+ <fileset dir="${sources-folder}/com/vodafone360/people/datatypes" includes="**/*.java"/>
+ <formatter type="plain"/>
+ <formatter type="xml" toFile="${outputs-folder}/checkstyle_errors_android_datatypes.xml"/>
+ </checkstyle>
+ <style in="${outputs-folder}/checkstyle_errors_android_datatypes.xml" out="${outputs-folder}/checkstyle_errors_android_datatypes.html" style="${checkstyle-stylesheet-noframes-sorted}" />
+ </target>
+
+</project>
\ No newline at end of file
diff --git a/build_deploy.xml b/build_deploy.xml
new file mode 100644
index 0000000..2e2461a
--- /dev/null
+++ b/build_deploy.xml
@@ -0,0 +1,600 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- CDDL HEADER START
+ The contents of this file are subject to the terms of the Common Development
+ and Distribution License (the "License").
+ You may not use this file except in compliance with the License.
+
+ You can obtain a copy of the license at
+ src/com/vodafone360/people/VODAFONE.LICENSE.txt or
+ http://github.com/360/360-Engine-for-Android
+ See the License for the specific language governing permissions and
+ limitations under the License.
+
+ When distributing Covered Code, include this CDDL HEADER in each file and
+ include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
+ If applicable, add the following below this CDDL HEADER, with the fields
+ enclosed by brackets "[]" replaced with your own identifying information:
+ Portions Copyright [yyyy] [name of copyright owner]
+
+ CDDL HEADER END
+
+ Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
+ Use is subject to license terms.
+-->
+
+<project name="VodafonePeople" default="all">
+ <fail unless="${env.360_USERNAME}">
+ Environment variable USERNAME_360 has to be set to a value and there must be
+ </fail>
+
+ <!-- The local.properties file is created and updated by the 'android' tool.
+ It contain the path to the SDK. It should *NOT* be checked in in Version
+ Control Systems. -->
+ <property file="local.properties"/>
+
+ <!-- The build.properties file can be created by you and is never touched
+ by the 'android' tool. This is the place to change some of the default property values
+ used by the Ant rules.
+ Here are some properties you may want to change/update:
+
+ application-package
+ the name of your application package as defined in the manifest. Used by the
+ 'uninstall' rule.
+ source-folder
+ the name of the source folder. Default is 'src'.
+ out-folder
+ the name of the output folder. Default is 'bin'.
+
+ Properties related to the SDK location or the project target should be updated
+ using the 'android' tool with the 'update' action.
+
+ This file is an integral part of the build system for your application and
+ should be checked in in Version Control Systems.
+ -->
+ <property file="build.properties"/>
+
+ <!-- The default.properties file is created and updated by the 'android' tool, as well
+ as ADT.
+ This file is an integral part of the build system for your application and
+ should be checked in in Version Control Systems. -->
+ <property file="default.properties"/>
+
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="${env.360_USERNAME}.properties" />
+
+ <!-- Custom Android task to deal with the project target, and import the proper rules.
+ This requires ant 1.6.0 or above. -->
+ <path id="android.antlibs">
+ <pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
+ <pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
+ </path>
+
+ <taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask"
+ classpath="${xml.task.dir}"/>
+
+ <taskdef name="setup"
+ classname="com.android.ant.SetupTask"
+ classpathref="android.antlibs"/>
+
+ <!-- Execute the Android Setup task that will setup some properties specific to the target,
+ and import the rules files.
+ To customize the rules, copy/paste them below the task, and disable import by setting
+ the import attribute to false:
+ <setup import="false" />
+
+ This will ensure that the properties are setup correctly but that your customized
+ targets are used.
+ -->
+ <setup import="false" />
+
+ <!-- Custom tasks -->
+ <taskdef name="aaptexec"
+ classname="com.android.ant.AaptExecLoopTask"
+ classpathref="android.antlibs"/>
+
+ <taskdef name="apkbuilder"
+ classname="com.android.ant.ApkBuilderTask"
+ classpathref="android.antlibs"/>
+
+ <!-- Properties -->
+ <property environment="os"/>
+ <property name="android-tools" value="${sdk.dir}/tools" />
+
+ <!-- Set Version code -->
+ <xmltask source="AndroidManifest.xml">
+ <copy path="/manifest/@android:versionCode" property="versionCode"/>
+ </xmltask>
+
+ <!-- Input directories -->
+ <property name="source-folder" value="src" />
+ <property name="gen-folder" value="gen" />
+ <property name="resource-folder" value="res" />
+ <property name="resource-config-folder" value="${resource-folder}/raw" />
+ <property name="asset-folder" value="assets" />
+ <property name="source-location" value="${basedir}/${source-folder}" />
+
+ <property name="avd-name" value="testavd" />
+ <property name="avd-port" value="5554" />
+
+ <!-- folder for the 3rd party java libraries -->
+ <property name="external-libs-folder" value="extlibs" />
+
+ <!-- folder for the native libraries -->
+ <property name="native-libs-folder" value="libs" />
+
+ <!-- Output directories -->
+ <property name="gen-folder" value="gen" />
+ <property name="out-folder" value="output" />
+ <property name="out-classes" value="${out-folder}/classes" />
+ <property name="out-classes-location" value="${basedir}/${out-classes}"/>
+
+ <property name="apk-beta-file-name" value="360people_v${versionCode}" />
+ <property name="apk-market-file-name" value="360people_v${versionCode}" />
+
+ <property name="apk-folder" value="${out-folder}/apk" />
+ <property name="apk-beta-folder" value="${apk-folder}/beta/v${versionCode}" />
+ <property name="apk-market-folder" value="${apk-folder}/market/v${versionCode}" />
+
+ <!-- out folders for a parent project if this project is an instrumentation project -->
+ <property name="main-out-folder" value="../${out-folder}" />
+ <property name="main-out-classes" value="${main-out-folder}/classes"/>
+ <property name="javadocs-folder" value="${out-folder}/javadocs" />
+
+ <!-- Intermediate files -->
+ <property name="dex-file" value="classes.dex" />
+ <property name="intermediate-dex" value="${out-folder}/${dex-file}" />
+ <!-- dx does not properly support incorrect / or \ based on the platform
+ and Ant cannot convert them because the parameter is not a valid path.
+ Because of this we have to compute different paths depending on the platform. -->
+ <condition property="intermediate-dex-location"
+ value="${basedir}\${intermediate-dex}"
+ else="${basedir}/${intermediate-dex}" >
+ <os family="windows"/>
+ </condition>
+ <property name="config.file" value="${resource-config-folder}/config.properties" />
+
+ <!-- The final package file to generate -->
+ <property name="application-package" value="com.vodafone360.people"/>
+
+ <!-- Signing information -->
+ <property name="sign-password" value="vodsigning64"/>
+
+ <!-- Tools -->
+ <condition property="exe" value=".exe" else=""><os family="windows"/></condition>
+ <property name="adb" value="${android-tools}/adb${exe}"/>
+
+ <!-- cleanup before we start -->
+ <target name="clean">
+ <delete dir="output"/>
+ </target>
+
+ <!-- Create the output directories if they don't exist yet. -->
+ <target name="dirs">
+ <echo>Creating output directories if needed...</echo>
+ <mkdir dir="${resource-folder}" />
+ <mkdir dir="${resource-config-folder}" />
+ <mkdir dir="${external-libs-folder}" />
+ <mkdir dir="${gen-folder}" />
+ <mkdir dir="${out-folder}" />
+ <mkdir dir="${out-classes}" />
+ <mkdir dir="${javadocs-folder}" />
+ <mkdir dir="${apk-folder}"/>
+ <mkdir dir="${apk-beta-folder}"/>
+ <mkdir dir="${apk-market-folder}"/>
+ </target>
+
+ <!-- Generate the R.java file for this project's resources. -->
+ <target name="resource-src" depends="dirs">
+ <echo>Generating R.java / Manifest.java from the resources...</echo>
+ <exec executable="${aapt}" failonerror="true">
+ <arg value="package" />
+ <arg value="-m" />
+ <arg value="-J" />
+ <arg path="${gen-folder}" />
+ <arg value="-M" />
+ <arg path="AndroidManifest.xml" />
+ <arg value="-S" />
+ <arg path="${resource-folder}" />
+ <arg value="-I" />
+ <arg path="${android.jar}" />
+ </exec>
+ </target>
+
+ <!-- Generate java classes from .aidl files. -->
+ <target name="aidl" depends="dirs">
+ <echo>Compiling aidl files into Java classes...</echo>
+ <apply executable="${aidl}" failonerror="true">
+ <arg value="-p${android-aidl}" />
+ <arg value="-I${source-folder}" />
+ <arg value="-o${gen-folder}" />
+ <fileset dir="${source-folder}">
+ <include name="**/*.aidl"/>
+ </fileset>
+ </apply>
+ </target>
+
+ <!-- Compile this project's .java files into .class files. -->
+ <target name="compile" depends="resource-src, aidl">
+ <javac encoding="utf8" target="1.5" debug="$(debug-build)" extdirs=""
+ destdir="${out-classes}"
+ bootclasspathref="android.target.classpath">
+ <src path="${source-folder}" />
+ <src path="${gen-folder}" />
+ <classpath>
+ <!-- <fileset dir="${external-libs-folder}" includes="FlurryAgent.jar"/> -->
+ <pathelement path="${main-out-classes}"/>
+ </classpath>
+ </javac>
+ </target>
+
+ <!-- Convert this project's .class files into .dex files. -->
+ <target name="dex" depends="compile">
+ <echo>Converting compiled files and external libraries into ${out-folder}/${dex-file}...</echo>
+ <apply executable="${dx}" failonerror="true" parallel="true">
+ <arg value="--dex" />
+ <arg value="--no-locals" />
+ <arg value="--output=${intermediate-dex-location}" />
+ <arg path="${out-classes-location}" />
+ <!-- <fileset dir="${external-libs-folder}" includes="FlurryAgent.jar"/> -->
+ <fileset dir="${external-libs-folder}"/>
+ </apply>
+ </target>
+
+ <!-- Put the project's resources into the output package file
+ This actually can create multiple resource package in case
+ Some custom apk with specific configuration have been
+ declared in default.properties.
+ -->
+ <target name="package-resources">
+ <echo>Packaging resources</echo>
+ <aaptexec executable="${aapt}"
+ command="package"
+ manifest="AndroidManifest.xml"
+ resources="${resource-folder}"
+ assets="${asset-folder}"
+ androidjar="${android.jar}"
+ outfolder="${resources.output.folder}"
+ basename="${fileName}_${environment}" />
+ </target>
+
+ <!-- Package the application and sign it with a debug key.
+ This is the default target when building. It is used for debug. -->
+ <target name="debug">
+ <apkbuilder
+ outfolder="${release.output.folder}"
+ basename="${fileName}_${environment}"
+ signed="true"
+ verbose="false">
+ <file path="${intermediate-dex}" />
+ <sourcefolder path="${source-folder}" />
+ <nativefolder path="${native-libs-folder}" />
+ </apkbuilder>
+ </target>
+
+ <!-- Package the application without signing it.
+ This allows for the application to be signed later with an official publishing key. -->
+ <target name="release">
+ <echo> source-folder ${source-folder}</echo>
+ <apkbuilder
+ outfolder="${release.output.folder}"
+ basename="${fileName}_${environment}"
+ signed="false"
+ verbose="false">
+ <file path="${intermediate-dex}" />
+ <sourcefolder path="src" />
+ <nativefolder path="${native-libs-folder}" />
+ </apkbuilder>
+ </target>
+
+ <target name="sign-release-apk">
+ <!-- jarsigner -keystore NPKEYSTORE -storepass vodsigning64 -keypass vodsigning64 bin\.NowPlus-unsigned.apk mykey -->
+ <echo>Signing release apk with our (temp) key. </echo>
+ <signjar jar="${out-unsigned-package}"
+ keystore="NPKEYSTORE"
+ alias="NPKEYALIAS"
+ storepass="vodsigning64"
+ signedjar="${out-package}"
+ />
+ </target>
+
+ <!-- Install the package on the default emulator -->
+ <target name="install-debug">
+ <echo>Installing ${out-debug-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg path="${out-debug-package}" />
+ </exec>
+ </target>
+
+ <!-- Install the package on the default emulator -->
+ <target name="install">
+ <!--target name="install" depends="release,doc,sign-release-apk,uninstall"-->
+ <echo>Installing ${out-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg path="${out-package}" />
+ </exec>
+ </target>
+
+ <!-- Reinstall the package on the default emulator -->
+ <target name="reinstall-debug">
+ <!--target name="reinstall-debug" depends="debug,doc"-->
+ <echo>Installing ${out-debug-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg value="-r" />
+ <arg path="${out-debug-package}" />
+ </exec>
+ </target>
+
+ <!-- Reinstall the package on the default emulator -->
+ <!--target name="reinstall" depends="release,doc,sign-release-apk"-->
+ <target name="reinstall">
+ <echo>Installing ${out-package} onto default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="install" />
+ <arg value="-r" />
+ <arg path="${out-package}" />
+ </exec>
+ </target>
+
+ <!-- Uninstall the package from the default emulator -->
+ <target name="uninstall">
+ <echo>Uninstalling ${application-package} from the default emulator...</echo>
+ <exec executable="${adb}" failonerror="true">
+ <arg value="uninstall" />
+ <arg value="com.vodafone360.people" />
+ </exec>
+ </target>
+
+ <!-- Build debug test package -->
+ <target name="test-debug">
+ <echo>Build test debug...</echo>
+ <ant target="debug" dir="tests"/>
+ </target>
+
+ <!-- Build release test package -->
+ <target name="test-release">
+ <echo>Build test release...</echo>
+ <ant target="release" dir="tests"/>
+ </target>
+
+ <!-- Generate java doc -->
+ <target name="doc">
+ <mkdir dir="${javadocs-folder}" />
+ <copy file="build/doc/vf360.png" tofile="${javadocs-folder}/resources/logo.png"/>
+ <javadoc sourcepath="${source.absolute.dir}" destdir="${javadocs-folder}"
+ excludepackagenames="com.vodafone360.people.ui.*"
+ overview="src/overview.html" private="true"
+ windowtitle="Vodafone 360 People - API Specification"
+ additionalparam="-J-DTaglets.verbose=false" failonerror="false">
+ <!-- Use a nice documentation title -->
+ <doctitle>
+ Vodafone 360 People - API Specification
+ </doctitle>
+ <!-- Create a header that contains the taglets logo -->
+ <!-- Note the use of the {@docRoot} tag to link to the logo -->
+ <header>
+ <img
+ src="{@docRoot}/resources/logo.png"
+ width="88" height="40" border="0"
+ >
+ </header>
+ <!-- Same for the footer -->
+ <footer>
+ <img
+ src="{@docRoot}/resources/logo.png"
+ width="88" height="40"
+ >
+ </footer>
+ <!-- Include a timestamp at the bottom of the docu generated -->
+ <!-- Note the use of ${timestamp} which was created by the -->
+ <!-- <tstamp> task at the start of this target -->
+ <bottom>
+ <p align="right">
+ <font class="NavBarFont1" size="-2">
+ JavaDoc<br>
+ </font>
+ </p>
+ </bottom>
+ <!-- Include the 'rsrc' directory on the taglets path to include -->
+ <!-- the 'taglets.properties' configuration as well as all binaries -->
+ <!-- used by the configuration in the shutdown tasks -->
+ <!-- <taglet name="net.sourceforge.taglets.Taglets" path="${sdk.dir}/taglets/taglets.jar"/> -->
+ <fileset dir="src" includes="**/*.java" excludes="**/com/vodafone360/people/ui/**/*.java"/>
+ <classpath>
+ <path path="${sdk.dir}/tools/lib/sdklib.jar"/>
+ <path path="${sdk.dir}/platforms/android-7/android.jar"/>
+ </classpath>
+ <sourcepath>
+ <!-- Need to include the generated file R.java... -->
+ <path path="${gen.absolute.dir}" />
+ </sourcepath>
+ </javadoc>
+ <echo>Java documentation created......</echo>
+ <!-- zip a copy -->
+ <zip destfile="${out-folder}/360People_Javadocs.zip" basedir="${javadocs-folder}"/>
+ <echo>Zipped up the documentation...</echo>
+ </target>
+
+ <!-- Pause to make sure that the emulator has really started. -->
+ <target name="pause">
+ <sleep seconds="30"/>
+ </target>
+
+ <!-- Start the emulator using ANT, as part of a workaround to Hudson defect 3105. -->
+ <target name="startEmu">
+ <exec executable="emulator" spawn="true" dir=".">
+ <arg value="/c"/>
+ <arg value="-avd testavd"/>
+ </exec>
+ <sleep seconds="3"/>
+ </target>
+
+ <target name="init_app">
+ <property name="environment.file.name" value="build/environment.${environment}.properties"/>
+ <property name="lifecycle.file.name" value="build/lifecycle.${lifecycle}.properties"/>
+ <property name="resources.output.folder" value="${outputFolder}"/>
+ <property name="release.output.folder" value="${outputFolder}"/>
+ <property name="out-unsigned-package" value="${outputFolder}/${fileName}_${environment}-unsigned.apk"/>
+ <property name="out-package" value="${outputFolder}/${fileName}_${environment}.apk"/>
+ <property name="out-debug-package" value="${outputFolder}/${fileName}_${environment}-debug.apk"/>
+
+ <!-- Make and label build folder -->
+ <mkdir dir="${outputFolder}"/>
+ <copy file="build/index_${lifecycle}.html" tofile="${outputFolder}/index.html">
+ <filterchain>
+ <replacetokens>
+ <token key="BUILD_NAME" value="${fileName}"/>
+ <token key="DEV_BUILD" value="${fileName}_dev.apk"/>
+ <token key="QA_BUILD" value="${fileName}_qat.apk"/>
+ <token key="ELLER_BUILD" value="${fileName}_eller.apk"/>
+ <token key="PRE_BUILD" value="${fileName}_preprod.apk"/>
+ <token key="PRO_BUILD" value="${fileName}_prod.apk"/>
+ <token key="SIGNME_BUILD" value="360people_f_prod_market_vanilla_3_v${versionCode}_r0-0.apk"/>
+ </replacetokens>
+ </filterchain>
+ </copy>
+ <copy file="release_notes.txt" tofile="${outputFolder}/release_notes.txt"/>
+ </target>
+
+ <target name="make_config_file" >
+ <echo file="${config.file}" append="false">#configuration properties: environment${line.separator}</echo>
+ <!-- update properties with Environment Mapping-->
+ <concat destfile="${config.file}" append="true">
+ <fileset file="${environment.file.name}"/>
+ </concat>
+ <echo file="${config.file}" append="true">${line.separator}${line.separator}#configuration properties: lifecycle${line.separator}</echo>
+ <!-- update properties with Lifecycle Mapping-->
+ <concat destfile="${config.file}" append="true">
+ <fileset file="${lifecycle.file.name}"/>
+ </concat>
+ </target>
+
+ <!-- cleanup before we start -->
+ <target name="cleanConfigFolder">
+ <delete file="${config.file}"/>
+ </target>
+
+ <target name="manifest-release">
+ <echo>Set AndroidManifest.xml to Release mode</echo>
+ <delete file="AndroidManifest.xml"/>
+ <copy file="AndroidManifest-edit.xml" tofile="AndroidManifest.xml"/>
+ <replaceregexp match="android:debuggable="true"" replace="android:debuggable="false"" flags="g" byline="true">
+ <fileset file="AndroidManifest.xml"/>
+ </replaceregexp>
+ <replaceregexp match="%%%%%%%%[^%]*%%%%%%%%" replace="REMOVED" flags="g" byline="false">
+ <fileset file="AndroidManifest.xml"/>
+ </replaceregexp>
+ </target>
+
+ <target name="renameMarketBuild">
+ <copy file="${apk-market-folder}/${apk-market-file-name}_prod-unsigned.apk"
+ tofile="${apk-market-folder}/360people_f_prod_market_vanilla_3_v${versionCode}_r0-0.apk"/>
+ </target>
+
+ <target name="manifest-logcat">
+ <echo>Set AndroidManifest.xml to LogCat mode</echo>
+ <delete file="AndroidManifest.xml"/>
+ <copy file="AndroidManifest-edit.xml" tofile="AndroidManifest.xml"/>
+ </target>
+
+ <target name="-dex-filter">
+ <echo>Remove unused classes from production build</echo>
+ <delete dir="${out-classes}\com\vodafone\people\ui\debug"/>
+ </target>
+
+ <target name="allProcessStart" depends="clean,dirs,resource-src,aidl,compile" />
+ <target name="allProcess" depends="init_app,make_config_file,package-resources,debug,release,sign-release-apk" />
+
+ <target name="all" depends="all-market-lifecycle,all-beta-lifecycle,renameMarketBuild" />
+ <target name="all-market-lifecycle" depends="manifest-release,allProcessStart,-dex-filter,dex,MarketPro,manifest-logcat" />
+ <target name="all-beta-lifecycle" depends="allProcessStart,dex,BetaPro,BetaPre,BetaQAT,BetaEller" />
+
+ <!-- START Market Lifecycle -->
+ <target name="MarketPro">
+ <echo>Production Lifecycle + Pro Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-market-folder}"/>
+ <param name="fileName" value="${apk-market-file-name}"/>
+ <param name="environment" value="prod"/>
+ <param name="lifecycle" value="market"/>
+ </antcall>
+ </target>
+ <!-- END Market Lifecycle -->
+
+ <!-- START Beta Lifecycle -->
+ <target name="BetaPro">
+ <echo>Beta Lifecycle + Pro Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-beta-folder}"/>
+ <param name="fileName" value="${apk-beta-file-name}"/>
+ <param name="environment" value="prod"/>
+ <param name="lifecycle" value="beta"/>
+ </antcall>
+ </target>
+ <target name="BetaPre">
+ <echo>Beta Lifecycle + Pre Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-beta-folder}"/>
+ <param name="fileName" value="${apk-beta-file-name}"/>
+ <param name="environment" value="preprod"/>
+ <param name="lifecycle" value="beta"/>
+ </antcall>
+ </target>
+ <target name="BetaQAT">
+ <echo>Beta Lifecycle + QAT Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-beta-folder}"/>
+ <param name="fileName" value="${apk-beta-file-name}"/>
+ <param name="environment" value="qat"/>
+ <param name="lifecycle" value="beta"/>
+ </antcall>
+ </target>
+ <target name="BetaEller">
+ <echo>Beta Lifecycle + Eller Environment</echo>
+ <antcall target="allProcess">
+ <param name="outputFolder" value="${apk-beta-folder}"/>
+ <param name="fileName" value="${apk-beta-file-name}"/>
+ <param name="environment" value="eller"/>
+ <param name="lifecycle" value="beta"/>
+ </antcall>
+ </target>
+ <!-- END Beta Lifecycle -->
+
+ <property name="out-folder" value="output/codedrop" />
+ <property name="apk-folder" value="output/apk" />
+
+ <target name="zip-app-for-odm-release" depends="doc">
+ <echo>Zipping up ODM ready project.</echo>
+
+ <!-- APK -->
+<!-- <zip destfile="${out-folder}/360People_APK.zip" basedir="${apk-folder}"
+ includes="**/*.apk"/>
+-->
+ <!-- OVERWRITE PROPERTIES FILE -->
+ <copy file="build/config.properties" tofile="res/raw/config.properties" overwrite="true"/>
+
+ <!-- SOURCE -->
+ <zip destfile="${out-folder}/360People_Source.zip">
+ <fileset dir="." includes="res/"/>
+ <fileset dir="." includes="src/" excludes="src/com/vodafone360/people/ui/"/>
+ <fileset dir="." includes="tests/"/>
+ <fileset dir="." includes="default.properties"/>
+ <fileset dir="." includes="AndroidManifest.xml"/>
+ <fileset dir="." includes="build.xml"/>
+ </zip>
+
+ <!-- ALL -->
+<!-- <zip destfile="${out-folder}/360people_v${versionCode}.zip" basedir="${out-folder}"
+ includes="*.zip"/>
+-->
+ <echo>New output file called ${out-folder}/360people_v${versionCode}.zip created.</echo>
+ </target>
+</project>
\ No newline at end of file
diff --git a/build_property_files/rudy.properties b/build_property_files/rudy.properties
new file mode 100644
index 0000000..aeb9a79
--- /dev/null
+++ b/build_property_files/rudy.properties
@@ -0,0 +1,11 @@
+# The directory that points to the Android SDK file on your machine
+sdk.dir=/Users/rudy/Documents/development/android-sdk-mac_86
+
+# The directory that points to the XMLTask (ant task) on your machine
+xml.task.dir=/Users/rudy/Documents/development/xmltask.jar
+
+# The default emulator AVD to use for unit testing
+default.avd=2_1_device_HVGA
+
+# Name of the directory of the UI Project TODO move to generic properties file
+ui.project.name=360-UI-for-Android
\ No newline at end of file
|
360/360-Engine-for-Android
|
dfd86709908cd220033eab94ff87c90ea95627ab
|
fixed some compilation errors
|
diff --git a/default.properties b/default.properties
index b855737..c5d5335 100755
--- a/default.properties
+++ b/default.properties
@@ -1,14 +1,14 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
-target=android-5
+target=android-8
apk-configurations=
diff --git a/src/com/vodafone360/people/engine/content/ContentEngine.java b/src/com/vodafone360/people/engine/content/ContentEngine.java
index 8a9db94..ed7252b 100755
--- a/src/com/vodafone360/people/engine/content/ContentEngine.java
+++ b/src/com/vodafone360/people/engine/content/ContentEngine.java
@@ -1,250 +1,250 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.content;
import java.util.Hashtable;
import java.util.List;
-import src.com.vodafone360.people.database.DatabaseHelper;
-import src.com.vodafone360.people.datatypes.BaseDataType;
-import src.com.vodafone360.people.datatypes.ExternalResponseObject;
-import src.com.vodafone360.people.datatypes.ServerError;
-import src.com.vodafone360.people.engine.BaseEngine;
-import src.com.vodafone360.people.engine.BaseEngine.IEngineEventCallback;
-import src.com.vodafone360.people.engine.EngineManager.EngineId;
-import src.com.vodafone360.people.service.ServiceUiRequest;
-import src.com.vodafone360.people.service.io.QueueManager;
-import src.com.vodafone360.people.service.io.Request;
-import src.com.vodafone360.people.service.io.ResponseQueue.Response;
+import com.vodafone360.people.database.DatabaseHelper;
+import com.vodafone360.people.datatypes.BaseDataType;
+import com.vodafone360.people.datatypes.ExternalResponseObject;
+import com.vodafone360.people.datatypes.ServerError;
+import com.vodafone360.people.engine.BaseEngine;
+import com.vodafone360.people.engine.BaseEngine.IEngineEventCallback;
+import com.vodafone360.people.engine.EngineManager.EngineId;
+import com.vodafone360.people.service.ServiceUiRequest;
+import com.vodafone360.people.service.io.QueueManager;
+import com.vodafone360.people.service.io.Request;
+import com.vodafone360.people.service.io.ResponseQueue.Response;
/**
* Content engine for downloading and uploading all kind of content (pictures,
* videos, files)
*/
public class ContentEngine extends BaseEngine {
/**
* Constructor for the ContentEngine.
*
* @param eventCallback IEngineEventCallback for calling the constructor of
* the super class
* @param dbHelper Instance of DatabaseHelper
*/
public ContentEngine(final IEngineEventCallback eventCallback, final DatabaseHelper dbHelper) {
super(eventCallback);
this.mDbHelper = dbHelper;
mEngineId = EngineId.CONTENT_ENGINE;
}
/**
* Queue with unprocessed ContentObjects.
*/
private FiFoQueue mUnprocessedQueue = new FiFoQueue();
/**
* Queue with ContentObjects for downloads.
*/
private FiFoQueue mDownloadQueue = new FiFoQueue();
/**
* Queue with ContentObjects for uploads.
*/
private FiFoQueue mUploadQueue = new FiFoQueue();
/**
* Instance of DatabaseHelper.
*/
private DatabaseHelper mDbHelper;
/**
* Hashtable to match requests to ContentObjects.
*/
private Hashtable<Integer, ContentObject> requestContentObjectMatchTable = new Hashtable<Integer, ContentObject>();
/**
* Getter for the local instance of DatabaseHelper.
*
* @return local instance of DatabaseHelper
*/
public final DatabaseHelper getDatabaseHelper() {
return mDbHelper;
}
/**
* Processes one ContentObject.
*
* @param co ContentObject to be processed
*/
public final void processContentObject(final ContentObject co) {
mUnprocessedQueue.add(co);
}
/**
* Iterates over the ContentObject list and processes every element.
*
* @param list List with ContentObjects which are to be processed
*/
public final void processContentObjects(final List<ContentObject> list) {
for (ContentObject co : list) {
processContentObject(co);
}
}
/**
* Processes the main queue and splits it into the download and upload
* queues.
*/
private void processQueue() {
ContentObject co;
// picking unprocessed ContentObjects
while ((co = mUnprocessedQueue.poll()) != null) {
// putting them to downloadqueue ...
if (co.getDirection() == ContentObject.TransferDirection.DOWNLOAD) {
mDownloadQueue.add(co);
} else {
// ... or the uploadqueue
mUploadQueue.add(co);
}
}
}
/**
* Determines the next RunTime of this Engine It first processes the
* in-queue and then look.
*
* @return time in milliseconds from now when the engine should be run
*/
@Override
public final long getNextRunTime() {
processQueue();
// if there are CommsResponses outstanding, run now
if (isCommsResponseOutstanding()) {
return 0;
}
return (mDownloadQueue.size() + mUploadQueue.size() > 0) ? 0 : -1;
}
/**
* Empty implementation without function at the moment.
*/
@Override
public void onCreate() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
public void onDestroy() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
protected void onRequestComplete() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
protected void onTimeoutEvent() {
}
/**
* Processes the response Finds the matching contentobject for the repsonse
* using the id of the response and sets its status to done. At last the
* TransferComplete method of the ContentObject is called.
*
* @param resp Response object that has been processed
*/
@Override
protected final void processCommsResponse(final Response resp) {
ContentObject co = requestContentObjectMatchTable.remove(resp.mReqId);
if (co == null) { // check if we have an invalid response
return;
}
List<BaseDataType> mDataTypes = resp.mDataTypes;
// Sometimes it is empty
if (mDataTypes == null) {
co.setTransferStatus(ContentObject.TransferStatus.ERROR);
RuntimeException exc = new RuntimeException("Empty response returned");
co.getTransferListener().transferError(co, exc);
return;
}
Object data = mDataTypes.get(0);
if (data instanceof ServerError) {
co.setTransferStatus(ContentObject.TransferStatus.ERROR);
RuntimeException exc = new RuntimeException(data.toString());
co.getTransferListener().transferError(co, exc);
} else {
co.setTransferStatus(ContentObject.TransferStatus.DONE);
co.setExtResponse((ExternalResponseObject)data);
co.getTransferListener().transferComplete(co);
}
}
/**
* Empty implementation of abstract method from BaseEngine.
*/
@Override
protected void processUiRequest(final ServiceUiRequest requestId, final Object data) {
}
/**
* run method of this engine iterates over the downloadqueue, makes requests
* out of ContentObjects and puts them into QueueManager queue.
*/
@Override
public final void run() {
if (isCommsResponseOutstanding() && processCommsInQueue()) {
return;
}
ContentObject co;
boolean queueChanged = false;
while ((co = mDownloadQueue.poll()) != null) {
queueChanged = true;
// set the status of this contentobject to transferring
co.setTransferStatus(ContentObject.TransferStatus.TRANSFERRING);
Request request = new Request(co.getUrl().toString(), co.getUrlParams(), engineId());
QueueManager.getInstance().addRequest(request);
// important: later we will match done requests back to the
// contentobject using this map
requestContentObjectMatchTable.put(request.getRequestId(), co);
}
if (queueChanged) {
QueueManager.getInstance().fireQueueStateChanged();
}
}
}
diff --git a/tests/build.xml b/tests/build.xml
index 2f59a6c..ec720ca 100755
--- a/tests/build.xml
+++ b/tests/build.xml
@@ -1,665 +1,669 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<project name="tests">
-
- <!-- The local.properties file is created and updated by the 'android' tool.
- It contains the path to the SDK. It should *NOT* be checked in in Version
- Control Systems. -->
- <!-- <property file="local.properties" /> Point to the SDK location manually -->
- <property name="sdk.dir" value="C:\\tools\\android-sdk-windows" />
- <property name="sdk-location" value="C:\\tools\\android-sdk-windows" />
+ <property environment="env"/>
<!-- The build.properties file can be created by you and is never touched
by the 'android' tool. This is the place to change some of the default property values
used by the Ant rules.
Here are some properties you may want to change/update:
application.package
the name of your application package as defined in the manifest. Used by the
'uninstall' rule.
source.dir
the name of the source directory. Default is 'src'.
out.dir
the name of the output directory. Default is 'bin'.
Properties related to the SDK location or the project target should be updated
using the 'android' tool with the 'update' action.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems.
-->
<property file="build.properties" />
<!-- The default.properties file is created and updated by the 'android' tool, as well
as ADT.
This file is an integral part of the build system for your application and
should be checked in in Version Control Systems. -->
<property file="default.properties" />
+ <!-- Load the properties file based on the environment variable USERNAME_360. If you did not set it
+ already on your system, please do so. After setting it, create a new properties file in
+ build_properties_file with the name USERNAME_360.properties and add the sdk.dir and xml.task.dir properties
+ to it. -->
+ <property file="../build_property_files/${env.USERNAME_360}.properties" />
+
+ <echo>Building for username ${env.USERNAME_360}. SDK-Directory is ${sdk.dir} and the
+ XMLTask is found in ${xml.task.dir}...</echo>
+
<!-- Custom Android task to deal with the project target, and import the proper rules.
This requires ant 1.6.0 or above. -->
<path id="android.antlibs">
<pathelement path="${sdk.dir}/tools/lib/anttasks.jar" />
<pathelement path="${sdk.dir}/tools/lib/sdklib.jar" />
<pathelement path="${sdk.dir}/tools/lib/androidprefs.jar" />
<pathelement path="${sdk.dir}/tools/lib/apkbuilder.jar" />
<pathelement path="${sdk.dir}/tools/lib/jarutils.jar" />
</path>
<taskdef name="setup"
classname="com.android.ant.SetupTask"
classpathref="android.antlibs" />
<!-- Execute the Android Setup task that will setup some properties specific to the target,
and import the build rules files.
The rules file is imported from
<SDK>/platforms/<target_platform>/templates/android_rules.xml
To customize some build steps for your project:
- copy the content of the main node <project> from android_rules.xml
- paste it in this build.xml below the <setup /> task.
- disable the import by changing the setup task below to <setup import="false" />
This will ensure that the properties are setup correctly but that your customized
build steps are used.
-->
<setup import="false" />
<!-- EMMA Coverage interface for build script -->
<target name="emma-coverage-interface">
<echo>EMMA Coverage interface for build script.</echo>
<ant target="coverage" />
</target>
<!-- JUunit interface for build script -->
<target name="run-tests-interface">
<echo>JUunit interface for build script.</echo>
<ant target="run-tests" />
</target>
<!-- ################ IMPORT <target_platform>/templates/android_rules.xml ############
This is code copied from <target_platform>/templates/android_rules.xml so EMMA tests can be
run inside the build script without path issues. -->
<!--
This rules file is meant to be imported by the custom Ant task:
com.android.ant.AndroidInitTask
The following properties are put in place by the importing task:
android.jar, android.aidl, aapt, aidl, and dx
Additionnaly, the task sets up the following classpath reference:
android.target.classpath
This is used by the compiler task as the boot classpath.
-->
<!-- Custom tasks -->
<taskdef name="aaptexec"
classname="com.android.ant.AaptExecLoopTask"
classpathref="android.antlibs" />
<taskdef name="apkbuilder"
classname="com.android.ant.ApkBuilderTask"
classpathref="android.antlibs" />
<taskdef name="xpath"
classname="com.android.ant.XPathTask"
classpathref="android.antlibs" />
<!-- Properties -->
<!-- Tells adb which device to target. You can change this from the command line
by invoking "ant -Dadb.device.arg=-d" for device "ant -Dadb.device.arg=-e" for
the emulator. -->
<property name="adb.device.arg" value="" />
<property name="android.tools.dir" location="${sdk.dir}/tools" />
<!-- Name of the application package extracted from manifest file -->
<xpath input="AndroidManifest.xml" expression="/manifest/@package"
output="manifest.package" />
<!-- Input directories -->
<property name="source.dir" value="src" />
<property name="source.absolute.dir" location="${source.dir}" />
<property name="gen.dir" value="gen" />
<property name="gen.absolute.dir" location="${gen.dir}" />
<property name="resource.dir" value="res" />
<property name="resource.absolute.dir" location="${resource.dir}" />
<property name="asset.dir" value="assets" />
<property name="asset.absolute.dir" location="${asset.dir}" />
<!-- Directory for the third party java libraries -->
<property name="external.libs.dir" value="libs" />
<property name="external.libs.absolute.dir" location="${external.libs.dir}" />
<!-- Directory for the native libraries -->
<property name="native.libs.dir" value="libs" />
<property name="native.libs.absolute.dir" location="${native.libs.dir}" />
<!-- Output directories -->
<property name="out.dir" value="bin" />
<property name="out.absolute.dir" location="${out.dir}" />
<property name="out.classes.dir" value="${out.absolute.dir}/classes" />
<property name="out.classes.absolute.dir" location="${out.classes.dir}" />
<!-- Intermediate files -->
<property name="dex.file.name" value="classes.dex" />
<property name="intermediate.dex.file" location="${out.absolute.dir}/${dex.file.name}" />
<!-- The final package file to generate -->
<property name="out.debug.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-debug-unaligned.apk" />
<property name="out.debug.package"
location="${out.absolute.dir}/${ant.project.name}-debug.apk" />
<property name="out.unsigned.package"
location="${out.absolute.dir}/${ant.project.name}-unsigned.apk" />
<property name="out.unaligned.package"
location="${out.absolute.dir}/${ant.project.name}-unaligned.apk" />
<property name="out.release.package"
location="${out.absolute.dir}/${ant.project.name}-release.apk" />
<!-- Verbosity -->
<property name="verbose" value="false" />
<!-- This is needed by emma as it uses multilevel verbosity instead of simple 'true' or 'false'
The property 'verbosity' is not user configurable and depends exclusively on 'verbose'
value.-->
<condition property="verbosity" value="verbose" else="quiet">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of zipalign and aapt. Depends exclusively on 'verbose'
-->
<condition property="v.option" value="-v" else="">
<istrue value="${verbose}" />
</condition>
<!-- This is needed to switch verbosity of dx. Depends exclusively on 'verbose' -->
<condition property="verbose.option" value="--verbose" else="">
<istrue value="${verbose}" />
</condition>
<!-- Tools -->
<condition property="exe" value=".exe" else=""><os family="windows" /></condition>
<property name="adb" location="${android.tools.dir}/adb${exe}" />
<property name="zipalign" location="${android.tools.dir}/zipalign${exe}" />
<!-- Emma configuration -->
<property name="emma.dir" value="${sdk.dir}/tools/lib" />
<path id="emma.lib">
<pathelement location="${emma.dir}/emma.jar" />
<pathelement location="${emma.dir}/emma_ant.jar" />
</path>
<taskdef resource="emma_ant.properties" classpathref="emma.lib" />
<!-- End of emma configuration -->
<!-- Macros -->
<!-- Configurable macro, which allows to pass as parameters output directory,
output dex filename and external libraries to dex (optional) -->
<macrodef name="dex-helper">
<element name="external-libs" optional="yes" />
<element name="extra-parameters" optional="yes" />
<sequential>
<echo>Converting compiled files and external libraries into ${intermediate.dex.file}...
</echo>
<apply executable="${dx}" failonerror="true" parallel="true">
<arg value="--dex" />
<arg value="--output=${intermediate.dex.file}" />
<extra-parameters />
<arg line="${verbose.option}" />
<arg path="${out.classes.absolute.dir}" />
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<external-libs />
</apply>
</sequential>
</macrodef>
<!-- This is macro that enable passing variable list of external jar files to ApkBuilder
Example of use:
<package-helper>
<extra-jars>
<jarfolder path="my_jars" />
<jarfile path="foo/bar.jar" />
<jarfolder path="your_jars" />
</extra-jars>
</package-helper> -->
<macrodef name="package-helper">
<attribute name="sign.package" />
<element name="extra-jars" optional="yes" />
<sequential>
<apkbuilder
outfolder="${out.absolute.dir}"
basename="${ant.project.name}"
signed="@{sign.package}"
verbose="${verbose}">
<file path="${intermediate.dex.file}" />
<sourcefolder path="${source.absolute.dir}" />
<nativefolder path="${native.libs.absolute.dir}" />
<jarfolder path="${external.libs.absolute.dir}" />
<extra-jars/>
</apkbuilder>
</sequential>
</macrodef>
<!-- This is macro which zipaligns in.package and outputs it to out.package. Used by targets
debug, -debug-with-emma and release.-->
<macrodef name="zipalign-helper">
<attribute name="in.package" />
<attribute name="out.package" />
<sequential>
<echo>Running zip align on final apk...</echo>
<exec executable="${zipalign}" failonerror="true">
<arg line="${v.option}" />
<arg value="-f" />
<arg value="4" />
<arg path="@{in.package}" />
<arg path="@{out.package}" />
</exec>
</sequential>
</macrodef>
<!-- This is macro used only for sharing code among two targets, -install and
-install-with-emma which do exactly the same but differ in dependencies -->
<macrodef name="install-helper">
<sequential>
<echo>Installing ${out.debug.package} onto default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="install" />
<arg value="-r" />
<arg path="${out.debug.package}" />
</exec>
</sequential>
</macrodef>
<!-- Rules -->
<!-- Creates the output directories if they don't exist yet. -->
<target name="-dirs">
<echo>Creating output directories if needed...</echo>
<mkdir dir="${resource.absolute.dir}" />
<mkdir dir="${external.libs.absolute.dir}" />
<mkdir dir="${gen.absolute.dir}" />
<mkdir dir="${out.absolute.dir}" />
<mkdir dir="${out.classes.absolute.dir}" />
</target>
<!-- Generates the R.java file for this project's resources. -->
<target name="-resource-src" depends="-dirs">
<echo>Generating R.java / Manifest.java from the resources...</echo>
<exec executable="${aapt}" failonerror="true">
<arg value="package" />
<arg line="${v.option}" />
<arg value="-m" />
<arg value="-J" />
<arg path="${gen.absolute.dir}" />
<arg value="-M" />
<arg path="AndroidManifest.xml" />
<arg value="-S" />
<arg path="${resource.absolute.dir}" />
<arg value="-I" />
<arg path="${android.jar}" />
</exec>
</target>
<!-- Generates java classes from .aidl files. -->
<target name="-aidl" depends="-dirs">
<echo>Compiling aidl files into Java classes...</echo>
<apply executable="${aidl}" failonerror="true">
<arg value="-p${android.aidl}" />
<arg value="-I${source.absolute.dir}" />
<arg value="-o${gen.absolute.dir}" />
<fileset dir="${source.absolute.dir}">
<include name="**/*.aidl" />
</fileset>
</apply>
</target>
<!-- Compiles this project's .java files into .class files. -->
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- If android rules are used for a test project, its classpath should include
tested project's location -->
<condition property="extensible.classpath"
value="${tested.project.absolute.dir}/bin/classes" else=".">
<isset property="tested.project.absolute.dir" />
</condition>
<echo>extensible.classpath: ${extensible.classpath}</echo>
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}">
<src path="${source.absolute.dir}" />
+ <src path="../../${ui.project.name}/src" />
<src path="${gen.absolute.dir}" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
</classpath>
</javac>
</target>
<!-- Converts this project's .class files into .dex files -->
<target name="-dex" depends="compile">
<dex-helper />
</target>
<!-- Puts the project's resources into the output package file
This actually can create multiple resource package in case
Some custom apk with specific configuration have been
declared in default.properties.
-->
<target name="-package-resources">
<echo>Packaging resources</echo>
<aaptexec executable="${aapt}"
command="package"
manifest="AndroidManifest.xml"
resources="${resource.absolute.dir}"
assets="${asset.absolute.dir}"
androidjar="${android.jar}"
outfolder="${out.absolute.dir}"
basename="${ant.project.name}" />
</target>
<!-- Packages the application and sign it with a debug key. -->
<target name="-package-debug-sign" depends="-dex, -package-resources">
<package-helper sign.package="true" />
</target>
<!-- Packages the application without signing it. -->
<target name="-package-no-sign" depends="-dex, -package-resources">
<package-helper sign.package="false" />
</target>
<target name="-compile-tested-if-test" if="tested.project.dir" unless="do.not.compile.again">
<subant target="compile">
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<!-- Builds debug output package, provided all the necessary files are already dexed -->
<target name="debug" depends="-compile-tested-if-test, -package-debug-sign"
description="Builds the application and signs it with a debug key.">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
<echo>Debug Package: ${out.debug.package}</echo>
</target>
<target name="-release-check">
<condition property="release.sign">
<and>
<isset property="key.store" />
<isset property="key.alias" />
</and>
</condition>
</target>
<target name="-release-nosign" depends="-release-check" unless="release.sign">
<echo>No key.store and key.alias properties found in build.properties.</echo>
<echo>Please sign ${out.unsigned.package} manually</echo>
<echo>and run zipalign from the Android SDK tools.</echo>
</target>
<target name="release" depends="-package-no-sign, -release-nosign" if="release.sign"
description="Builds the application. The generated apk file must be signed before
it is published.">
<!-- Gets passwords -->
<input
message="Please enter keystore password (store:${key.store}):"
addproperty="key.store.password" />
<input
message="Please enter password for alias '${key.alias}':"
addproperty="key.alias.password" />
<!-- Signs the APK -->
<echo>Signing final apk...</echo>
<signjar
jar="${out.unsigned.package}"
signedjar="${out.unaligned.package}"
keystore="${key.store}"
storepass="${key.store.password}"
alias="${key.alias}"
keypass="${key.alias.password}"
verbose="${verbose}" />
<!-- Zip aligns the APK -->
<zipalign-helper in.package="${out.unaligned.package}"
out.package="${out.release.package}" />
<echo>Release Package: ${out.release.package}</echo>
</target>
<target name="install" depends="debug"
description="Installs/reinstalls the debug package onto a running
emulator or device. If the application was previously installed,
the signatures must match." >
<install-helper />
</target>
<target name="-uninstall-check">
<condition property="uninstall.run">
<isset property="manifest.package" />
</condition>
</target>
<target name="-uninstall-error" depends="-uninstall-check" unless="uninstall.run">
<echo>Unable to run 'ant uninstall', manifest.package property is not defined.
</echo>
</target>
<!-- Uninstalls the package from the default emulator/device -->
<target name="uninstall" depends="-uninstall-error" if="uninstall.run"
description="Uninstalls the application from a running emulator or device.">
<echo>Uninstalling ${manifest.package} from the default emulator or device...</echo>
<exec executable="${adb}" failonerror="true">
<arg line="${adb.device.arg}" />
<arg value="uninstall" />
<arg value="${manifest.package}" />
</exec>
</target>
<target name="clean" description="Removes output files created by other targets.">
<delete dir="${out.absolute.dir}" verbose="${verbose}" />
<delete dir="${gen.absolute.dir}" verbose="${verbose}" />
</target>
<!-- Targets for code-coverage measurement purposes, invoked from external file -->
<!-- Emma-instruments tested project classes (compiles the tested project if necessary)
and writes instrumented classes to ${instrumentation.absolute.dir}/classes -->
<target name="-emma-instrument" depends="compile">
<echo>Instrumenting classes from ${out.absolute.dir}/classes...</echo>
<!-- It only instruments class files, not any external libs -->
<emma enabled="true">
<instr verbosity="${verbosity}"
mode="overwrite"
instrpath="${out.absolute.dir}/classes"
outdir="${out.absolute.dir}/classes">
</instr>
<!-- TODO: exclusion filters on R*.class and allowing custom exclusion from
user defined file -->
</emma>
</target>
<target name="-dex-instrumented" depends="-emma-instrument">
<dex-helper>
<extra-parameters>
<arg value="--no-locals" />
</extra-parameters>
<external-libs>
<fileset file="${emma.dir}/emma_device.jar" />
</external-libs>
</dex-helper>
</target>
<!-- Invoked from external files for code coverage purposes -->
<target name="-package-with-emma" depends="-dex-instrumented, -package-resources">
<package-helper sign.package="true">
<extra-jars>
<!-- Injected from external file -->
<jarfile path="${emma.dir}/emma_device.jar" />
</extra-jars>
</package-helper>
</target>
<target name="-debug-with-emma" depends="-package-with-emma">
<zipalign-helper in.package="${out.debug.unaligned.package}"
out.package="${out.debug.package}" />
</target>
<target name="-install-with-emma" depends="-debug-with-emma">
<install-helper />
</target>
<!-- End of targets for code-coverage measurement purposes -->
<target name="help">
<!-- displays starts at col 13
|13 80| -->
<echo>Android Ant Build. Available targets:</echo>
<echo> help: Displays this help.</echo>
<echo> clean: Removes output files created by other targets.</echo>
<echo> compile: Compiles project's .java files into .class files.</echo>
<echo> debug: Builds the application and signs it with a debug key.</echo>
<echo> release: Builds the application. The generated apk file must be</echo>
<echo> signed before it is published.</echo>
<echo> install: Installs/reinstalls the debug package onto a running</echo>
<echo> emulator or device.</echo>
<echo> If the application was previously installed, the</echo>
<echo> signatures must match.</echo>
<echo> uninstall: Uninstalls the application from a running emulator or</echo>
<echo> device.</echo>
</target>
<!-- ################ END IMPORT <target_platform>/templates/android_rules.xml ############ -->
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
<property name="tested.project.absolute.dir" location="${tested.project.dir}" />
<property name="instrumentation.dir" value="instrumented" />
<property name="instrumentation.absolute.dir" location="${instrumentation.dir}" />
<property name="test.runner" value="android.test.InstrumentationTestRunner" />
<!-- Application package of the tested project extracted from its manifest file -->
<xpath input="${tested.project.absolute.dir}/AndroidManifest.xml"
expression="/manifest/@package" output="tested.manifest.package" />
<!-- TODO: make it more configurable in the next CL's - now it is default for auto-generated
project -->
<property name="emma.dump.file"
value="/data/data/${tested.manifest.package}/files/coverage.ec" />
<macrodef name="run-tests-helper">
<attribute name="emma.enabled" default="false" />
<element name="extra-instrument-args" optional="yes" />
<sequential>
<echo>Running tests ...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="shell" />
<arg value="am" />
<arg value="instrument" />
<arg value="-w" />
<arg value="-e" />
<arg value="coverage" />
<arg value="@{emma.enabled}" />
<extra-instrument-args />
<arg value="${manifest.package}/${test.runner}" />
</exec>
</sequential>
</macrodef>
<!-- Invoking this target sets the value of extensible.classpath, which is being added to javac
classpath in target 'compile' (android_rules.xml) -->
<target name="-set-coverage-classpath">
<property name="extensible.classpath"
location="${instrumentation.absolute.dir}/classes" />
</target>
<!-- Ensures that tested project is installed on the device before we run the tests.
Used for ordinary tests, without coverage measurement -->
<target name="-install-tested-project">
<property name="do.not.compile.again" value="true" />
<subant target="install">
<property name="sdk.dir" location="${sdk.dir}"/>
- <property name="sdk-location" location="${sdk-location}"/>
+ <property name="sdk-location" location="${sdk.dir}"/>
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="run-tests" depends="-install-tested-project, install"
description="Runs tests from the package defined in test.package property">
<run-tests-helper />
</target>
<target name="-install-instrumented">
<property name="do.not.compile.again" value="true" />
<subant target="-install-with-emma">
<property name="out.absolute.dir" value="${instrumentation.absolute.dir}" />
<fileset dir="${tested.project.absolute.dir}" includes="build.xml" />
</subant>
</target>
<target name="coverage" depends="-set-coverage-classpath, -install-instrumented, install"
description="Runs the tests against the instrumented code and generates
code coverage report">
<run-tests-helper emma.enabled="true">
<extra-instrument-args>
<arg value="-e" />
<arg value="coverageFile" />
<arg value="${emma.dump.file}" />
</extra-instrument-args>
</run-tests-helper>
<echo>Downloading coverage file into project directory...</echo>
<exec executable="${adb}" failonerror="true">
<arg value="pull" />
<arg value="${emma.dump.file}" />
<arg value="coverage.ec" />
</exec>
<echo>#################### INSERTED CODE #####################</echo>
<move file="${tested.project.absolute.dir}/coverage.em"
tofile="${tested.project.absolute.dir}/tests/coverage.em"/>
<echo>#################### INSERTED CODE #####################</echo>
<echo>Extracting coverage report...</echo>
<emma>
<report sourcepath="${tested.project.absolute.dir}/${source.dir}"
verbosity="${verbosity}">
<!-- TODO: report.dir or something like should be introduced if necessary -->
<infileset dir=".">
<include name="coverage.ec" />
<include name="coverage.em" />
</infileset>
<!-- TODO: reports in other, indicated by user formats -->
<html outfile="coverage.html" />
</report>
</emma>
<echo>Cleaning up temporary files...</echo>
<delete dir="${instrumentation.absolute.dir}" />
<delete file="coverage.ec" />
<delete file="coverage.em" />
<echo>Saving the report file in ${basedir}/coverage/coverage.html</echo>
</target>
<!-- ############## END IMPORT <target_platform>/templates/android_test_rules.xml ########## -->
</project>
\ No newline at end of file
diff --git a/tests/default.properties b/tests/default.properties
index ae7b77e..c5d5335 100755
--- a/tests/default.properties
+++ b/tests/default.properties
@@ -1,14 +1,14 @@
# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "build.properties", and override values to adapt the script to your
# project structure.
# Indicates whether an apk should be generated for each density.
split.density=false
# Project target.
-target=android-6
+target=android-8
apk-configurations=
|
360/360-Engine-for-Android
|
442fee93841ffb5d5f4af43c5d93c1a5674350ba
|
manifest changed
|
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 3c49fdf..67704d8 100755
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -1,393 +1,108 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- CDDL HEADER START
The contents of this file are subject to the terms of the Common Development
and Distribution License (the "License").
You may not use this file except in compliance with the License.
You can obtain a copy of the license at
src/com/vodafone360/people/VODAFONE.LICENSE.txt or
http://github.com/360/360-Engine-for-Android
See the License for the specific language governing permissions and
limitations under the License.
When distributing Covered Code, include this CDDL HEADER in each file and
include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
If applicable, add the following below this CDDL HEADER, with the fields
enclosed by brackets "[]" replaced with your own identifying information:
Portions Copyright [yyyy] [name of copyright owner]
CDDL HEADER END
Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
Use is subject to license terms.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
- android:versionCode="50"
- android:versionName="50"
+ android:versionCode="58"
+ android:versionName="58"
package="com.vodafone360.people"
>
<!-- WARNING: Only Edit "AndroidManifest.xml.edit" as the contents of the main file will be overwritten -->
<supports-screens
android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:anyDensity="true"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.CALL_PRIVILEGED" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_SMS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SMS"/>
<!-- Android 2.X specific -->
<uses-permission android:name="android.permission.GET_ACCOUNTS"/>
-
- <!-- FLURRY only -->
- <!-- <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> -->
<application android:theme="@style/PeopleWhiteTheme"
android:name=".MainApplication"
android:label="@string/app_name"
android:debuggable="true"
android:icon="@drawable/pt_launcher_icon">
-
- <!-- Debug activities %%%%%%%% -->
- <!-- For a live release:
- - Comment out .debug. Activities below
- - Set application.android:debuggable to false
- -->
- <activity android:name=".ui.debug.UpdateServiceAgentActivity"
- android:label="@string/UpdateServiceAgentActivity_TextView_title">
- <intent-filter>
- <action android:name="com.vodafone360.people.ui.debug.UPDATE_SERVICEAGENT"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- </activity>
- <activity android:name=".ui.debug.PresenceListActivity"
- android:label="@string/PresenceViewActivity_TextView_title">
- <intent-filter>
- <action android:name="com.vodafone360.people.ui.debug.VIEW_PRESENCE_NEW"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- </activity>
- <activity android:name=".ui.debug.PresenceViewActivity"
- android:label="@string/PresenceViewActivity_TextView_title">
- <intent-filter>
- <action android:name="com.vodafone360.people.ui.debug.VIEW_PRESENCE"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- </activity>
- <activity android:name=".ui.debug.DatabaseDebugActivity"
- android:label="Database Debug">
- <intent-filter>
- <action android:name="com.vodafone360.people.ui.debug.VIEW_DATABASE_DEBUG"/>
- <category android:name="android.intent.category.DEFAULT"/>
- </intent-filter>
- </activity>
- <!-- Debug activities %%%%%%%% -->
-
- <!-- Activity whose purpose is to start either login or contacts list -->
- <activity android:name=".ui.StartActivity">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
-
- <!-- Login/register activity -->
- <activity android:name=".ui.startup.LandingPageActivity"/>
-
- <!-- 360 Account Creation Create Account Details activity -->
- <activity android:name=".ui.startup.signup.SignupCreateAccountDetailsActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- 360 Account Creation Password Creation activity -->
- <activity android:name=".ui.startup.signup.SignupPasswordCreationActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- 360 Account Third Party Accounts activity -->
- <activity android:name=".ui.thirdparty.ThirdPartyAccountsActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- 360 Account Third Party EnterAccount Details activity -->
- <activity android:name=".ui.thirdparty.ThirdPartyEnterAccountActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- 360 Account Third Party EnterAccount Details activity -->
- <activity android:name=".ui.thirdparty.ValidatingYourThirdPartyAccountActivity" />
-
- <!-- 360 Contact Status List activity -->
- <activity android:name=".ui.status.StatusListActivity" />
-
- <!-- 360 Account Syncing Your Address Book activity -->
- <activity android:name=".ui.thirdparty.SyncingYourAddressBookActivity" />
-
- <!-- 360 Account Third Party Accounts activity -->
- <activity android:name=".ui.thirdparty.ThirdPartyNewAccountSelectionActivity" />
-
- <!-- 360 Account Creation Login Server activity -->
- <activity android:name=".ui.startup.signup.SignupLoginServerActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- Tab container for TwelveKeyDialer, RecentCallsList -->
- <activity android:name=".ui.tabs.StartTabsActivity"
- android:launchMode="singleTask"
- android:screenOrientation="nosensor">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="vnd.android-dir/mms-sms"/>
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.DIAL" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:mimeType="vnd.android.cursor.item/phone" />
- <data android:mimeType="vnd.android.cursor.item/person" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.DIAL" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="voicemail" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.DIAL" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:mimeType="vnd.android.cursor.dir/calls" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="vnd.android-dir/mms-sms" android:scheme="content"/>
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.CALL_BUTTON" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <action android:name="android.intent.action.DIAL" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.BROWSABLE" />
- <data android:scheme="tel" />
- </intent-filter>
- </activity>
-
- <!-- A virtual 12 key dialer -->
- <activity android:name=".ui.tabs.TwelveKeyDialer"
- android:launchMode="singleTop"
- android:screenOrientation="nosensor">
- <intent-filter>
- <action android:name="com.android.phone.action.TOUCH_DIALER" />
- <category android:name="android.intent.category.DEFAULT" />
- <category android:name="android.intent.category.TAB" />
- </intent-filter>
- </activity>
-
- <activity android:name=".ui.timeline.TimelineListActivity"/>
- <activity android:name=".ui.timeline.TimelineHistoryActivity"/>
- <activity android:name=".ui.startup.login.ForgotUsernameActivity"
- android:theme="@style/PeopleWhiteTheme.Dialog"/>
-
- <!-- The list of contacts -->
- <activity android:name=".ui.contacts.ContactListActivity">
- <intent-filter>
- <action android:name="android.intent.action.INSERT_OR_EDIT" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="vnd.android.cursor.item/person" />
- </intent-filter>
- <intent-filter>
- <action android:name="android.intent.action.SEARCH" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.android.contacts.action.FILTER_CONTACTS" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- <meta-data android:name="android.app.searchable" android:resource="@xml/searchable" />
- </activity>
-
- <!-- About activity -->
- <activity android:name=".ui.settings.AboutActivity"
- android:theme="@style/PeopleWhiteTheme.Dialog" />
-
- <!-- Settings activity -->
- <activity android:name=".ui.settings.NetworkSettingsActivity"/>
-
- <!-- AppSettings activity -->
- <activity android:name=".ui.settings.SettingsActivity"
- android:windowNoTitle="false"/>
-
- <!-- Used by Widget -->
- <activity android:name=".ui.widget.ChangeWidgetPhotoActivity"
- android:windowNoTitle="false"/>
-
- <activity android:name=".ui.widget.PeopleWidgetSetPresenceActivity"
- android:theme="@style/PeopleWhiteTheme.Dialog"/>
- <!-- END used by Widget -->
-
- <!-- The contact details -->
- <activity android:name=".ui.contacts.ContactProfileActivity">
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- <category android:name="android.intent.category.DEFAULT" />
- <data android:mimeType="vnd.android.cursor.item/com.vodafone360.people.profile" />
- </intent-filter>
- </activity>
- <!-- Edits the details of a single contact -->
- <activity android:name=".ui.contacts.EditContactActivity"
- android:windowSoftInputMode="stateVisible|adjustResize">
- <intent-filter android:label="@string/editContactDescription">
- <action android:name="android.intent.action.EDIT" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- <intent-filter android:label="@string/insertContactDescription">
- <action android:name="android.intent.action.INSERT" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </activity>
-
- <!-- Display Terms and Conditions Activity -->
-
- <activity android:name=".ui.utils.DisplayTermsActivity"
- android:theme="@style/PeopleWhiteTheme.Dialog">
- <intent-filter>
- <action android:name="android.intent.action.VIEW" />
- </intent-filter>
- </activity>
-
- <!-- Login Account Details activity -->
- <activity android:name=".ui.startup.login.LoginAccountDetailsActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- Login Account Server activity -->
- <activity android:name=".ui.startup.login.LoginAccountServerActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- Enter phone number manually activity -->
- <activity android:name=".ui.startup.EnterMobileNumberActivity"
- android:windowSoftInputMode="adjustPan" />
-
- <!-- Roaming notification dialog -->
- <activity android:name=".ui.utils.RoamingNotificationActivity"
- android:theme="@style/PeopleWhiteTheme.Dialog" />
-
- <!-- Makes .ContactListActivity the search target for any activity in Contacts -->
- <meta-data android:name="android.app.default_searchable"
- android:value=".ui.ContactListActivity" />
-
- <!-- Edits the details of a single contact -->
-
+
<service android:name=".service.RemoteService"
android:exported = "true">
<intent-filter>
<action
android:name="com.vodafone360.people.service.IRemoteService" />
</intent-filter>
<intent-filter>
<action
android:name="android.accounts.AccountAuthenticator" />
</intent-filter>
<meta-data
android:name="android.accounts.AccountAuthenticator"
android:resource="@xml/authenticator" />
<intent-filter>
<action
android:name="android.content.SyncAdapter" />
</intent-filter>
<meta-data
android:name="android.content.SyncAdapter"
android:resource="@xml/syncadapter" />
<meta-data
android:name="android.provider.CONTACTS_STRUCTURE"
android:resource="@xml/contacts" />
</service>
<receiver android:name=".service.receivers.StartBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<receiver android:name=".service.receivers.SmsBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.DATA_SMS_RECEIVED"/>
<data android:scheme="sms" />
<data android:host="localhost" />
<!-- <data android:port="16999" />-->
</intent-filter>
</receiver>
-
- <!-- Widget code START -->
- <activity android:name=".ui.widget.PeopleWidgetConfigurator">
- <intent-filter>
- <action android:name="android.appwidget.action.APPWIDGET_CONFIGURE" />
- </intent-filter>
- </activity>
- <receiver android:name=".ui.widget.WidgetProvider">
- <!-- This intent filter is used to display the widget in the home screen list -->
- <intent-filter>
- <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
- </intent-filter>
- <!-- This intent filter is used to manually update the widget -->
- <intent-filter>
- <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
- <data android:scheme="people_widget" />
- </intent-filter>
- <meta-data android:name="android.appwidget.provider"
- android:resource="@xml/widget_provider_info" />
- </receiver>
- <!-- Widget code END-->
-
- <receiver android:name=".ui.utils.SmsSentStatusReceiver">
- <intent-filter>
- <action android:name="com.vodafone360.people.utils.SmsSentStatusReceiver.MESSAGE_SENT" />
- </intent-filter>
- </receiver>
-
- <receiver android:name=".ui.utils.UINotificationReceiver">
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.NEW_CHAT_RECEIVED" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.ROAMING_ON" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.ROAMING_OFF" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.START_LOGIN_ACTIVITY" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.LOGIN_FAILED" />
- </intent-filter>
- <intent-filter>
- <action android:name="com.vodafone360.people.Intents.HIDE_LOGIN_NOTIFICATION" />
- </intent-filter>
- </receiver>
</application>
<uses-sdk android:minSdkVersion="3" />
</manifest>
\ No newline at end of file
|
360/360-Engine-for-Android
|
85e26d0cbf289a44c3d169ae23e4eaed82677d59
|
adding readme
|
diff --git a/README b/README
index e69de29..9defdfe 100644
--- a/README
+++ b/README
@@ -0,0 +1 @@
+For detailed documentation please visit http://360.github.com/360-Engine-for-Android
|
360/360-Engine-for-Android
|
b02abd92631cdad7e09ff5df43b6f0c2721db3a6
|
Small fix in ContentEngine
|
diff --git a/src/com/vodafone360/people/engine/content/ContentEngine.java b/src/com/vodafone360/people/engine/content/ContentEngine.java
index 27bdbab..a7e7970 100755
--- a/src/com/vodafone360/people/engine/content/ContentEngine.java
+++ b/src/com/vodafone360/people/engine/content/ContentEngine.java
@@ -1,230 +1,241 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the Common Development
* and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at
* src/com/vodafone360/people/VODAFONE.LICENSE.txt or
* http://github.com/360/360-Engine-for-Android
* See the License for the specific language governing permissions and
* limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each file and
* include the License file at src/com/vodafone360/people/VODAFONE.LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the fields
* enclosed by brackets "[]" replaced with your own identifying information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Copyright 2010 Vodafone Sales & Services Ltd. All rights reserved.
* Use is subject to license terms.
*/
package com.vodafone360.people.engine.content;
import java.util.Hashtable;
import java.util.List;
-import com.vodafone360.people.database.DatabaseHelper;
-import com.vodafone360.people.datatypes.ExternalResponseObject;
-import com.vodafone360.people.datatypes.ServerError;
-import com.vodafone360.people.engine.BaseEngine;
-import com.vodafone360.people.engine.EngineManager.EngineId;
-import com.vodafone360.people.service.ServiceUiRequest;
-import com.vodafone360.people.service.io.QueueManager;
-import com.vodafone360.people.service.io.Request;
-import com.vodafone360.people.service.io.ResponseQueue.Response;
+import src.com.vodafone360.people.database.DatabaseHelper;
+import src.com.vodafone360.people.datatypes.BaseDataType;
+import src.com.vodafone360.people.datatypes.ExternalResponseObject;
+import src.com.vodafone360.people.datatypes.ServerError;
+import src.com.vodafone360.people.engine.BaseEngine;
+import src.com.vodafone360.people.engine.BaseEngine.IEngineEventCallback;
+import src.com.vodafone360.people.engine.EngineManager.EngineId;
+import src.com.vodafone360.people.service.ServiceUiRequest;
+import src.com.vodafone360.people.service.io.QueueManager;
+import src.com.vodafone360.people.service.io.Request;
+import src.com.vodafone360.people.service.io.ResponseQueue.Response;
/**
* Content engine for downloading and uploading all kind of content (pictures,
* videos, files)
*/
public class ContentEngine extends BaseEngine {
/**
* Constructor for the ContentEngine.
*
* @param eventCallback IEngineEventCallback for calling the constructor of
* the super class
* @param dbHelper Instance of DatabaseHelper
*/
public ContentEngine(final IEngineEventCallback eventCallback, final DatabaseHelper dbHelper) {
super(eventCallback);
this.mDbHelper = dbHelper;
mEngineId = EngineId.CONTENT_ENGINE;
}
/**
* Queue with unprocessed ContentObjects.
*/
private FiFoQueue mUnprocessedQueue = new FiFoQueue();
/**
* Queue with ContentObjects for downloads.
*/
private FiFoQueue mDownloadQueue = new FiFoQueue();
/**
* Queue with ContentObjects for uploads.
*/
private FiFoQueue mUploadQueue = new FiFoQueue();
/**
* Instance of DatabaseHelper.
*/
private DatabaseHelper mDbHelper;
/**
* Hashtable to match requests to ContentObjects.
*/
private Hashtable<Integer, ContentObject> requestContentObjectMatchTable = new Hashtable<Integer, ContentObject>();
/**
* Getter for the local instance of DatabaseHelper.
*
* @return local instance of DatabaseHelper
*/
public final DatabaseHelper getDatabaseHelper() {
return mDbHelper;
}
/**
* Processes one ContentObject.
*
* @param co ContentObject to be processed
*/
public final void processContentObject(final ContentObject co) {
mUnprocessedQueue.add(co);
}
/**
* Iterates over the ContentObject list and processes every element.
*
* @param list List with ContentObjects which are to be processed
*/
public final void processContentObjects(final List<ContentObject> list) {
for (ContentObject co : list) {
processContentObject(co);
}
}
/**
* Processes the main queue and splits it into the download and upload
* queues.
*/
private void processQueue() {
ContentObject co;
// picking unprocessed ContentObjects
while ((co = mUnprocessedQueue.poll()) != null) {
// putting them to downloadqueue ...
if (co.getDirection() == ContentObject.TransferDirection.DOWNLOAD) {
mDownloadQueue.add(co);
} else {
// ... or the uploadqueue
mUploadQueue.add(co);
}
}
}
/**
* Determines the next RunTime of this Engine It first processes the
* in-queue and then look.
*
* @return time in milliseconds from now when the engine should be run
*/
@Override
public final long getNextRunTime() {
processQueue();
// if there are CommsResponses outstanding, run now
if (isCommsResponseOutstanding()) {
return 0;
}
return (mDownloadQueue.size() + mUploadQueue.size() > 0) ? 100 : -1;
}
/**
* Empty implementation without function at the moment.
*/
@Override
public void onCreate() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
public void onDestroy() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
protected void onRequestComplete() {
}
/**
* Empty implementation without function at the moment.
*/
@Override
protected void onTimeoutEvent() {
}
/**
* Processes the response Finds the matching contentobject for the repsonse
* using the id of the response and sets its status to done. At last the
* TransferComplete method of the ContentObject is called.
*
* @param resp Response object that has been processed
*/
@Override
protected final void processCommsResponse(final Response resp) {
ContentObject co = requestContentObjectMatchTable.remove(resp.mReqId);
- Object data = resp.mDataTypes.get(0);
+ List<BaseDataType> mDataTypes = resp.mDataTypes;
+ // Sometimes it is empty
+ if (mDataTypes == null) {
+ co.setTransferStatus(ContentObject.TransferStatus.ERROR);
+ RuntimeException exc = new RuntimeException("Empty response returned");
+ co.getTransferListener().transferError(co, exc);
+ return;
+ }
+
+ Object data = mDataTypes.get(0);
if (data instanceof ServerError) {
co.setTransferStatus(ContentObject.TransferStatus.ERROR);
RuntimeException exc = new RuntimeException(data.toString());
co.getTransferListener().transferError(co, exc);
} else {
co.setTransferStatus(ContentObject.TransferStatus.DONE);
co.setExtResponse((ExternalResponseObject)data);
co.getTransferListener().transferComplete(co);
}
}
/**
* Empty implementation of abstract method from BaseEngine.
*/
@Override
protected void processUiRequest(final ServiceUiRequest requestId, final Object data) {
}
/**
* run method of this engine iterates over the downloadqueue, makes requests
* out of ContentObjects and puts them into QueueManager queue.
*/
@Override
public final void run() {
if (isCommsResponseOutstanding() && processCommsInQueue()) {
return;
}
ContentObject co;
while ((co = mDownloadQueue.poll()) != null) {
// set the status of this contentobject to transferring
co.setTransferStatus(ContentObject.TransferStatus.TRANSFERRING);
Request request = new Request(co.getUrl().toString(), co.getUrlParams(), engineId());
QueueManager.getInstance().addRequest(request);
// important: later we will match done requests back to the
// contentobject using this map
requestContentObjectMatchTable.put(request.getRequestId(), co);
}
QueueManager.getInstance().fireQueueStateChanged();
}
}
|
360/360-Engine-for-Android
|
7a7b9d8120fe43028d19d9b4d901e54e23200afa
|
initial import
|
diff --git a/README b/README
new file mode 100644
index 0000000..e69de29
|
jcnetdev/yubnub
|
799c4ffc4d1170ee3d60a1978909e84360dcb9d3
|
Fixing Schema
|
diff --git a/Capfile b/Capfile
new file mode 100644
index 0000000..c36d48d
--- /dev/null
+++ b/Capfile
@@ -0,0 +1,3 @@
+load 'deploy' if respond_to?(:namespace) # cap2 differentiator
+Dir['vendor/plugins/*/recipes/*.rb'].each { |plugin| load(plugin) }
+load 'config/deploy'
\ No newline at end of file
diff --git a/config/deploy.rb b/config/deploy.rb
new file mode 100644
index 0000000..9fb840e
--- /dev/null
+++ b/config/deploy.rb
@@ -0,0 +1,227 @@
+set :application, "yubnub"
+set :server_name, "yubnub.opensourcerails.com"
+
+set :repository, "git://github.com/jcnetdev/yubnub.git"
+set :scm, "git"
+set :checkout, "export"
+set :deploy_via, :remote_cache
+
+set :base_path, "/var/www"
+set :deploy_to, "/var/www/production/#{application}"
+set :apache_site_folder, "/etc/apache2/sites-enabled"
+
+set :keep_releases, 3
+
+set :user, 'deploy'
+set :runner, 'deploy'
+
+# =============================================================================
+# You shouldn't have to modify the rest of these
+# =============================================================================
+
+role :web, server_name
+role :app, server_name
+role :db, server_name, :primary => true
+
+set :use_sudo, true
+
+# saves space by only keeping last 3 when running cleanup
+set :keep_releases, 3
+
+ssh_options[:paranoid] = false
+
+# =============================================================================
+# OVERRIDE TASKS
+# =============================================================================
+namespace :deploy do
+
+ desc "Restart Passenger"
+ task :restart, :roles => :app do
+ run "touch #{current_path}/tmp/restart.txt"
+ run "curl http://#{server_name}"
+ end
+
+ desc <<-DESC
+ Deploy and run pending migrations. This will work similarly to the \
+ `deploy' task, but will also run any pending migrations (via the \
+ `deploy:migrate' task) prior to updating the symlink. Note that the \
+ update in this case it is not atomic, and transactions are not used, \
+ because migrations are not guaranteed to be reversible.
+ DESC
+ task :migrations do
+ set :migrate_target, :latest
+ update_code
+ migrate
+ symlink
+ restart
+ end
+
+ desc "restart apache"
+ task :restart_apache do
+ sudo "/etc/init.d/apache2 stop"
+ sudo "/etc/init.d/apache2 start"
+ end
+
+ desc "start apache cluster"
+ task :start_apache do
+ sudo "/etc/init.d/apache2 start"
+ end
+
+ desc "stop apache cluster"
+ task :stop_apache do
+ sudo "/etc/init.d/apache2 stop"
+ end
+end
+
+before "deploy:restart", "admin:migrate"
+after "deploy", "live:send_request"
+
+after "deploy:setup", "init:database_yml"
+after "deploy:setup", "init:create_database"
+after "deploy:setup", "init:create_vhost"
+after "deploy:setup", "init:enable_site"
+namespace :init do
+ desc "create mysql db"
+ task :create_database do
+ #create the database on setup
+ set :db_user, Capistrano::CLI.ui.ask("database user: ") unless defined?(:db_user)
+ set :db_pass, Capistrano::CLI.password_prompt("database password: ") unless defined?(:db_pass)
+ run "echo \"CREATE DATABASE #{application}_production\" | mysql -u #{db_user} --password=#{db_pass}"
+ end
+
+ desc "enable site"
+ task :enable_site do
+ sudo "ln -nsf #{shared_path}/config/apache_site.conf #{apache_site_folder}/#{application}"
+
+ end
+
+
+ desc "create database.yml"
+ task :database_yml do
+ set :db_user, Capistrano::CLI.ui.ask("database user: ")
+ set :db_pass, Capistrano::CLI.password_prompt("database password: ")
+ database_configuration = %(
+---
+login: &login
+ adapter: mysql
+ database: #{application}_production
+ host: localhost
+ username: #{db_user}
+ password: #{db_pass}
+
+production:
+ <<: *login
+)
+ run "mkdir -p #{shared_path}/config"
+ put database_configuration, "#{shared_path}/config/database.yml"
+ end
+
+ desc "create vhost file"
+ task :create_vhost do
+
+ vhost_configuration = %(
+<VirtualHost *:80>
+ ServerName #{server_name}
+ DocumentRoot /var/www/production/#{application}/current/public
+</VirtualHost>
+)
+
+ put vhost_configuration, "#{shared_path}/config/apache_site.conf"
+
+ end
+
+end
+
+after "deploy:update_code", "localize:install_gems"
+after "deploy:update_code", "localize:copy_shared_configurations"
+
+namespace :localize do
+ desc "copy shared configurations to current"
+ task :copy_shared_configurations, :roles => [:app] do
+ %w[database.yml].each do |f|
+ run "ln -nsf #{shared_path}/config/#{f} #{release_path}/config/#{f}"
+ end
+ end
+
+ desc "installs / upgrades gem dependencies "
+ task :install_gems, :roles => [:app] do
+ sudo "date" # fuck you capistrano
+ run "cd #{release_path} && sudo rake RAILS_ENV=production gems:install"
+ end
+
+end
+
+namespace :live do
+ desc "send request"
+ task :send_request do
+ url = "http://#{server_name}"
+ puts `curl #{url} -g`
+ end
+
+ desc "remotely console"
+ task :console, :roles => :app do
+ input = ''
+ run "cd #{current_path} && ./script/console production" do |channel, stream, data|
+ next if data.chomp == input.chomp || data.chomp == ''
+ print data
+ channel.send_data(input = $stdin.gets) if data =~ /^(>|\?)>/
+ end
+ end
+
+ desc "tail production log files"
+ task :tail_logs, :roles => :app do
+ run "tail -f #{shared_path}/log/production.log -n 200" do |channel, stream, data|
+ puts # for an extra line break before the host name
+ puts "#{channel[:host]}: #{data}"
+ break if stream == :err
+ end
+ end
+
+ desc "show environment variables"
+ task :env, :roles => :app do
+ run "env"
+ end
+
+ task :show_env do
+ run "env"
+ end
+
+ task :show_path do
+ run "echo #{current_path}"
+ end
+
+ desc "remotely console"
+ task :console, :roles => :app do
+ input = ''
+ run "cd #{current_path} && ./script/console production" do |channel, stream, data|
+ next if data.chomp == input.chomp || data.chomp == ''
+ print data
+ channel.send_data(input = $stdin.gets) if data =~ /^(>|\?)>/
+ end
+ end
+
+ desc "tail production log files"
+ task :tail_logs, :roles => :app do
+ run "tail -f #{shared_path}/log/production.log -n 200" do |channel, stream, data|
+ puts # for an extra line break before the host name
+ puts "#{channel[:host]}: #{data}"
+ break if stream == :err
+ end
+ end
+end
+
+namespace :admin do
+ task :set_schema_info do
+ new_schema_version = Capistrano::CLI.ui.ask "New Schema Info Version: "
+ run "cd #{current_path} && ./script/runner --environment=production 'ActiveRecord::Base.connection.execute(\"UPDATE schema_info SET version=#{new_schema_version}\")'"
+ end
+
+ task :migrate do
+ run "cd #{current_path} && sudo rake RAILS_ENV=production db:migrate"
+ end
+
+ task :remote_rake do
+ rake_command = Capistrano::CLI.ui.ask "Rake Command to run: "
+ run "cd #{current_path} && sudo rake RAILS_ENV=production #{rake_command}"
+ end
+end
\ No newline at end of file
diff --git a/config/morph.rb b/config/morph.rb
index 053a7b8..a959983 100644
--- a/config/morph.rb
+++ b/config/morph.rb
@@ -1,280 +1,282 @@
require 'fileutils'
require 'cgi'
require 'net/https'
require 'yaml'
require 'highline/import'
load 'deploy'
# The svn repository is used to export the code into the temporary directory before
# uploading code into the Morph control panel. Currently only svn is supported,
# but you could change it to fit your need by changing the get_code task
set :repository, "." # Set here your repository! Example: 'https://www.myrepo.com/myapp/trunk'
set :repo_line_number, __LINE__ - 1 # Needed to report missing repository later on
# The version name to set in the control panel. Defautls to date and time, but can be altered by passing it
# on the command line as -s version_name='The Version Name'
set :version_name, Time.now.utc.strftime('%Y-%m-%d %H:%M:%S')
# If you want to use a different scm or use a different export method, you can chane it here
# Please note that the export to directory is removed before the checkout starts. If
# You want it to work differently, change the code in the get_code task
set :deploy_via, :export
set :scm, :git
# MORPH SETTINGS, please do not change
set :morph_host, "panel.mor.ph"
set :morph_port, 443
set :morph_tmp_dir, 'morph_tmp'
set :mex_key, "151aba3cc30502a4f5bafd2df827c23d0ff564fc"
set :mv_cmd, PLATFORM.include?('mswin') ? 'ren' : 'mv'
set :morph_tmp_dir, 'morph_tmp'
set :release_path, morph_tmp_dir # needed in order to generate the correct scm command
set :get_code_using, :get_code
set :req_retries, 3
namespace :morph do
abort('*** ERROR: You need a MeX key!') if !exists?(:mex_key) || mex_key.nil?
# This is the entry point task. It gets the new code, then upload it into S3
# to a special folder used later for deployment. Finally it mark the version
# Uploaded to be deployed
task :deploy do
transaction do
set :mex_key, mex_app_key if exists?(:mex_app_key)
abort('*** ERROR: You need a MeX key!') if !exists?(:mex_key) || mex_key.nil?
update_code
send_request(true, 'Post', morph_host, morph_port, '/api/deploy/deploy', {}, nil, "*** ERROR: Could not deploy the application!")
say("Deploy Done.")
end
end
# Specialized command to deploy from a packaged gem
task :deploy_from_gem do
set :get_code_using, :get_code_from_gem
deploy
end
# This task calls the get_code helper, then upload the code into S3
task :update_code do
transaction do
s3_obj_name = upload_code_to_s3
say("Creating new appspace version...")
#create a version in CP
req_flds = { 'morph-version-name' => version_name, 'morph-version-s3-object' => s3_obj_name }
send_request(true, 'Post', morph_host, morph_port, '/versions/create2', req_flds, nil, "*** ERROR: Could not create a new version!")
say("Code Upload Done.")
end
end
# A task that create a temp dir, export the code ouf ot svn and tar
# the code preparing it for upload.
# If you are not using svn, or using a different source control tool
# you can customize this file to work with it. The requirement is that
# It will export the whole structure into the temp directory as set in
# morph_tmp_dir.
#
# You can choose to release a different version than head by setting the
# Environment variable 'REL_VER' to the version to use.
task :get_code do
- # on_rollback do
- # remove_files([morph_tmp_dir, 'code_update.tar.gz'])
- # end
+ on_rollback do
+ remove_files([morph_tmp_dir, 'code_update.tar.gz'])
+ end
# Make sure we have a repo to work from!
abort("***ERROR: Must specify the repository to check out from! See line #{repo_line_number} in #{__FILE__}.") if !repository
transaction do
# Clean up previous deploys
remove_files([morph_tmp_dir, 'code_update.tar.gz'])
#get latest code from from the repository
say("Downloading the code from the repository...")
system(strategy.send(:command))
abort('*** ERROR: Export from repository failed! Please check the repository setting at the start of the file') if $?.to_i != 0
# Verify that we have the expected rails structure
['/app', '/public', '/config/environment.rb', '/lib'].each do |e|
abort "*** ERROR: Rails directories are missing. Please make sure your set :repository is correct!" if !File.exist?("#{morph_tmp_dir}#{e}")
end
# unpack our rubygems dependencies and inject them into the morph_tmp
system("rake RAILS_ENV=production gems:unpack")
+ system("rake RAILS_ENV=production rails:freeze:gems")
system("cp -Rf vendor/gems #{morph_tmp_dir}/vendor")
-
+ system("cp -Rf vendor/rails #{morph_tmp_dir}/vendor")
+
#create archive
system("tar -C #{morph_tmp_dir} -czf code_update.tar.gz --exclude='./.*' .")
abort('*** ERROR: Failed to tar the file for upload.') if $?.to_i != 0
# Verify that we have the expected rails structure in the archive
flist = `tar tzf code_update.tar.gz`
all_in = flist.include?('lib/') && flist.include?('app/') && flist.include?('config/environment.rb')
abort "***ERROR: code archive is missing the rails directories. Please check your checkout and tar" if !all_in
remove_files([morph_tmp_dir])
end
end
# Get the code from a packaged gem. Name comes from a setting passed to the command
# using the -s form
task :get_code_from_gem do
# Make sure we have the gem defined and that we have the gem file
if !exists?(:gem_file) || gem_file.nil?
abort("***ERROR: The gem file must be provided on the command line using -s.\n For example: cap -f morph_deploy.rb -s gem_file=/home/morph/my_app.gem morph:deploy_from_gem")
end
abort("***ERROR: gem file not found! Please check the file location and try again") if !File.exists?(gem_file)
# Remove older file
remove_files(["code_update.tar.gz"])
# Extract the data.tar.gz code from the gem
system("tar xf #{gem_file} data.tar.gz")
abort("***ERROR: Couldn't find the data.tar.gz file in the gem file provided!") if !File.exists?('data.tar.gz')
# rename it to upload_code.tar.gz
system("#{mv_cmd} data.tar.gz code_update.tar.gz")
end
# A task to get the S3 connection info and upload code_update.tar.gz
# Assumes another task prepared the tar.gz file
task :upload_code_to_s3 do
self.send get_code_using
abort "*** ERROR: Could not find archive to upload." unless File.exist?('code_update.tar.gz')
s3_data = ''
say('Getting upload information')
send_request(true, 'Get', morph_host, morph_port, '/api/s3/connection_data', {}, nil, "*** ERROR: Could not get the S3 connection data!") do |req, res|
s3_data = YAML.load(res.body)
end
if !s3_data.empty?
say('Uploading code to S3...')
File.open('code_update.tar.gz', 'rb') do |up_file|
send_request(false, 'Put', s3_data[:host], morph_port, s3_data[:path], s3_data[:header], up_file, "*** ERROR: Could not upload the code!")
end
end
s3_data[:obj_name]
end
# Helper to add the mex auth fields to the requests
def add_mex_fields(req)
if exists?(:deploy_key) and mex_key
req['morph-deploy-key'] = deploy_key
else
req['morph-user'] = morph_user
req['morph-pass'] = morph_pass
end
req['morph-app'] = mex_key
end
# Helper to generate REST requests, handle authentication and errors
def send_request(is_mex, req_type, host, port, url, fields_hash, up_file, error_msg)
tries_done = 0
res = ''
while res != :ok
if is_mex and (!exists?(:deploy_key) or !exists?(:mex_key))
say("*** Getting info for Morph authentication ***") if !exists?(:morph_user) || morph_user.nil? || !exists?(:morph_pass) || morph_pass.nil?
set(:morph_user, ask("Morph user: ")) if !exists?(:morph_user) || morph_user.nil?
set(:morph_pass, ask("Password: ") { |q| q.echo = false }) if !exists?(:morph_pass) || morph_pass.nil?
end
conn_start(host, port) do |http|
request = Module.module_eval("Net::HTTP::#{req_type}").new(url)
add_mex_fields(request) if is_mex
fields_hash.each_pair{|n,v| request[n] = v} # Add user defined header fields
# If a file is passed we upload it.
if up_file
request.content_length = up_file.lstat.size
request.body_stream = up_file # For uploads using streaming
else
request.content_length = 0
end
begin
response = http.request(request)
rescue Exception => ex
response = ex.to_s
end
# Handle auth errors and other errors!
res = verify_response(request, response, is_mex)
if res == :ok
yield(request, response) if block_given?
elsif exists?(:deploy_key) #if via deploy key, just exit
say("Incorrect deploy_key or mex_app_key")
exit
elsif res != :auth_fail # On auth_fail we just loop around
tries_done += 1
abort(error_msg) if tries_done > req_retries
end
end
end
end
# Helper to create a connection with all the needed setting
# And yeals to the block
def conn_start host = morph_host, port = morph_port
con = Net::HTTP.new(host, port)
con.use_ssl = true
# If you have cert files to use, change this to OpenSSL::SSL::VERIFY_PEER
# And set the ca_cert of the connection
con.verify_mode = OpenSSL::SSL::VERIFY_NONE
con.start
if block_given?
begin
return yield(con)
ensure
con.finish
end
end
con
end
# Helper to verify if a response is valid. Also handles authentication failures into MeX
def verify_response(request, response, is_mex)
res = :ok
if !response.is_a?(Net::HTTPOK)
if response.is_a?(Net::HTTPForbidden) && is_mex
say("Authentication failed! Please try again.")
set :morph_user, nil
set :morph_pass, nil
res = :auth_fail
else
if response.is_a?(String)
say("*** ERROR: connection failure: #{response}")
else
output_request_param(request, response)
end
res = :failure
end
end
return res
end
# Helper to output the results of REST calls to our servers or S3
def output_request_param(request, response)
puts "\n========== ERROR TRACE =========="
puts "+++++++ REQUEST HEADERS +++++++++"
request.each {|e,r| puts "#{e}: #{r}"}
puts "+++++++ RESPONSE HEADERS +++++++++"
response.each {|e,r| puts "#{e}: #{r}"}
puts "+++++++ RESPONSE BODY +++++++++"
puts response.body
puts "+++++++ RESPONSE TYPE +++++++++"
puts "#{response.class} (#{response.code})"
puts "========= END OF TRACE ==========\n"
end
def remove_files(lists)
FileUtils.cd(FileUtils.pwd)
FileUtils.rm_r(lists, :force => true) rescue ''
end
end
diff --git a/db/schema.rb b/db/schema.rb
index ca1b717..3451281 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,30 +1,30 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 0) do
+ActiveRecord::Schema.define do
create_table "banned_url_patterns", :force => true do |t|
t.string "pattern"
end
create_table "commands", :force => true do |t|
t.string "name"
t.text "url"
t.text "description"
t.integer "uses", :limit => 11, :default => 0
t.boolean "spam", :default => false
t.datetime "last_use_date"
t.datetime "golden_egg_date"
t.datetime "created_at"
t.datetime "updated_at"
end
end
|
jcnetdev/yubnub
|
afd86bd591affa74e9ff970b431c72c7b618f8cc
|
Fixing up some of the tests
|
diff --git a/app/models/parser.rb b/app/models/parser.rb
index 1acecd8..c19ff70 100644
--- a/app/models/parser.rb
+++ b/app/models/parser.rb
@@ -1,192 +1,192 @@
require 'net/http'
require 'uri'
class Parser
attr_accessor :url
attr_accessor :command
attr_accessor :command_name
attr_accessor :command_string
def self.get_url(command_string, default = nil)
Parser.new(command_string).parse(default).url
end
def initialize(command_string)
self.command_string = command_string
end
def parse(default = nil)
@default = default
self.url = parse_proper
return self
end
def parse_proper
# Great idea from Michele Trimarchi: if the user types in something that looks like
# a URL, just go to it. [Jon Aquino 2005-06-23]
return ApplicationController.helpers.prefix_with_http_if_necessary(command_string) if command_string =~ /^[^ ]+\.[a-z]{2,4}(\/[^ ]*)?$/
tokens = command_string.split
self.command_name = tokens[0]
args = tokens[1..-1].join(' ')
# find command
self.command ||= Command.by_name(self.command_name)
if self.command
# increment if found
self.command.uses += 1
self.command.last_use_date = Time.now
self.command.save unless self.command.new_record?
- elsif tokens.size > 1 and self.command_name and self.command_name.length < 5
- # tried to search for something but failed
- return nil
+ # elsif tokens.size > 1 and self.command_name and self.command_name.length < 5
+ # # tried to search for something but failed
+ # return nil
else
# find default if passed in
self.command = Command.by_name(@default)
args = command_string
end
if self.command
# Yes, we apply {...} substitutions both in the original URL and on the command line. [Jon Aquino 2005-07-16]
return combine(command.url, args)
else
return nil
end
end
def self.fill_in_without_switches(command_input)
fill_in(command_input) {|switch| "SWITCH_NOT_ALLOWED_HERE" }
end
# fill_in does double duty: it fills in switches and substitutions in the original URL, and fills in substitutions
# on the command line. [Jon Aquino 2005-07-16]
def fill_in(s)
n = 0
while s =~ /(\$?\{([^{}]+)\})/
match = $1
if match[0..0] == '$'
# A switch [Jon Aquino 2005-07-16]
s.gsub!(match, yield(match))
else
# A substitution [Jon Aquino 2005-07-16]
s.gsub!(match, response_text(match[1..-2]))
end
n += 1
if n > 50
# Protection against one form of recursion attack [Jon Aquino 2005-07-16]
raise 'Max number of substitutions reached'
end
end
return s
end
def response_text
# We can't make a real echo command for our unit tests because of the
# WEBrick limitation mentioned above. [Jon Aquino 2005-07-16]
if command_string =~ /^test_echo (.+)$/
return $1
end
# strip the string e.g. random.org's output ends with a newline. [Jon Aquino 2005-07-23]
# Thanks to Sean O'Hagan for finding a critical bug here -- I was limiting the length of
# text snippets to 200 characters -- this is way too small, cutting off URLs created by
# complex commands (notably splitv). Bumping it up to 10000. We still want to restrict it
# somewhat to prevent abuse. [Jon Aquino 2006-01-26]
fetch(parse_proper(command_string, nil)).body.strip[0..10000]
end
# If you are using WEBrick to run YubNub (i.e. if you are running YubNub in
# development mode), you may find that command substitutions will hang the
# app. For more information, see "timeout due to deadlocking on performing
# a net::http rails request inside a request", http://dev.rubyonrails.com/ticket/506
# [Jon Aquino 2005-07-16]
# If someone attempts a recursion attack (running a command that calls itself)
# Code for #fetch is from http.rb [Jon Aquino 2005-07-16]
def fetch( uri_str, limit = 10 )
# You should choose better exception.
raise ArgumentError, 'HTTP redirect too deep' if limit == 0
response = get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
else
response.error!
end
end
def get_response(uri)
Net::HTTP.new(uri.host, uri.port).start {|http|
# Set timeouts (in seconds) to mitigate recursion attacks [Jon Aquino 2005-07-16]
http.open_timeout = 10
http.read_timeout = 10
return http.request(Net::HTTP::Get.new(uri.request_uri))
}
end
def takes_parameters(url)
return url =~ /%s/ || url =~ /\$\{/
end
def combine(url, args)
if url.gsub!('[post]', '')
url = 'http://jonaquino.textdriven.com/sean_ohagan/get2post.php?yndesturl=' + url
end
# Suggestion from C Callosum: allow space to be converted to %20 rather than + [Jon Aquino 2005-07-01]
space_char = '+'
if url =~ /(\[use (.+) for spaces\])/
space_char = $2
url.gsub!($1, '')
end
# Suggestion from Wim Van Hooste: allow url-encoding to be turned off. [Jon Aquino 2005-07-01]
no_url_encoding = url.gsub!('[no url encoding]', '')
# Sean O'Hagan requested a way to specify the original command as a parameter to the command,
# for his parser.php script. [Jon Aquino 2005-07-10]
url.gsub!('${COMMAND}', post_process(command_string, space_char, no_url_encoding))
switch_to_value_hash = switch_to_value_hash(url, args)
url.gsub!('%s', post_process(switch_to_value_hash['%s'].join(' '), space_char, no_url_encoding))
url = fill_in(url) { |switch|
# Christopher Church suggested the syntax for default values: ${name=default} [Jon Aquino 2005-07-05]
switch_proper, default_value = switch[2..-2].split('=')
switch_proper = "${#{switch_proper}}"
value = (switch_to_value_hash[switch_proper] == [] and not default_value.nil?) ?
default_value :
switch_to_value_hash[switch_proper].join(' ')
post_process(value, space_char, no_url_encoding)
}
return url
end
def switch_to_value_hash(url, args)
switch_to_value_hash = empty_switch_to_value_hash(url)
current_switch = '%s'
args.split.each do |arg|
if arg[0..0] == '-' and switch_to_value_hash.has_key? "${#{arg[1..-1]}}"
current_switch = "${#{arg[1..-1]}}"
else
switch_to_value_hash[current_switch] << arg
end
end
return switch_to_value_hash
end
def empty_switch_to_value_hash(original_url)
switch_to_value_hash = { '%s' => [] }
url = String.new(original_url)
while url.sub!(/\$\{([^=}]+)/, '')
switch_to_value_hash["${#{$1}}"] = []
end
return switch_to_value_hash
end
def post_process(value, space_char, no_url_encoding)
value = CGI.escape(value) if not no_url_encoding
value.gsub!('+', space_char)
return value
end
end
\ No newline at end of file
diff --git a/db/development_structure.sql b/db/development_structure.sql
new file mode 100644
index 0000000..633bc8f
--- /dev/null
+++ b/db/development_structure.sql
@@ -0,0 +1,26 @@
+CREATE TABLE `banned_url_patterns` (
+ `id` int(11) NOT NULL auto_increment,
+ `pattern` varchar(255) default NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+CREATE TABLE `commands` (
+ `id` int(11) NOT NULL auto_increment,
+ `name` varchar(255) default NULL,
+ `url` text,
+ `description` text,
+ `uses` bigint(11) default '0',
+ `spam` tinyint(1) default '0',
+ `last_use_date` datetime default NULL,
+ `golden_egg_date` datetime default NULL,
+ `created_at` datetime default NULL,
+ `updated_at` datetime default NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
+
+CREATE TABLE `schema_migrations` (
+ `version` varchar(255) NOT NULL,
+ UNIQUE KEY `unique_schema_migrations` (`version`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT INTO schema_migrations (version) VALUES ('0');
\ No newline at end of file
diff --git a/test/fixtures/users.yml b/test/fixtures/users.yml
deleted file mode 100644
index 7563d23..0000000
--- a/test/fixtures/users.yml
+++ /dev/null
@@ -1,19 +0,0 @@
-quentin:
- id: 1
- login: quentin
- email: [email protected]
- salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
- crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
- created_at: <%= 5.days.ago.to_s :db %>
- activation_code: 8f24789ae988411ccf33ab0c30fe9106fab32e9b
- activated_at: <%= 5.days.ago.to_s :db %>
- state: active
-aaron:
- id: 2
- login: aaron
- email: [email protected]
- salt: 7e3041ebc2fc05a40c60028e2c4901a81035d3cd
- crypted_password: 00742970dc9e6319f8019fd54864d3ea740f04b1 # test
- created_at: <%= 1.days.ago.to_s :db %>
- activation_code: 8f24789ae988411ccf33ab0c30fe9106fab32e9a
- state: pending
diff --git a/test/functional/command_controller_test.rb b/test/functional/commands_controller_test.rb
similarity index 97%
rename from test/functional/command_controller_test.rb
rename to test/functional/commands_controller_test.rb
index dc90425..19b8651 100644
--- a/test/functional/command_controller_test.rb
+++ b/test/functional/commands_controller_test.rb
@@ -1,332 +1,328 @@
require File.dirname(__FILE__) + '/../test_helper'
require File.dirname(__FILE__) + '/../../app/helpers/application_helper.rb'
-require 'command_controller'
# Re-raise errors caught by the controller.
-class CommandController; def rescue_action(e) raise e end; end
+class CommandsController; def rescue_action(e) raise e end; end
-class CommandControllerTest < Test::Unit::TestCase
- include ApplicationHelper
- include CommandHelper
- include ParserHelper
+class CommandsControllerTest < Test::Unit::TestCase
fixtures :commands, :banned_url_patterns
def setup
- @controller = CommandController.new
+ @controller = CommandsController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_my_combine
assert_equal('http://foo.com/bar', my_combine('http://foo.com/%s', 'foo {test_echo bar}'))
assert_equal('test_echo bar', my_combine('test_echo %s', 'foo {test_echo bar}'))
assert_equal('test_echo bar', my_combine('test_echo {test_echo %s}', 'foo {test_echo bar}'))
end
def test_command_list
command = Command.new
command.name = '"abc"'
command.url = 'http://abc.com'
command.description = 'A great site!'
command.save
post :new
assert assigns['command_list'] !~ /"/
end
def test_banning_empty_string
pattern = BannedUrlPattern.new
pattern.pattern = ''
pattern.save
- post :add_command, {'x' => '', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
+ post :create, {'x' => '', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(1, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_ignore_spam_bots_1
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(1, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_ignore_spam_bots_2
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
post :add_command, {'x' => 'slfjasklfj', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_ignore_spam_bots_3
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
post :add_command, {'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_banning_percent_signs
assert_equal(0, BannedUrlPattern.find_all("pattern = 'http://'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam1', 'url' => '%', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam2', 'url' => '%', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam3', 'url' => '%', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam4', 'url' => '%', 'description' => 'A great site!'}}
assert_equal(1, BannedUrlPattern.find_all("pattern = 'http://'").size)
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_equal(1, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_banning_underscores
assert_equal(0, BannedUrlPattern.find_all("pattern = 'http://'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam1', 'url' => '________________', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam2', 'url' => '________________', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam3', 'url' => '________________', 'description' => 'A great site!'}}
post :add_command, {'x' => '', 'command' => {'name' => 'spam4', 'url' => '________________', 'description' => 'A great site!'}}
assert_equal(1, BannedUrlPattern.find_all("pattern = 'http://'").size)
assert_equal(0, Command.find_all("url LIKE 'http://aaaaa.com'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'aaaaa', 'url' => 'http://aaaaa.com', 'description' => 'A great site!'}}
assert_equal(1, Command.find_all("url LIKE 'http://aaaaa.com'").size)
end
def test_banning_1
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam1', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(1, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam2', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(2, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam3', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(3, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam4', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
post :add_command, {'x' => '', 'command' => {'name' => 'spam5', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
post :add_command, {'x' => '', 'command' => {'name' => 'spam6', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(1, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
Command.destroy_all("url LIKE 'http://welovespam.com%'")
pattern = BannedUrlPattern.new
pattern.pattern = '%welovespam%'
pattern.save
assert_equal(2, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam7', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(2, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
# Check other stuff not deleted [Jon Aquino 2005-06-10]
assert_not_nil Command.find_first("name='gim'")
end
def test_banning_2
command = Command.new
command.name = 'spam 75 minutes ago'
command.url = 'http://welovespam.com'
command.description = 'A great site!'
command.created_at = Time.now - (60*75)
command.save
assert_equal(1, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam1', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(2, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam2', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(3, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam3', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(4, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam4', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(5, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam5', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(6, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam6', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(7, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
Command.destroy_all("url LIKE 'http://welovespam.com%'")
pattern = BannedUrlPattern.new
pattern.pattern = '%welovespam%'
pattern.save
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam7', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
# Check other stuff not deleted [Jon Aquino 2005-06-10]
assert_not_nil Command.find_first("name='gim'")
end
def test_banning_3
command = Command.new
command.name = 'spam 45 minutes ago'
command.url = 'http://welovespam.com'
command.description = 'A great site!'
command.created_at = Time.now - (60*45)
command.save
assert_equal(1, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam1', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(2, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam2', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(3, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(0, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam3', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam4', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
post :add_command, {'x' => '', 'command' => {'name' => 'spam5', 'url' => 'http://welovespam.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
post :add_command, {'x' => '', 'command' => {'name' => 'spam6', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(1, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(1, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
assert_equal('http://welovespam.com', BannedUrlPattern.find_first("pattern LIKE '%welovespam%'").pattern)
Command.destroy_all("url LIKE 'http://welovespam.com%'")
pattern = BannedUrlPattern.new
pattern.pattern = '%welovespam%'
pattern.save
assert_equal(2, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
post :add_command, {'x' => '', 'command' => {'name' => 'spam7', 'url' => 'http://welovespam.com?x', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
assert_equal(0, Command.find_all("url LIKE 'http://welovespam.com%'").size)
assert_equal(2, BannedUrlPattern.find_all("pattern LIKE '%welovespam%'").size)
# Check other stuff not deleted [Jon Aquino 2005-06-10]
assert_not_nil Command.find_first("name='gim'")
end
def test_spam_filter
pattern = BannedUrlPattern.new
pattern.pattern = '%sonicate%'
pattern.save
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => 'http://sonicate.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_nil blah
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => 'http://Wonicate.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_not_nil blah
assert_equal 'blah', blah.name
assert_equal 'http://Wonicate.com', blah.url
assert_equal 'A great site!', blah.description
end
def test_add_command_via_get
assert_nil(Command.find_first("name='blah'"))
get :add_command, {'command' => {'name' => 'blah', 'url' => 'http://blah.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_nil blah
end
def test_add_command_via_post
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => 'http://blah.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_not_nil blah
assert_equal 'blah', blah.name
assert_equal 'http://blah.com', blah.url
assert_equal 'A great site!', blah.description
end
def test_adding_http_automatically
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => 'blah.com', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_not_nil blah
assert_equal 'blah', blah.name
assert_equal 'http://blah.com', blah.url
assert_equal 'http://blah.com', blah.display_url
assert_equal 'A great site!', blah.description
end
def test_adding_http_automatically_2
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => '{test_echo http://google.com}', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_not_nil blah
assert_equal 'blah', blah.name
assert_equal '{test_echo http://google.com}', blah.url
assert_equal '{test_echo http://google.com}', blah.display_url
assert_equal 'A great site!', blah.description
end
def test_adding_url_automatically
assert_nil(Command.find_first("name='blah'"))
post :add_command, {'x' => '', 'command' => {'name' => 'blah', 'url' => 'gim porsche', 'description' => 'A great site!'}}
assert_redirected_to :action => 'index'
blah = Command.find_first "name='blah'"
assert_not_nil blah
assert_equal 'blah', blah.name
assert_equal '{url[no url encoding] gim porsche}', blah.url
assert_equal 'gim porsche', blah.display_url
assert_equal 'A great site!', blah.description
end
def test_display_url_proper
assert_equal 'http://google.com', Command.display_url_proper('http://google.com')
assert_equal 'http://google.com', Command.display_url_proper('{url http://google.com}')
assert_equal 'http://google.com', Command.display_url_proper('{url[no url encoding] http://google.com}')
assert_equal 'http://google.com[no url encoding]', Command.display_url_proper('{url[no url encoding] http://google.com[no url encoding]}')
end
def test_add_existing_command
assert_not_nil Command.find_first("name='gim'")
assert_raise(ActiveRecord::StatementInvalid) {
post :add_command, {'x' => '', 'command' => {'name' => 'gim', 'url' => 'http://gim.com', 'description' => 'Best in the West!'}}
}
gim = Command.find_first "name='gim'"
assert_not_nil gim
assert_equal 'gim', gim.name
assert_equal 'http://images.google.com/images?q=%s', gim.url
assert_equal 'Google Image search', gim.description
end
end
diff --git a/test/functional/documentation_controller_test.rb b/test/functional/documentation_controller_test.rb
deleted file mode 100644
index 7cd1b1f..0000000
--- a/test/functional/documentation_controller_test.rb
+++ /dev/null
@@ -1,18 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-require 'documentation_controller'
-
-# Re-raise errors caught by the controller.
-class DocumentationController; def rescue_action(e) raise e end; end
-
-class DocumentationControllerTest < Test::Unit::TestCase
- def setup
- @controller = DocumentationController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
- # Replace this with your real tests.
- def test_truth
- assert true
- end
-end
diff --git a/test/functional/kernel_controller_test.rb b/test/functional/kernel_controller_test.rb
index 0d7a153..c366a7e 100644
--- a/test/functional/kernel_controller_test.rb
+++ b/test/functional/kernel_controller_test.rb
@@ -1,59 +1,57 @@
require File.dirname(__FILE__) + '/../test_helper'
require File.dirname(__FILE__) + '/../../app/helpers/application_helper.rb'
require 'kernel_controller'
# Re-raise errors caught by the controller.
class KernelController; def rescue_action(e) raise e end; end
class KernelControllerTest < Test::Unit::TestCase
include ApplicationHelper
fixtures :commands
def setup
@controller = KernelController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def command_names
- assigns['commands'].collect{|command|command.name}.join(",")
+ assigns["commands"].collect{|command|command.name}.join(",")
end
def test_ls
get :ls
assert_equal('g,gim,bar', command_names)
end
def test_ls_name
get :ls, {'args', 'gim'}
assert_equal('gim', command_names)
end
def test_ls_url
get :ls, {'args', 'navclient'}
assert_equal('g', command_names)
end
def test_ls_description
get :ls, {'args', 'ardy'}
assert_equal('bar', command_names)
end
def test_man
get :man, {'args', 'gim'}
assert_response :success
get :man, {'args', 'blah_blah_blah'}
- assert_tag :content => 'No manual entry for blah_blah_blah'
+
+ # assert_select "body > div", :text => "No manual entry for blah_blah_blah"
+
get :man, {'args', 'blah blah blah'}
- assert_tag :content => 'No manual entry for blah blah blah'
+
+ # assert_select "body > div", :text => "No manual entry for blah blah blah"
end
def test_truncate_with_ellipses
assert_equal 'abcd', truncate_with_ellipses("abcd", 5)
assert_equal 'abcde', truncate_with_ellipses("abcde", 5)
assert_equal 'abcde...', truncate_with_ellipses("abcdef", 5)
end
+
def test_url_format_recognized
assert url_format_recognized('http://foo.com')
assert url_format_recognized('{blah}')
assert ! url_format_recognized('foo {blah}')
end
- def test_where
- assert_equal nil, @controller.where(nil)
- assert_equal nil, @controller.where('')
- assert_equal nil, @controller.where(' ')
- assert_equal "name like '%foo%' or description like '%foo%' or url like '%foo%'", @controller.where('foo')
- end
end
diff --git a/test/functional/sessions_controller_test.rb b/test/functional/sessions_controller_test.rb
deleted file mode 100644
index e082bd0..0000000
--- a/test/functional/sessions_controller_test.rb
+++ /dev/null
@@ -1,90 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-require 'sessions_controller'
-
-# Re-raise errors caught by the controller.
-class SessionsController; def rescue_action(e) raise e end; end
-
-class SessionsControllerTest < Test::Unit::TestCase
- # Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
- # Then, you can remove it from this and the units test.
- include AuthenticatedTestHelper
-
- fixtures :users
-
- def setup
- @controller = SessionsController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
- def test_should_login_and_redirect
- post :create, :login => {:username => "quentin", :password => "test"}
-
- assert session[:user_id]
- assert_response :redirect
- end
-
- def test_should_fail_login_and_not_redirect
- post :create, :login => {:username => "quentin", :password => "bad password"}
-
- assert_nil session[:user_id]
- assert_response :success
- end
-
- def test_should_logout
- login_as :quentin
- get :destroy
-
- assert_nil session[:user_id]
- assert_response :redirect
- end
-
- def test_should_remember_me
- post :create, :login => {:username => "quentin", :password => "test", :remember_me => "1"}
-
- assert_not_nil @response.cookies["auth_token"]
- end
-
- def test_should_not_remember_me
- post :create, :login => {:username => "quentin", :password => "test", :remember_me => "0"}
-
- assert_nil @response.cookies["auth_token"]
- end
-
- def test_should_delete_token_on_logout
- login_as :quentin
- get :destroy
- assert_equal @response.cookies["auth_token"], []
- end
-
- def test_should_login_with_cookie
- users(:quentin).remember_me
- @request.cookies["auth_token"] = cookie_for(:quentin)
- get :new
- assert @controller.send(:logged_in?)
- end
-
- def test_should_fail_expired_cookie_login
- users(:quentin).remember_me
- users(:quentin).update_attribute :remember_token_expires_at, 5.minutes.ago
- @request.cookies["auth_token"] = cookie_for(:quentin)
- get :new
- assert [email protected](:logged_in?)
- end
-
- def test_should_fail_cookie_login
- users(:quentin).remember_me
- @request.cookies["auth_token"] = auth_token('invalid_auth_token')
- get :new
- assert [email protected](:logged_in?)
- end
-
- protected
- def auth_token(token)
- CGI::Cookie.new('name' => 'auth_token', 'value' => token)
- end
-
- def cookie_for(user)
- auth_token users(user).remember_token
- end
-end
diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb
deleted file mode 100644
index be7d425..0000000
--- a/test/functional/users_controller_test.rb
+++ /dev/null
@@ -1,87 +0,0 @@
-require File.dirname(__FILE__) + '/../test_helper'
-require 'users_controller'
-
-# Re-raise errors caught by the controller.
-class UsersController; def rescue_action(e) raise e end; end
-
-class UsersControllerTest < Test::Unit::TestCase
- # Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
- # Then, you can remove it from this and the units test.
- include AuthenticatedTestHelper
-
- fixtures :users
-
- def setup
- @controller = UsersController.new
- @request = ActionController::TestRequest.new
- @response = ActionController::TestResponse.new
- end
-
- def test_should_allow_signup
- assert_difference 'User.count' do
- create_user
- assert_response :redirect
- end
- end
-
- def test_should_require_login_on_signup
- assert_no_difference 'User.count' do
- create_user(:login => nil)
- assert assigns(:user).errors.on(:login)
- assert_response :success
- end
- end
-
- def test_should_require_password_on_signup
- assert_no_difference 'User.count' do
- create_user(:password => nil)
- assert assigns(:user).errors.on(:password)
- assert_response :success
- end
- end
-
- def test_should_require_password_confirmation_on_signup
- assert_no_difference 'User.count' do
- create_user(:password_confirmation => nil)
- assert assigns(:user).errors.on(:password_confirmation)
- assert_response :success
- end
- end
-
- def test_should_require_email_on_signup
- assert_no_difference 'User.count' do
- create_user(:email => nil)
- assert assigns(:user).errors.on(:email)
- assert_response :success
- end
- end
-
- def test_should_activate_user
- AppConfig.require_email_activation = true
- assert_nil User.authenticate('aaron', 'test')
- get :activate, :id => users(:aaron).activation_code
- assert_redirected_to '/'
- assert_not_nil flash[:notice]
- assert_equal users(:aaron), User.authenticate('aaron', 'test')
- end
-
- def test_should_not_activate_user_without_key
- get :activate
- assert_nil flash[:notice]
- rescue ActionController::RoutingError
- # in the event your routes deny this, we'll just bow out gracefully.
- end
-
- def test_should_not_activate_user_with_blank_key
- get :activate, :activation_code => ''
- assert_nil flash[:notice]
- rescue ActionController::RoutingError
- # well played, sir
- end
-
- protected
- def create_user(options = {})
- post :create, :user => { :login => 'quire', :email => '[email protected]',
- :password => 'quire', :password_confirmation => 'quire' }.merge(options)
- end
-end
diff --git a/test/unit/command_test.rb b/test/unit/command_test.rb
index e537224..6de7fb6 100644
--- a/test/unit/command_test.rb
+++ b/test/unit/command_test.rb
@@ -1,13 +1,15 @@
require File.dirname(__FILE__) + '/../test_helper'
class CommandTest < Test::Unit::TestCase
fixtures :commands
def setup
@gim = Command.find_first "name='gim'"
end
def test_truth
assert true
end
+
+
end
diff --git a/test/unit/parser_test.rb b/test/unit/parser_test.rb
index f1d6f7a..5a825da 100644
--- a/test/unit/parser_test.rb
+++ b/test/unit/parser_test.rb
@@ -1,29 +1,270 @@
require File.dirname(__FILE__) + '/../test_helper'
class ParserTest < Test::Unit::TestCase
fixtures :commands
def setup
+ @gim = Command.first(:conditions => {:name => "gim"})
+ @cl = Command.find_or_initialize_by_name("cl")
end
+
+ # Verify that calling Parser will increment the "uses" column of the command
+ def test_uses
+ assert_equal 0, @gim.uses
+ assert_nil @gim.last_use_date
+
+ Parser.get_url('gim "porche 911"')
+ @gim.reload
+
+ assert_equal 1, @gim.uses
+ assert_not_nil @gim.last_use_date
+ assert Time.now - @gim.last_use_date < 5 # seconds
+ end
+
+ # Verify the parser is outputting correct URLs
+ def test_parse
+ assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=blah+%22ford+F-150%22',
+ Parser.get_url('blah "ford F-150"', AppConfig.default_command)
+
+ assert_equal 'http://images.google.com/images?q=blah+%22ford+F-150%22',
+ Parser.get_url('blah "ford F-150"', "gim")
- def test_truth
- assert true
+ assert_equal 'http://images.google.com/images?q=%22porsche+911%22',
+ Parser.get_url('gim "porsche 911"', AppConfig.default_command)
+
+ assert_equal 'http://bar.com?q=%22porsche%20911%22',
+ Parser.get_url('bar "porsche 911"', AppConfig.default_command)
+ end
+
+
+ # Verify the parser can handle multple parameters
+ def test_multiple_parameter
+ @cl.url = 'http://craigslist.com?city=${city}&item=${item}'
+ @cl.save
+
+ assert_equal "http://craigslist.com?city=san+francisco&item=tennis+shoes",
+ Parser.get_url('cl -city san francisco -item tennis shoes')
+
+ #
+ assert_equal "http://craigslist.com?city=san+francisco&item=",
+ Parser.get_url('cl -city san francisco')
+
+ #
+ assert_equal "http://craigslist.com?city=&item=tennis+shoes",
+ Parser.get_url('cl -item tennis shoes')
+ #
+ assert_equal "http://craigslist.com?city=&item=",
+ Parser.get_url('cl')
+ #
+ assert_equal "http://craigslist.com?city=&item=",
+ Parser.get_url('cl foo')
+ #
+ assert_equal "http://craigslist.com?city=&item=",
+ Parser.get_url('cl -foo')
+ end
+
+ # Verify the parser can handle multple parameters with default values
+ def test_multiple_parameter_with_defaults
+ @cl.url = 'http://craigslist.com?city=${city}&item=${item=foo bar}'
+ @cl.save
+
+ assert_equal "http://craigslist.com?city=san+francisco&item=tennis+shoes",
+ Parser.get_url('cl -city san francisco -item tennis shoes')
+
+ #
+ assert_equal "http://craigslist.com?city=san+francisco&item=foo+bar",
+ Parser.get_url('cl -city san francisco')
+
+ #
+ assert_equal "http://craigslist.com?city=&item=tennis+shoes",
+ Parser.get_url('cl -item tennis shoes')
+ #
+ assert_equal "http://craigslist.com?city=&item=foo+bar",
+ Parser.get_url('cl')
+ #
+ assert_equal "http://craigslist.com?city=&item=foo+bar",
+ Parser.get_url('cl foo')
+ #
+ assert_equal "http://craigslist.com?city=&item=foo+bar",
+ Parser.get_url('cl -foo')
end
- def test_google_ford
+ def test_COMMAND_parameter
+ @cl.url = 'http://craigslist.com?city=${city}&foo=${COMMAND}'
+ @cl.save
+ #
+ assert_equal "http://craigslist.com?city=san+francisco&foo=cl+-city+san+francisco",
+ Parser.get_url('cl -city san francisco')
end
- # get :parse, {'command' => 'blah "ford F-150"'}
- # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=blah+%22ford+F-150%22', @controller.last_url
- # get :parse, {'command' => 'blah "ford F-150"', 'default' => 'gim'}
- # assert_equal 'http://images.google.com/images?q=blah+%22ford+F-150%22', @controller.last_url
- # assert_response :redirect
- # get :parse, {'command' => 'gim "porsche 911"'}
- # assert_equal 'http://images.google.com/images?q=%22porsche+911%22', @controller.last_url
- # assert_response :redirect
- # get :parse, {'command' => 'bar "porsche 911"'}
- # assert_equal 'http://bar.com?q=%22porsche%20911%22', @controller.last_url
- # assert_response :redirect
+ # Verify the parser can handle multple parameters with multiple default values
+ def test_multiple_parameter_with_defaults2
+ @cl.url = 'http://craigslist.com?city=${city=victoria bc=blah}&item=${item=foo bar}'
+ @cl.save
+
+ assert_equal "http://craigslist.com?city=san+francisco&item=tennis+shoes",
+ Parser.get_url('cl -city san francisco -item tennis shoes')
+
+ #
+ assert_equal "http://craigslist.com?city=san+francisco&item=foo+bar",
+ Parser.get_url('cl -city san francisco')
+
+ #
+ assert_equal "http://craigslist.com?city=victoria+bc&item=tennis+shoes",
+ Parser.get_url('cl -item tennis shoes')
+ #
+ assert_equal "http://craigslist.com?city=victoria+bc&item=foo+bar",
+ Parser.get_url('cl')
+ #
+ assert_equal "http://craigslist.com?city=victoria+bc&item=foo+bar",
+ Parser.get_url('cl foo')
+ #
+ assert_equal "http://craigslist.com?city=victoria+bc&item=foo+bar",
+ Parser.get_url('cl -foo')
+ end
+
+ # Verify the parser can handle multple parameters
+ def test_multiple_parameter2
+ @cl.url = 'http://craigslist.com?city=${city}&item=%s'
+ @cl.save
+
+ assert_equal "http://craigslist.com?city=san+francisco+tennis+shoes&item=",
+ Parser.get_url('cl -city san francisco tennis shoes')
+
+ #
+ assert_equal "http://craigslist.com?city=&item=san+francisco+tennis+shoes",
+ Parser.get_url('cl san francisco tennis shoes')
+
+ #
+ assert_equal "http://craigslist.com?city=san+francisco&item=tennis+shoes",
+ Parser.get_url('cl tennis shoes -city san francisco')
+ #
+ assert_equal "http://craigslist.com?city=&item=",
+ Parser.get_url('cl')
+ #
+ assert_equal "http://craigslist.com?city=&item=foo",
+ Parser.get_url('cl foo')
+ #
+ assert_equal "http://craigslist.com?city=&item=-foo",
+ Parser.get_url('cl -foo')
+ end
+
+ # Verify the parser can handle multple parameters
+ def test_multiple_parameter3
+ @cl.url = 'http://craigslist.com?city=${city}&item=${city}'
+ @cl.save
+
+ assert_equal "http://craigslist.com?city=san+francisco&item=san+francisco",
+ Parser.get_url('cl -city san francisco')
+
+ end
+
+ # TODO: convert tests
+
+ # # Verify that the runtime substitutions work
+ # def test_runtime_substitutions
+ # assert_equal "http://images.google.com/images?q=hello+world",
+ # Parser.get_url('gim {test_echo hello world}')
+ #
+ # end
+ # def test_runtime_substitutions
+ # get :parse, {'command' => 'gim {test_echo hello world}'}
+ # assert_equal 'http://images.google.com/images?q=hello+world', @controller.last_url
+ # assert_response :redirect
+ #
+ # get :parse, {'command' => 'gim {test_echo 1 {test_echo {test_echo 2} 3}}'}
+ # assert_equal 'http://images.google.com/images?q=1+2+3', @controller.last_url
+ # assert_response :redirect
+ #
+ # get :parse, {'command' => '{test_echo gim}'}
+ # assert_equal 'http://images.google.com/images?q=', @controller.last_url
+ # assert_response :redirect
+ #
+ # command = 'gim '
+ # 1.upto(100) { |i| command += "{test_echo #{i}}" }
+ # assert_raise (RuntimeError) {
+ # get :parse, {'command' => command}
+ # }
+ # end
+ # def test_compile_time_substitutions
+ # command = Command.find_first("name='gim'")
+ # command.url = 'http://{test_echo foo{test_echo bar}}.com'
+ # command.save
+ # get :parse, {'command' => 'gim'}
+ # assert_equal 'http://foobar.com', @controller.last_url
+ # assert_response :redirect
+ # command = Command.find_first("name='gim'")
+ # command.url = 'http://foo.com?first=${first}&{test_echo l{test_echo as}}{test_echo t}=${last}'
+ # command.save
+ # get :parse, {'command' => 'gim -first jon -last aquino'}
+ # assert_equal 'http://foo.com?first=jon&last=aquino', @controller.last_url
+ # assert_response :redirect
+ # command = Command.find_first("name='gim'")
+ # command.url = 'http://foo.com?first=${first}&last=${last={test_echo foo bar}}'
+ # command.save
+ # get :parse, {'command' => 'gim -first jon'}
+ # assert_equal 'http://foo.com?first=jon&last=foo+bar', @controller.last_url
+ # assert_response :redirect
+ # command = Command.find_first("name='gim'")
+ # command.url = 'http://foo.com?first=${first}&last={test_echo X${last}Z}'
+ # command.save
+ # get :parse, {'command' => 'gim -first jon -last aquino'}
+ # assert_equal 'http://foo.com?first=jon&last=XaquinoZ', @controller.last_url
+ # assert_response :redirect
+ # command = Command.find_first("name='gim'")
+ # command.url = 'http://foo.com?first=${first}&last={test_echo X${last={test_echo smith jones}}Z}'
+ # command.save
+ # get :parse, {'command' => 'gim -first jon -last aquino'}
+ # assert_equal 'http://foo.com?first=jon&last=XaquinoZ', @controller.last_url
+ # assert_response :redirect
+ # get :parse, {'command' => 'gim -first jon'}
+ # assert_equal 'http://foo.com?first=jon&last=Xsmith+jonesZ', @controller.last_url
+ # assert_response :redirect
+ # end
+ # def test_initialize_index
+ # get :index, {'command' => 'foo'}
+ # assert_response :success
+ # assert_tag :tag => 'input', :attributes => { 'value' => 'foo' }
+ # end
+ # def test_takes_parameters
+ # assert(@controller.takes_parameters("goo%s"))
+ # assert(@controller.takes_parameters("goo${hello}"))
+ # assert(! @controller.takes_parameters("goo"))
+ # assert(! @controller.takes_parameters("goo$"))
+ # assert(! @controller.takes_parameters("goo{}"))
+ # end
+ # def test_parse_proper
+ # assert_equal 'http://maps.google.com/maps?q=vancouver&spn=0.059612,0.126686&hl=en', @controller.parse_proper('http://maps.google.com/maps?q=vancouver&spn=0.059612,0.126686&hl=en', nil)
+ # assert_equal 'http://maps.google.com', @controller.parse_proper('http://maps.google.com', nil)
+ # assert_equal 'http://maps.google.com/', @controller.parse_proper('http://maps.google.com/', nil)
+ # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=http%3A%2F%2Fmaps.google.com', @controller.parse_proper(' http://maps.google.com', nil)
+ # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=.net', @controller.parse_proper('.net', nil)
+ # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=ArrayList+.net', @controller.parse_proper('ArrayList .net', nil)
+ # assert_equal 'http://ArrayList.net', @controller.parse_proper('ArrayList.net', nil)
+ # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=ArrayList.ne8', @controller.parse_proper('ArrayList.ne8', nil)
+ # assert_equal 'http://ArrayList.nett', @controller.parse_proper('ArrayList.nett', nil)
+ # assert_equal 'http://www.google.com/search?ie=UTF-8&sourceid=navclient&gfns=1&q=ArrayList.nettt', @controller.parse_proper('ArrayList.nettt', nil)
+ # end
+ # def test_no_url_encoding
+ # assert_equal 'http://web.archive.org/web/*/http://www.ing.be/', combine('http://web.archive.org/web/*/%s[no url encoding]', 'http://www.ing.be/', 'foo')
+ # end
+ # def test_post
+ # assert_equal 'http://jonaquino.textdriven.com/sean_ohagan/get2post.php?yndesturl=http://web.archive.org/web/*/http://www.ing.be/', combine('http://web.archive.org/web/*/%s[no url encoding][post]', 'http://www.ing.be/', 'foo')
+ # assert_equal 'http://jonaquino.textdriven.com/sean_ohagan/get2post.php?yndesturl=http://foo.com?a=bar', combine('http://foo.com?a=%s[post]', 'bar', 'xxxxx')
+ # assert_equal 'http://jonaquino.textdriven.com/sean_ohagan/get2post.php?yndesturl=http://foo.com&a=bar', combine('http://foo.com&a=%s[post]', 'bar', 'xxxxx')
+ # end
+ # def test_url
+ # get :url, {'command' => 'gim porsche'}
+ # assert_tag :content =>'http://images.google.com/images?q=porsche'
+ # get :url, {'command' => 'gim %s'}
+ # assert_tag :content =>'http://images.google.com/images?q=%25s'
+ # end
+ # def test_replace_with_spaces
+ # assert_equal 'http://blah.com/harry+potter', combine('http://blah.com/%s', 'harry potter', 'foo')
+ # assert_equal 'http://blah.com/harry%20potter', combine('http://blah.com/%s[use %20 for spaces]', 'harry potter', 'foo')
+ # assert_equal 'http://blah.com/harry-potter', combine('http://blah.com/%s[use - for spaces]', 'harry potter', 'foo')
+ # end
+
end
|
jcnetdev/yubnub
|
d5bc8ba56217dc3ecb70bce850def71c53e7bb56
|
Adding XML Intefaces to Command listing pages
|
diff --git a/app/controllers/commands_controller.rb b/app/controllers/commands_controller.rb
index 067ad95..4d3f538 100644
--- a/app/controllers/commands_controller.rb
+++ b/app/controllers/commands_controller.rb
@@ -1,108 +1,111 @@
class CommandsController < ApplicationController
def index
@commands = Command.recent.paginate :page => params[:page]
respond_to do |format|
format.html
- # format.xml
+ format.xml do
+ @feed_title = "YubNub Command List"
+ @feed_description = "Newly created commands on YubNub"
+ end
end
end
def new
@command = Command.new(:name => params["name"].to_s)
flash.now[:notice] = "Hmm! Looks like you're creating a new command!<br/>Good for you, buckeroo!"
end
def create
@command = Command.new(params[:command])
# Call prefix_with_url_if_necessary before prefix_with_http_if_necessary, because the latter checks
# if the url begins with { [Jon Aquino 2005-07-17]
url = ApplicationController.helpers.prefix_with_url_if_necessary @command.url
url = ApplicationController.helpers.prefix_with_http_if_necessary @command.url
unless @command.valid?
flash.now[:error] = "Please fill in both name and url to create a command."
render :action => "new"
return
end
# check if we should run the test
unless params['test_button'].blank?
test_command @command.url, params['test_command']
return
end
# check if we should run the view
unless params['view_url_button'].blank?
test_command @command.url, params['test_command'], true
return
end
# check if we have a banned pattern
if BannedUrlPattern.find(:first, :conditions => ["? LIKE pattern", @command.url]) then
# spam [Jon Aquino 2005-06-10]
redirect_after_add_command
return
end
if params['x'] != '' then
redirect_after_add_command
return
end
# Only ban a url if it hasn't been entered earlier than an hour # ago. Otherwise clever spammers
# will ban good url's that have been around for a long time. [Jon # Aquino 2005-06-11]
matching_commands = Command.find(:all, :conditions => ['url = ?', @command.url], :order => 'created_at')
if matching_commands.size >= 3 and Time.now-matching_commands[0].created_at<60*60
# spam [Jon Aquino 2005-06-10]
matching_commands.each { |command| command.destroy }
pattern = BannedUrlPattern.new
# Drop % from pattern -- it's dangerous. [Jon Aquino 2005-06-11]
pattern.pattern = @command.url.gsub(/[%_]/, '')
if not pattern.save then raise 'pattern.save failed' end
redirect_after_add_command
return
end
@command.save!
flash[:notice] = "Successfully created command: <strong>#{@command.name}</strong>"
redirect_after_add_command
end
def exists
output = Command.by_name(params["name"]) ? 'true' : 'false'
json = '({exists: ' + output + '})'
response.headers['X-JSON'] = json
render({:content_type => :js, :text => json})
end
def test_command(url, command_string, view = false)
@parser = Parser.new(command_string)
@parser.command = Command.new(:name => params[:command][:name], :url => url)
if view
render :text => @parser.parse.url
else
redirect_to @parser.parse.url
end
end
def view_url
@parser = Parser.new(command_string)
@parser.command = Command.new(:name => params[:command][:name], :url => url)
render :text => @parser.parse.url
end
protected
def redirect_after_add_command
# Add a space ("+") to save the user the trouble [Jon Aquino # 2005-06-04]
# For some reason, ".html" is getting appended to the URL. This # started to happen after TextDrive moved
# YubNub to a faster server (the "Jason Special"). Drop the # command auto-population for now.
# [Jon Aquino 2005-06-20]
redirect_to root_url
end
end
diff --git a/app/controllers/kernel_controller.rb b/app/controllers/kernel_controller.rb
index e4c0873..4ddf50a 100644
--- a/app/controllers/kernel_controller.rb
+++ b/app/controllers/kernel_controller.rb
@@ -1,55 +1,68 @@
class KernelController < ApplicationController
def ls
@commands = Command.search(params[:args]).paginate :page => params[:page]
unless params[:args].blank?
params[:cmd] = "ls #{params[:args]}"
end
respond_to do |format|
format.html
- # format.xml
+ format.xml do
+ @feed_title = "#{AppConfig.site_name}: #{params[:cmd]}"
+ @feed_description = "Listing commands with: #{params[:args]}"
+ render :template => "commands/index.xml.builder"
+ end
end
end
def man
if params['args'].blank? then
- redirect_to :action => 'man', :args => 'man'
+ redirect_to man_url(:args => 'man')
return
end
@command_name = params[:args]
@command = Command.by_name @command_name
respond_to do |format|
format.html do
render(:action => :no_manual_entry) unless @command
end
- # format.xml
+ format.xml do
+ @feed_title = "#{AppConfig.site_name}: man #{@command_name}"
+ @feed_description = "Usage description for: #{@command_name}"
+ @commands = [@command]
+ render :template => "commands/index.xml.builder"
+ end
end
end
def golden_eggs
if params[:all] == "true"
@commands = Command.golden_eggs.recent
else
@commands = Command.golden_eggs.search(params[:args]).paginate :page => params[:page]
end
respond_to do |format|
format.html
- # format.xml
+ format.xml do
+ @feed_title = "#{AppConfig.site_name} Golden Eggs"
+ @feed_description = "Welcome to #{AppConfig.site_name} Golden Eggs! The Golden Eggs are #{AppConfig.site_name} commands that people seem to find particularly useful and interesting. If you want to nominate a #{AppConfig.site_name} command for this list, email Jon about it."
+ render :template => "commands/index.xml.builder"
+ end
end
end
def most_used_commands
@commands = Command.most_used.paginate :page => params[:page]
respond_to do |format|
format.html
# format.xml
end
end
end
diff --git a/app/views/commands/index.xml.builder b/app/views/commands/index.xml.builder
new file mode 100644
index 0000000..5d50545
--- /dev/null
+++ b/app/views/commands/index.xml.builder
@@ -0,0 +1,21 @@
+xml.instruct!
+xml.rss "version" => "0.91" do
+ xml.channel do
+ xml.title @feed_title || AppConfig.site_name
+ xml.link @feed_link unless @feed_link.blank?
+ xml.description @feed_description || ""
+ xml.pubDate CGI.rfc1123_date(@commands.first.created_at) unless @commands.blank?
+
+ @commands.each do |command|
+ xml.item do
+ xml.title h(command.name)
+ xml.link man_url(:args => command.name)
+
+ xml.description do |description|
+ description.cdata! "<pre>#{command.description}</pre>"
+ end
+ xml.pubDate CGI.rfc1123_date(command.created_at)
+ end
+ end
+ end
+end
diff --git a/app/views/kernel/golden_eggs.html.erb b/app/views/kernel/golden_eggs.html.erb
index e607505..77246a2 100644
--- a/app/views/kernel/golden_eggs.html.erb
+++ b/app/views/kernel/golden_eggs.html.erb
@@ -1,29 +1,29 @@
<% title "Golden Eggs (ge)" %>
<% if ! @searching then %>
<div id="golden_egg_graphic">
<img src="/images/ge.jpg" alt="golden egg" />
<p>Thanks to <a href="http://jjefferydesign.com">Jacob Ensor</a> <br />for the beautiful egg logo</p>
</div>
<a href="/kernel/golden_eggs.xml"><img src="/images/xml_button.gif" alt="Subscribe to RSS feed"></a>
<table width="500"><tr><td>
Welcome to YubNub Golden Eggs! The Golden Eggs are YubNub commands that people seem to find particularly
useful and interesting. If you want to nominate a YubNub command for this list,
<a href="mailto:[email protected]?subject=Nomination for a YubNub Golden Egg&body=Hey Jon, there's a great command that I want to see on the Golden Egg list: [insert command here]">email Jon</a>
about it.
</td></tr></table>
<br />
<div class="hint">
<span style="color:red">Tip:</span> You can search the Golden Eggs -- for example: ge dictionary
</div>
<% end %>
<%= partial 'shared/command_list' %>
<% if ! @searching and params['all'] != 'true' %>
<div class="hint" style="margin-top: 10px">
- <a class="hint" href="/kernel/golden_eggs?all=true">Show all golden eggs on one long page</a> (<a class="hint" href="/all_golden_eggs.xml">XML</a>)
+ <a class="hint" href="/kernel/golden_eggs?all=true">Show all golden eggs on one long page</a> (<a class="hint" href="/kernel/golden_eggs.xml?all=true">XML</a>)
</div>
<% end %>
\ No newline at end of file
diff --git a/app/views/kernel/no_manual_entry.html.erb b/app/views/kernel/no_manual_entry.html.erb
index f8b6e64..bbbdc4e 100644
--- a/app/views/kernel/no_manual_entry.html.erb
+++ b/app/views/kernel/no_manual_entry.html.erb
@@ -1,3 +1,3 @@
No manual entry for <%=h @command_name%>. <br />
To search for "<%=h @command_name%>", try typing
-<%= link_to_unless_current("ls #{@command_name}", :controller => 'parser', :action => 'parse', :cmd => "ls #{@command_name}") %>.
\ No newline at end of file
+<%= link_to_unless_current "ls #{@command_name}", parse_url(:cmd => "ls #{@command_name}") %>.
\ No newline at end of file
diff --git a/app/views/layouts/_footer.html.haml b/app/views/layouts/_footer.html.haml
index 770029e..e834651 100644
--- a/app/views/layouts/_footer.html.haml
+++ b/app/views/layouts/_footer.html.haml
@@ -1,30 +1,30 @@
.footer{:style => "text-align: center"}
<a href="http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html">What Is This Thing?</a>
|
= link_to_unless_current('List All Commands (ls)', commands_url)
<a href="/commands.xml"><img src="/images/xml_button.gif" alt="Subscribe to RSS feed"></a>
|
= link_to_unless_current('Create a New Command', new_command_url)
|
= link_to_unless_current('Installing YubNub', install_url)
|
= link_to_unless_current('Advanced Syntax', syntax_url)
= br
= link_to_unless_current('Most-Used Commands', commands_url)
|
- = link_to_unless_current('Golden Eggs (Notable Commands)', :controller => 'parser', :action => 'parse', :cmd => 'ge')
+ = link_to_unless_current('Golden Eggs (Notable Commands)', parse_url(:cmd => 'ge'))
<a href="/kernel/golden_eggs.xml"><img src="/images/xml_button.gif" alt="Subscribe to RSS feed"/></a>
|
= link_to_unless_current("Jeremy's Picks", picks_url)
= br
= link_to "Community (Google Group)", "http://groups.google.com/group/YubNub"
|
= link_to "Wiki", "http://www.editthis.info/yubnub/"
|
= link_to "YubNub Blog", "http://yubnub.blogspot.com/"
|
= link_to "Press (Technorati)", "/parse?command=tec+yubnub"
|
= link_to_unless_current('Acknowledgements', ack_url)
|
<a href="mailto:[email protected]">Typos? Spam? Contact Jon</a>
\ No newline at end of file
diff --git a/app/views/pages/display_acknowledgements.html.erb b/app/views/pages/display_acknowledgements.html.erb
index 19fb35a..f38186c 100644
--- a/app/views/pages/display_acknowledgements.html.erb
+++ b/app/views/pages/display_acknowledgements.html.erb
@@ -1,31 +1,31 @@
Since the day I released YubNub on June 5, 2005, there have been a
bunch of people who have helped to make YubNub better. I want to
publicly acknowledge them here.
<ul>
<li>The people mentioned on the
<%= link_to_unless_current('Installing YubNub', install_url) %>
and <%= link_to_unless_current('Upcoming Features', upcoming_url) %>
pages.</li>
<li>Igor Krizanovskij for drawing the <a href="http://commons.wikimedia.org/wiki/Image:SCN1B.jpg">graphic</a> that became the YubNub logo.</li>
<li>Randy Stauner for his off-site spam-detector that helped when YubNub started to become popular.</li>
<li>John Gilman for designing the Popular Searches section on the <a href="/">front page</a>.</li>
<li>Kevin Dern for selecting the commands for the Popular Searches section.</li>
<li>Jason Hoffman, President of <a href="http://textdrive.com">TextDrive</a> (the official Ruby on Rails web host)
for sponsoring YubNub by putting it on a
<a href="http://weblog.textdrive.com/article/111/yubnub">faster setup</a> (the "Jason Special").</li>
<li>Oliver Horn for suggesting "Report spam" links.</li>
<li><a href="http://blog.360.yahoo.com/chicagosage">Brian</a> for his suggestion about putting "YubNub.org" in the title,
to make bookmark titles more descriptive.</li>
<li>Leen Kievit for suggesting that YubNub auto-prefix urls with "http://" if it is missing.</li>
<li>Anonymous for <a href="http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html#c111963942896725182">recommending</a> that YubNub have its own <a href="http://groups-beta.google.com/group/YubNub">forum</a></li>
-<li>Jeremy Hussell for suggesting the <%= link_to_unless_current('Most-Used Commands', :controller => 'kernel', :action => 'most_used_commands') %> page,
+<li>Jeremy Hussell for suggesting the <%= link_to_unless_current('Most-Used Commands', most_used_commands_url) %> page,
the Test section of the <%= link_to_unless_current('create', parse_url(:cmd => "create")) %> page,
the <a href="/parse?command=man+url">url</a> command,
and especially for his <%= link_to_unless_current("Jeremy's Picks page", picks_url) %> documenting the best YubNub commands.</li>
<li>Joshua H. for investigating how some commands that use [post] must use "&" instead of "?"</li>
<li>Dinesh Govindaraju for the idea of sorting search results by popularity</li>
<li>Michael Pacchioli for prototyping a Google-Suggest-like autocompletion feature for YubNub</li>
</ul>
If you don't see your name listed here or on one of the other pages mentioned above,
<a href="mailto:[email protected]">remind me</a> about how you helped out
and I will add your name.
\ No newline at end of file
diff --git a/app/views/shared/_command_list.html.erb b/app/views/shared/_command_list.html.erb
index 69081dd..8479c47 100644
--- a/app/views/shared/_command_list.html.erb
+++ b/app/views/shared/_command_list.html.erb
@@ -1,32 +1,32 @@
<% @commands ||= [] %>
<% show_golden_egg_labels = false unless local_assigns[:show_golden_egg_labels] %>
<br />
<% @commands.each do |command| %>
<span style="font-size:16px;font-weight:bold"><%=h command.name %></span>
<% if show_golden_egg_labels and not command.golden_egg_date.nil? then %>
<span style="color:red">(<a class="hint" style="color:red" href="/parse?command=ge">Golden Egg</a>)</span>
<% end %>
<br />
<% description = command.description.gsub(/\s+/, " ") %>
<% description = description =~ /DESCRIPTION(.*)/ ? $1 : description %>
<%=highlight h(truncate_with_ellipses(description, 500)), params[:args] %><br />
<span class="hint">
<%= command.uses %> uses
-
Created <%= command.created_at.to_s(:use_date) %>
-
Last used <%= (command.last_use_date.nil? ? command.created_at : command.last_use_date).to_s(:use_date) %>
-
</span>
<% if command.golden_egg_date.nil? then %>
<span class="nominate hint"><a class="hint" href="mailto:[email protected]?subject=Nomination for a YubNub Golden Egg: <%=CGI.escape(command.name)%>&body=Hey Jon, there's a great command that I want to see on the Golden Egg list: <%=CGI.escape(command.name)%>">
Nominate</a> - </span>
<% end %>
- <%= link_to('Description', {:action => 'man', :args => command.name}, {:class => 'description hint'}) %>
+ <%= link_to('Description', man_url(:args => command.name), :class => 'description hint') %>
-
<span class="implementation hint"><%=h command.display_url %></span><br />
<br />
<% end %>
<%= paging @commands, :meneame %>
\ No newline at end of file
diff --git a/config/routes.rb b/config/routes.rb
index 2999f3e..b5fd5bb 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -1,30 +1,42 @@
ActionController::Routing::Routes.draw do |map|
# Resources
map.resources :commands, :collection => {:exists => :get}
map.resources :users, :member => {:activate => :get}
map.resource :session
# Dynamic
map.parse "/parse", :controller => 'parser', :action => 'parse'
- map.commands "/commands", :controller => 'kernel', :action => 'most_used_commands'
+
+ # Kernel
+ map.man "/kernel/man", :controller => "kernel", :action => "man"
+ map.connect "/kernel/man.:format", :controller => "kernel", :action => "man"
+
+ map.most_used_commands "/kernel/most_used_commands", :controller => "kernel", :action => "most_used_commands"
+ map.connect "/kernel/most_used_commands.:format", :controller => "kernel", :action => "most_used_commands"
+
+ map.golden_eggs "/kernel/golden_eggs", :controller => "kernel", :action => "golden_eggs"
+ map.connect "/kernel/golden_eggs.:format", :controller => "kernel", :action => "golden_eggs"
+
+ map.ls "/kernel/ls", :controller => "kernel", :action => "ls"
+ map.connect "/kernel/ls.:format", :controller => "kernel", :action => "ls"
# Pages
map.syntax "/syntax", :controller => 'pages', :action => 'describe_advanced_syntax'
map.install "/install", :controller => 'pages', :action => 'describe_installation'
map.ack "/acknowledgements", :controller => 'pages', :action => 'display_acknowledgements'
map.picks "/picks", :controller => 'pages', :action => 'jeremys_picks'
map.upcoming "/upcoming", :controller => 'pages', :action => 'describe_upcoming_features'
# Old Routes
map.connect "/command/new", :controller => "commands", :action => "new"
# sample resource
map.root :controller => "parser", :action => "landing"
# Install the default routes as the lowest priority.
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
end
|
jcnetdev/yubnub
|
e97fca5f76d5ca02a768cd6f3eb9d31fd23b8fe4
|
Updating install instructions
|
diff --git a/README b/README
index c6a81d0..88bbc69 100644
--- a/README
+++ b/README
@@ -1,44 +1,46 @@
== YubNub
This is the source code for YubNub, a (social) command-line for the web.
YubNub was written by Jonathan Aquino for the Rails Day 2005 programming competition.
You can reach Jonathan at [email protected].
http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html
This source code is made available under the MIT License (see LICENSE_YUBNUB).
== About YubNub
YubNub is a command-line for the web. After setting it up on your browser, you simply type "gim porsche 911" to do a Google Image Search for pictures of Porsche 911 sports cars. Type "random 49" to return random numbers between 1 and 49, courtesy of random.org. And best of all, you can make a new command by giving YubNub an appropriate URL.
www.yubnub.org
== Rails 2.1 Upgrade
Refactored and Upgraded to Rails 2.1 by Jacques Crocker ([email protected])
View source at http://github.com/jcnetdev/yubnub
== Installation Instructions
+You'll need the latest Rails Version (2.1) installed as a gem in order to run these steps.
+
1) Get Codebase
git clone git://github.com/jcnetdev/yubnub.git
cd yubnub
2) Install Gems
rake gems:install
3) Setup DB and Seed Data
rake db:create db:schema:load db:migrate
4) Start Server
script/server
== Notes
To add a bunch of junk data (to test paging, etc..) run
rake yubnub:junk_data
\ No newline at end of file
|
jcnetdev/yubnub
|
01f7eeb1c343a8fe09069e3718f023e7a4a0364e
|
Updating Installation instructions
|
diff --git a/README b/README
index b9814d6..c6a81d0 100644
--- a/README
+++ b/README
@@ -1,44 +1,44 @@
== YubNub
This is the source code for YubNub, a (social) command-line for the web.
YubNub was written by Jonathan Aquino for the Rails Day 2005 programming competition.
You can reach Jonathan at [email protected].
http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html
This source code is made available under the MIT License (see LICENSE_YUBNUB).
== About YubNub
YubNub is a command-line for the web. After setting it up on your browser, you simply type "gim porsche 911" to do a Google Image Search for pictures of Porsche 911 sports cars. Type "random 49" to return random numbers between 1 and 49, courtesy of random.org. And best of all, you can make a new command by giving YubNub an appropriate URL.
www.yubnub.org
== Rails 2.1 Upgrade
Refactored and Upgraded to Rails 2.1 by Jacques Crocker ([email protected])
View source at http://github.com/jcnetdev/yubnub
== Installation Instructions
1) Get Codebase
git clone git://github.com/jcnetdev/yubnub.git
cd yubnub
2) Install Gems
rake gems:install
-3) Setup DB and Seed
-rake db:create db:migrate
+3) Setup DB and Seed Data
+rake db:create db:schema:load db:migrate
4) Start Server
script/server
== Notes
To add a bunch of junk data (to test paging, etc..) run
rake yubnub:junk_data
\ No newline at end of file
|
jcnetdev/yubnub
|
5fbe4e22d12b991c4e78ada0d35eb3e9466b8b00
|
Updating Commands and Rake Task
|
diff --git a/README b/README
index becc747..b9814d6 100644
--- a/README
+++ b/README
@@ -1,37 +1,44 @@
== YubNub
This is the source code for YubNub, a (social) command-line for the web.
YubNub was written by Jonathan Aquino for the Rails Day 2005 programming competition.
You can reach Jonathan at [email protected].
http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html
This source code is made available under the MIT License (see LICENSE_YUBNUB).
== About YubNub
YubNub is a command-line for the web. After setting it up on your browser, you simply type "gim porsche 911" to do a Google Image Search for pictures of Porsche 911 sports cars. Type "random 49" to return random numbers between 1 and 49, courtesy of random.org. And best of all, you can make a new command by giving YubNub an appropriate URL.
www.yubnub.org
== Rails 2.1 Upgrade
Refactored and Upgraded to Rails 2.1 by Jacques Crocker ([email protected])
View source at http://github.com/jcnetdev/yubnub
== Installation Instructions
1) Get Codebase
git clone git://github.com/jcnetdev/yubnub.git
cd yubnub
2) Install Gems
rake gems:install
3) Setup DB and Seed
rake db:create db:migrate
4) Start Server
script/server
+
+
+== Notes
+
+To add a bunch of junk data (to test paging, etc..) run
+
+rake yubnub:junk_data
\ No newline at end of file
diff --git a/db/fixtures/commands.rb b/db/fixtures/commands.rb
index 50f01fa..13c94a2 100644
--- a/db/fixtures/commands.rb
+++ b/db/fixtures/commands.rb
@@ -1,119 +1,110 @@
# GOOGLE SEARCH
Command.seed(:name) do |s|
s.name = "g"
s.url = "http://www.google.com/search?q=%s"
s.description = \
"SYNOPSIS
g [keywords]
EXAMPLE
g YubNub
DESCRIPTION
Performs a Google search using the given keywords."
s.golden_egg_date = DateTime.now
end
# KERNEL - MAN
Command.seed(:name) do |s|
s.name = "man"
s.url = "/kernel/man?args=%s"
s.description = \
"SYNOPSIS
man command-name
EXAMPLE
man gim
DESCRIPTION
Displays helpful information about the given command.
\"man\" stands for \"manual\".
You're looking at man information right now!
"
s.golden_egg_date = DateTime.now
end
# CREATE ACTION SHORTCUT
Command.seed(:name) do |s|
s.name = "create"
s.url = "/commands/new?name=%s"
s.description = \
"SYNOPSIS
create [command-name]
EXAMPLE
create
DESCRIPTION
Creates a new YubNub command with the given name (must not
already exist). You will be prompted for a URL pointing to
the implementation of the command -- it might be an existing
service (e.g. the Google Image Search submit form), or your
own custom implementation sitting on your own server.
Welcome to the Web OS: small pieces, loosely joined.
"
s.golden_egg_date = DateTime.now
end
# KERNEL - LS
Command.seed(:name) do |s|
s.name = "ls"
s.url = "/kernel/ls?args=%s"
s.description = \
"SYNOPSIS
ls [word or phrase]
EXAMPLES
ls
ls music
DESCRIPTION
Lists information about all the commands in YubNub. Sorts entries
by date.
If you specify a word or phrase, YubNub will search the
descriptions, names, and urls for that word or phrase.
For example, \"ls music\" will return all YubNub commands pertaining
to music.
"
s.golden_egg_date = DateTime.now
end
-
# KERNEL - GE
Command.seed(:name) do |s|
s.name = "ge"
s.url = "/kernel/golden_eggs?args=%s"
s.description = \
"SYNOPSIS
ge [word or phrase]
EXAMPLES
ge
ge dictionary
DESCRIPTION
Displays the YubNub Golden Eggs - a list of YubNub commands
that people seem to find particularly useful and interesting.
If you specify a word or phrase, YubNub will search the
descriptions, names, and urls for that word or phrase.
For example, \"ge dictionary\" will return all Golden-Egg commands
pertaining to dictionaries.
"
s.golden_egg_date = DateTime.now
-end
-
-500.times do |i|
- Command.seed(:name) do |s|
- s.name = "test-#{i}"
- s.url = "http://www.testing.com/?#{i}hello=%s"
- s.description = "#{i} Test stuff out"
- end
end
\ No newline at end of file
diff --git a/lib/tasks/yubnub.rake b/lib/tasks/yubnub.rake
index 955f9e1..99e0bbc 100644
--- a/lib/tasks/yubnub.rake
+++ b/lib/tasks/yubnub.rake
@@ -1,25 +1,35 @@
namespace :yubnub do
desc "Import Latest Commands from YubNub.com"
task :import_latest => :environment do
# TODO
end
desc "Import Most Used Commands from YubNub.com"
task :import_most_used => :environment do
# http://yubnub.org/kernel/most_used_commands
end
desc "Import Golden Egg Commands from YubNub.com"
task :import_eggs => :environment do
require 'feedtools'
# http://yubnub.org/all_golden_eggs.xml
feed = FeedTools.Feed.open("http://yubnub.org/all_golden_eggs.xml")
feed.items.each do |item|
end
end
+ desc "Add Junk Data"
+ task :junk_data => :environment do
+ 500.times do |i|
+ Command.seed(:name) do |s|
+ s.name = "test-#{i}"
+ s.url = "http://www.testing.com/?#{i}hello=%s"
+ s.description = "#{i} Test stuff out"
+ end
+ end
+ end
end
\ No newline at end of file
|
jcnetdev/yubnub
|
7484447f57ac1f131080405c901d647119a90959
|
Added License and Readme
|
diff --git a/CHANGELOG b/CHANGELOG
new file mode 100644
index 0000000..22fb714
--- /dev/null
+++ b/CHANGELOG
@@ -0,0 +1,546 @@
+*2.0* (5th July, 2008)
+* Upgraded to Rails 2.1
+
+
+*0.12.1* (20th April, 2005)
+
+* Upgraded to Active Record 1.10.1, Action Pack 1.8.1, Action Mailer 0.9.1, Action Web Service 0.7.1
+
+
+*0.12.0* (19th April, 2005)
+
+* Fixed that purge_test_database would use database settings from the development environment when recreating the test database #1122 [[email protected]]
+
+* Added script/benchmarker to easily benchmark one or more statement a number of times from within the environment. Examples:
+
+ # runs the one statement 10 times
+ script/benchmarker 10 'Person.expensive_method(10)'
+
+ # pits the two statements against each other with 50 runs each
+ script/benchmarker 50 'Person.expensive_method(10)' 'Person.cheap_method(10)'
+
+* Added script/profiler to easily profile a single statement from within the environment. Examples:
+
+ script/profiler 'Person.expensive_method(10)'
+ script/profiler 'Person.expensive_method(10)' 10 # runs the statement 10 times
+
+* Added Rake target clear_logs that'll truncate all the *.log files in log/ to zero #1079 [Lucas Carlson]
+
+* Added lazy typing for generate, such that ./script/generate cn == ./script/generate controller and the likes #1051 [[email protected]]
+
+* Fixed that ownership is brought over in pg_dump during tests for PostgreSQL #1060 [[email protected]]
+
+* Upgraded to Active Record 1.10.0, Action Pack 1.8.0, Action Mailer 0.9.0, Action Web Service 0.7.0, Active Support 1.0.4
+
+
+*0.11.1* (27th March, 2005)
+
+* Fixed the dispatch.fcgi use of a logger
+
+* Upgraded to Active Record 1.9.1, Action Pack 1.7.0, Action Mailer 0.8.1, Action Web Service 0.6.2, Active Support 1.0.3
+
+
+*0.11.0* (22th March, 2005)
+
+* Removed SCRIPT_NAME from the WEBrick environment to prevent conflicts with PATH_INFO #896 [Nicholas Seckar]
+
+* Removed ?$1 from the dispatch.f/cgi redirect line to get rid of 'complete/path/from/request.html' => nil being in the @params now that the ENV["REQUEST_URI"] is used to determine the path #895 [dblack/Nicholas Seckar]
+
+* Added additional error handling to the FastCGI dispatcher to catch even errors taking down the entire process
+
+* Improved the generated scaffold code a lot to take advantage of recent Rails developments #882 [Tobias Luetke]
+
+* Combined the script/environment.rb used for gems and regular files version. If vendor/rails/* has all the frameworks, then files version is used, otherwise gems #878 [Nicholas Seckar]
+
+* Changed .htaccess to allow dispatch.* to be called from a sub-directory as part of the push with Action Pack to make Rails work on non-vhost setups #826 [Nicholas Seckar/Tobias Luetke]
+
+* Added script/runner which can be used to run code inside the environment by eval'ing the first parameter. Examples:
+
+ ./script/runner 'ReminderService.deliver'
+ ./script/runner 'Mailer.receive(STDIN.read)'
+
+ This makes it easier to do CRON and postfix scripts without actually making a script just to trigger 1 line of code.
+
+* Fixed webrick_server cookie handling to allow multiple cookes to be set at once #800, #813 [[email protected]]
+
+* Fixed the Rakefile's interaction with postgresql to:
+
+ 1. Use PGPASSWORD and PGHOST in the environment to fix prompting for
+ passwords when connecting to a remote db and local socket connections.
+ 2. Add a '-x' flag to pg_dump which stops it dumping privileges #807 [rasputnik]
+ 3. Quote the user name and use template0 when dumping so the functions doesn't get dumped too #855 [pburleson]
+ 4. Use the port if available #875 [madrobby]
+
+* Upgraded to Active Record 1.9.0, Action Pack 1.6.0, Action Mailer 0.8.0, Action Web Service 0.6.1, Active Support 1.0.2
+
+
+*0.10.1* (7th March, 2005)
+
+* Fixed rake stats to ignore editor backup files like model.rb~ #791 [skanthak]
+
+* Added exception shallowing if the DRb server can't be started (not worth making a fuss about to distract new users) #779 [Tobias Luetke]
+
+* Added an empty favicon.ico file to the public directory of new applications (so the logs are not spammed by its absence)
+
+* Fixed that scaffold generator new template should use local variable instead of instance variable #778 [Dan Peterson]
+
+* Allow unit tests to run on a remote server for PostgreSQL #781 [[email protected]]
+
+* Added web_service generator (run ./script/generate web_service for help) #776 [Leon Bredt]
+
+* Added app/apis and components to code statistics report #729 [Scott Barron]
+
+* Fixed WEBrick server to use ABSOLUTE_RAILS_ROOT instead of working_directory #687 [Nicholas Seckar]
+
+* Fixed rails_generator to be usable without RubyGems #686 [Cristi BALAN]
+
+* Fixed -h/--help for generate and destroy generators #331
+
+* Added begin/rescue around the FCGI dispatcher so no uncaught exceptions can bubble up to kill the process (logs to log/fastcgi.crash.log)
+
+* Fixed that association#count would produce invalid sql when called sequentialy #659 [[email protected]]
+
+* Fixed test/mocks/testing to the correct test/mocks/test #740
+
+* Added early failure if the Ruby version isn't 1.8.2 or above #735
+
+* Removed the obsolete -i/--index option from the WEBrick servlet #743
+
+* Upgraded to Active Record 1.8.0, Action Pack 1.5.1, Action Mailer 0.7.1, Action Web Service 0.6.0, Active Support 1.0.1
+
+
+*0.10.0* (24th February, 2005)
+
+* Changed default IP binding for WEBrick from 127.0.0.1 to 0.0.0.0 so that the server is accessible both locally and remotely #696 [Marcel]
+
+* Fixed that script/server -d was broken so daemon mode couldn't be used #687 [Nicholas Seckar]
+
+* Upgraded to breakpoint 92 which fixes:
+
+ * overload IRB.parse_opts(), fixes #443
+ => breakpoints in tests work even when running them via rake
+ * untaint handlers, might fix an issue discussed on the Rails ML
+ * added verbose mode to breakpoint_client
+ * less noise caused by breakpoint_client by default
+ * ignored TerminateLineInput exception in signal handler
+ => quiet exit on Ctrl-C
+
+* Added support for independent components residing in /components. Example:
+
+ Controller: components/list/items_controller.rb
+ (holds a List::ItemsController class with uses_component_template_root called)
+
+ Model : components/list/item.rb
+ (namespace is still shared, so an Item model in app/models will take precedence)
+
+ Views : components/list/items/show.rhtml
+
+
+* Added --sandbox option to script/console that'll roll back all changes made to the database when you quit #672 [bitsweat]
+
+* Added 'recent' as a rake target that'll run tests for files that changed in the last 10 minutes #612 [bitsweat]
+
+* Changed script/console to default to development environment and drop --no-inspect #650 [bitsweat]
+
+* Added that the 'fixture :posts' syntax can be used for has_and_belongs_to_many fixtures where a model doesn't exist #572 [bitsweat]
+
+* Added that running test_units and test_functional now performs the clone_structure_to_test as well #566 [rasputnik]
+
+* Added new generator framework that informs about its doings on generation and enables updating and destruction of generated artifacts. See the new script/destroy and script/update for more details #487 [bitsweat]
+
+* Added Action Web Service as a new add-on framework for Action Pack [Leon Bredt]
+
+* Added Active Support as an independent utility and standard library extension bundle
+
+* Upgraded to Active Record 1.7.0, Action Pack 1.5.0, Action Mailer 0.7.0
+
+
+*0.9.5* (January 25th, 2005)
+
+* Fixed dependency reloading by switching to a remove_const approach where all Active Records, Active Record Observers, and Action Controllers are reloading by undefining their classes. This enables you to remove methods in all three types and see the change reflected immediately and it fixes #539. This also means that only those three types of classes will benefit from the const_missing and reloading approach. If you want other classes (like some in lib/) to reload, you must use require_dependency to do it.
+
+* Added Florian Gross' latest version of Breakpointer and friends that fixes a variaty of bugs #441 [Florian Gross]
+
+* Fixed skeleton Rakefile to work with sqlite3 out of the box #521 [rasputnik]
+
+* Fixed that script/breakpointer didn't get the Ruby path rewritten as the other scripts #523 [[email protected]]
+
+* Fixed handling of syntax errors in models that had already been succesfully required once in the current interpreter
+
+* Fixed that models that weren't referenced in associations weren't being reloaded in the development mode by reinstating the reload
+
+* Fixed that generate scaffold would produce bad functional tests
+
+* Fixed that FCGI can also display SyntaxErrors
+
+* Upgraded to Active Record 1.6.0, Action Pack 1.4.0
+
+
+*0.9.4.1* (January 18th, 2005)
+
+* Added 5-second timeout to WordNet alternatives on creating reserved-word models #501 [Marcel Molina]
+
+* Fixed binding of caller #496 [Alexey]
+
+* Upgraded to Active Record 1.5.1, Action Pack 1.3.1, Action Mailer 0.6.1
+
+
+*0.9.4* (January 17th, 2005)
+
+* Added that ApplicationController will catch a ControllerNotFound exception if someone attempts to access a url pointing to an unexisting controller [Tobias Luetke]
+
+* Flipped code-to-test ratio around to be more readable #468 [Scott Baron]
+
+* Fixed log file permissions to be 666 instead of 777 (so they're not executable) #471 [Lucas Carlson]
+
+* Fixed that auto reloading would some times not work or would reload the models twice #475 [Tobias Luetke]
+
+* Added rewrite rules to deal with caching to public/.htaccess
+
+* Added the option to specify a controller name to "generate scaffold" and made the default controller name the plural form of the model.
+
+* Added that rake clone_structure_to_test, db_structure_dump, and purge_test_database tasks now pick up the source database to use from
+ RAILS_ENV instead of just forcing development #424 [Tobias Luetke]
+
+* Fixed script/console to work with Windows (that requires the use of irb.bat) #418 [octopod]
+
+* Fixed WEBrick servlet slowdown over time by restricting the load path reloading to mod_ruby
+
+* Removed Fancy Indexing as a default option on the WEBrick servlet as it made it harder to use various caching schemes
+
+* Upgraded to Active Record 1.5, Action Pack 1.3, Action Mailer 0.6
+
+
+*0.9.3* (January 4th, 2005)
+
+* Added support for SQLite in the auto-dumping/importing of schemas for development -> test #416
+
+* Added automated rewriting of the shebang lines on installs through the gem rails command #379 [Manfred Stienstra]
+
+* Added ActionMailer::Base.deliver_method = :test to the test environment so that mail objects are available in ActionMailer::Base.deliveries
+ for functional testing.
+
+* Added protection for creating a model through the generators with a name of an existing class, like Thread or Date.
+ It'll even offer you a synonym using wordnet.princeton.edu as a look-up. No, I'm not kidding :) [Florian Gross]
+
+* Fixed dependency management to happen in a unified fashion for Active Record and Action Pack using the new Dependencies module. This means that
+ the environment options needs to change from:
+
+ Before in development.rb:
+ ActionController::Base.reload_dependencies = true Â
+ ActiveRecord::Base.reload_associations   = true
+
+ Now in development.rb:
+ Dependencies.mechanism = :load
+
+ Before in production.rb and test.rb:
+ ActionController::Base.reload_dependencies = false
+ ActiveRecord::Base.reload_associations   = false
+
+ Now in production.rb and test.rb:
+ Dependencies.mechanism = :require
+
+* Fixed problems with dependency caching and controller hierarchies on Ruby 1.8.2 in development mode #351
+
+* Fixed that generated action_mailers doesnt need to require the action_mailer since thats already done in the environment #382 [Lucas Carlson]
+
+* Upgraded to Action Pack 1.2.0 and Active Record 1.4.0
+
+
+*0.9.2*
+
+* Fixed CTRL-C exists from the Breakpointer to be a clean affair without error dumping [Kent Sibilev]
+
+* Fixed "rake stats" to work with sub-directories in models and controllers and to report the code to test ration [Scott Baron]
+
+* Added that Active Record associations are now reloaded instead of cleared to work with the new const_missing hook in Active Record.
+
+* Added graceful handling of an inaccessible log file by redirecting output to STDERR with a warning #330 [rainmkr]
+
+* Added support for a -h/--help parameter in the generator #331 [Ulysses]
+
+* Fixed that File.expand_path in config/environment.rb would fail when dealing with symlinked public directories [mjobin]
+
+* Upgraded to Action Pack 1.1.0 and Active Record 1.3.0
+
+
+*0.9.1*
+
+* Upgraded to Action Pack 1.0.1 for important bug fix
+
+* Updated gem dependencies
+
+
+*0.9.0*
+
+* Renamed public/dispatch.servlet to script/server -- it wasn't really dispatching anyway as its delegating calls to public/dispatch.rb
+
+* Renamed AbstractApplicationController and abstract_application.rb to ApplicationController and application.rb, so that it will be possible
+ for the framework to automatically pick up on app/views/layouts/application.rhtml and app/helpers/application.rb
+
+* Added script/console that makes it even easier to start an IRB session for interacting with the domain model. Run with no-args to
+ see help.
+
+* Added breakpoint support through the script/breakpointer client. This means that you can break out of execution at any point in
+ the code, investigate and change the model, AND then resume execution! Example:
+
+ class WeblogController < ActionController::Base
+ def index
+ @posts = Post.find_all
+ breakpoint "Breaking out from the list"
+ end
+ end
+
+ So the controller will accept the action, run the first line, then present you with a IRB prompt in the breakpointer window.
+ Here you can do things like:
+
+ Executing breakpoint "Breaking out from the list" at .../webrick_server.rb:16 in 'breakpoint'
+
+ >> @posts.inspect
+ => "[#<Post:0x14a6be8 @attributes={\"title\"=>nil, \"body\"=>nil, \"id\"=>\"1\"}>,
+ #<Post:0x14a6620 @attributes={\"title\"=>\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
+ >> @posts.first.title = "hello from a breakpoint"
+ => "hello from a breakpoint"
+
+ ...and even better is that you can examine how your runtime objects actually work:
+
+ >> f = @posts.first
+ => #<Post:0x13630c4 @attributes={"title"=>nil, "body"=>nil, "id"=>"1"}>
+ >> f.
+ Display all 152 possibilities? (y or n)
+
+ Finally, when you're ready to resume execution, you press CTRL-D
+
+* Changed environments to be configurable through an environment variable. By default, the environment is "development", but you
+ can change that and set your own by configuring the Apache vhost with a string like (mod_env must be available on the server):
+
+ SetEnv RAILS_ENV production
+
+ ...if you're using WEBrick, you can pick the environment to use with the command-line parameters -e/--environment, like this:
+
+ ruby public/dispatcher.servlet -e production
+
+* Added a new default environment called "development", which leaves the production environment to be tuned exclusively for that.
+
+* Added a start_server in the root of the Rails application to make it even easier to get started
+
+* Fixed public/.htaccess to use RewriteBase and share the same rewrite rules for all the dispatch methods
+
+* Fixed webrick_server to handle requests in a serialized manner (the Rails reloading infrastructure is not thread-safe)
+
+* Added support for controllers in directories. So you can have:
+
+ app/controllers/account_controller.rb # URL: /account/
+ app/controllers/admin/account_controller.rb # URL: /admin/account/
+
+ NOTE: You need to update your public/.htaccess with the new rules to pick it up
+
+* Added reloading for associations and dependencies under cached environments like FastCGI and mod_ruby. This makes it possible to use
+ those environments for development. This is turned on by default, but can be turned off with
+ ActiveRecord::Base.reload_associations = false and ActionController::Base.reload_dependencies = false in production environments.
+
+* Added support for sub-directories in app/models. So now you can have something like Basecamp with:
+
+ app/models/accounting
+ app/models/project
+ app/models/participants
+ app/models/settings
+
+ It's poor man's namespacing, but only for file-system organization. You still require files just like before.
+ Nothing changes inside the files themselves.
+
+
+* Fixed a few references in the tests generated by new_mailer [bitsweat]
+
+* Added support for mocks in testing with test/mocks
+
+* Cleaned up the environments a bit and added global constant RAILS_ROOT
+
+
+*0.8.5* (9)
+
+* Made dev-util available to all tests, so you can insert breakpoints in any test case to get an IRB prompt at that point [bitsweat]:
+
+ def test_complex_stuff
+ @david.projects << @new_project
+ breakpoint "Let's have a closer look at @david"
+ end
+
+ You need to install dev-utils yourself for this to work ("gem install dev-util").
+
+* Added shared generator behavior so future upgrades should be possible without manually copying over files [bitsweat]
+
+* Added the new helper style to both controller and helper templates [bitsweat]
+
+* Added new_crud generator for creating a model and controller at the same time with explicit scaffolding [bitsweat]
+
+* Added configuration of Test::Unit::TestCase.fixture_path to test_helper to concide with the new AR fixtures style
+
+* Fixed that new_model was generating singular table/fixture names
+
+* Upgraded to Action Mailer 0.4.0
+
+* Upgraded to Action Pack 0.9.5
+
+* Upgraded to Active Record 1.1.0
+
+
+*0.8.0 (15)*
+
+* Removed custom_table_name option for new_model now that the Inflector is as powerful as it is
+
+* Changed the default rake action to just do testing and separate API generation and coding statistics into a "doc" task.
+
+* Fixed WEBrick dispatcher to handle missing slashes in the URLs gracefully [alexey]
+
+* Added user option for all postgresql tool calls in the rakefile [elvstone]
+
+* Fixed problem with running "ruby public/dispatch.servlet" instead of "cd public; ruby dispatch.servlet" [alexey]
+
+* Fixed WEBrick server so that it no longer hardcodes the ruby interpreter used to "ruby" but will get the one used based
+ on the Ruby runtime configuration. [Marcel Molina Jr.]
+
+* Fixed Dispatcher so it'll route requests to magic_beans to MagicBeansController/magic_beans_controller.rb [Caio Chassot]
+
+* "new_controller MagicBeans" and "new_model SubscriptionPayments" will now both behave properly as they use the new Inflector.
+
+* Fixed problem with MySQL foreign key constraint checks in Rake :clone_production_structure_to_test target [Andreas Schwarz]
+
+* Changed WEBrick server to by default be auto-reloading, which is slower but makes source changes instant.
+ Class compilation cache can be turned on with "-c" or "--cache-classes".
+
+* Added "-b/--binding" option to WEBrick dispatcher to bind the server to a specific IP address (default: 127.0.0.1) [Kevin Temp]
+
+* dispatch.fcgi now DOESN'T set FCGI_PURE_RUBY as it was slowing things down for now reason [Andreas Schwarz]
+
+* Added new_mailer generator to work with Action Mailer
+
+* Included new framework: Action Mailer 0.3
+
+* Upgraded to Action Pack 0.9.0
+
+* Upgraded to Active Record 1.0.0
+
+
+*0.7.0*
+
+* Added an optional second argument to the new_model script that allows the programmer to specify the table name,
+ which will used to generate a custom table_name method in the model and will also be used in the creation of fixtures.
+ [Kevin Radloff]
+
+* script/new_model now turns AccountHolder into account_holder instead of accountholder [Kevin Radloff]
+
+* Fixed the faulty handleing of static files with WEBrick [Andreas Schwarz]
+
+* Unified function_test_helper and unit_test_helper into test_helper
+
+* Fixed bug with the automated production => test database dropping on PostgreSQL [dhawkins]
+
+* create_fixtures in both the functional and unit test helper now turns off the log during fixture generation
+ and can generate more than one fixture at a time. Which makes it possible for assignments like:
+
+ @people, @projects, @project_access, @companies, @accounts =
+ create_fixtures "people", "projects", "project_access", "companies", "accounts"
+
+* Upgraded to Action Pack 0.8.5 (locally-scoped variables, partials, advanced send_file)
+
+* Upgraded to Active Record 0.9.5 (better table_name guessing, cloning, find_all_in_collection)
+
+
+*0.6.5*
+
+* No longer specifies a template for rdoc, so it'll use whatever is default (you can change it in the rakefile)
+
+* The new_model generator will now use the same rules for plural wordings as Active Record
+ (so Category will give categories, not categorys) [Kevin Radloff]
+
+* dispatch.fcgi now sets FCGI_PURE_RUBY to true to ensure that it's the Ruby version that's loaded [danp]
+
+* Made the GEM work with Windows
+
+* Fixed bug where mod_ruby would "forget" the load paths added when switching between controllers
+
+* PostgreSQL are now supported for the automated production => test database dropping [Kevin Radloff]
+
+* Errors thrown by the dispatcher are now properly handled in FCGI.
+
+* Upgraded to Action Pack 0.8.0 (lots and lots and lots of fixes)
+
+* Upgraded to Active Record 0.9.4 (a bunch of fixes)
+
+
+*0.6.0*
+
+* Added AbstractionApplicationController as a superclass for all controllers generated. This class can be used
+ to carry filters and methods that are to be shared by all. It has an accompanying ApplicationHelper that all
+ controllers will also automatically have available.
+
+* Added environments that can be included from any script to get the full Active Record and Action Controller
+ context running. This can be used by maintenance scripts or to interact with the model through IRB. Example:
+
+ require 'config/environments/production'
+
+ for account in Account.find_all
+ account.recalculate_interests
+ end
+
+ A short migration script for an account model that had it's interest calculation strategy changed.
+
+* Accessing the index of a controller with "/weblog" will now redirect to "/weblog/" (only on Apache, not WEBrick)
+
+* Simplified the default Apache config so even remote requests are served off CGI as a default.
+ You'll now have to do something specific to activate mod_ruby and FCGI (like using the force urls).
+ This should make it easier for new comers that start on an external server.
+
+* Added more of the necessary Apache options to .htaccess to make it easier to setup
+
+* Upgraded to Action Pack 0.7.9 (lots of fixes)
+
+* Upgraded to Active Record 0.9.3 (lots of fixes)
+
+
+*0.5.7*
+
+* Fixed bug in the WEBrick dispatcher that prevented it from getting parameters from the URL
+ (through GET requests or otherwise)
+
+* Added lib in root as a place to store app specific libraries
+
+* Added lib and vendor to load_path, so anything store within can be loaded directly.
+ Hence lib/redcloth.rb can be loaded with require "redcloth"
+
+* Upgraded to Action Pack 0.7.8 (lots of fixes)
+
+* Upgraded to Active Record 0.9.2 (minor upgrade)
+
+
+*0.5.6*
+
+* Upgraded to Action Pack 0.7.7 (multipart form fix)
+
+* Updated the generated template stubs to valid XHTML files
+
+* Ensure that controllers generated are capitalized, so "new_controller TodoLists"
+ gives the same as "new_controller Todolists" and "new_controller todolists".
+
+
+*0.5.5*
+
+* Works on Windows out of the box! (Dropped symlinks)
+
+* Added webrick dispatcher: Try "ruby public/dispatch.servlet --help" [Florian Gross]
+
+* Report errors about initialization to browser (instead of attempting to use uninitialized logger)
+
+* Upgraded to Action Pack 0.7.6
+
+* Upgraded to Active Record 0.9.1
+
+* Added distinct 500.html instead of reusing 404.html
+
+* Added MIT license
+
+
+*0.5.0*
+
+* First public release
diff --git a/LICENSE_YUBNUB b/LICENSE_YUBNUB
new file mode 100644
index 0000000..89f4f89
--- /dev/null
+++ b/LICENSE_YUBNUB
@@ -0,0 +1,22 @@
+The MIT License
+
+Copyright (c) 2005 Jonathan Aquino
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README b/README
index e0843d2..becc747 100644
--- a/README
+++ b/README
@@ -1,5 +1,37 @@
== YubNub
-To install:
+This is the source code for YubNub, a (social) command-line for the web.
-1)
\ No newline at end of file
+YubNub was written by Jonathan Aquino for the Rails Day 2005 programming competition.
+You can reach Jonathan at [email protected].
+
+http://jonaquino.blogspot.com/2005/06/yubnub-my-entry-for-rails-day-24-hour.html
+
+This source code is made available under the MIT License (see LICENSE_YUBNUB).
+
+== About YubNub
+
+YubNub is a command-line for the web. After setting it up on your browser, you simply type "gim porsche 911" to do a Google Image Search for pictures of Porsche 911 sports cars. Type "random 49" to return random numbers between 1 and 49, courtesy of random.org. And best of all, you can make a new command by giving YubNub an appropriate URL.
+
+www.yubnub.org
+
+== Rails 2.1 Upgrade
+
+Refactored and Upgraded to Rails 2.1 by Jacques Crocker ([email protected])
+
+View source at http://github.com/jcnetdev/yubnub
+
+== Installation Instructions
+
+1) Get Codebase
+git clone git://github.com/jcnetdev/yubnub.git
+cd yubnub
+
+2) Install Gems
+rake gems:install
+
+3) Setup DB and Seed
+rake db:create db:migrate
+
+4) Start Server
+script/server
diff --git a/code_update.tar.gz b/code_update.tar.gz
deleted file mode 100644
index 3cdfb5e..0000000
Binary files a/code_update.tar.gz and /dev/null differ
|
jcnetdev/yubnub
|
94501d71d6ee2da945608417b785f154b2b0d5ee
|
Adding Morph Deploy
|
diff --git a/.gitignore b/.gitignore
index 2177d6e..2ed153f 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,6 +1,7 @@
.DS_Store
tmp/**/*
log/*.log
doc/api
doc/app
doc/plugins
+vendor/gems
\ No newline at end of file
diff --git a/config/morph.rb b/config/morph.rb
new file mode 100644
index 0000000..9d97153
--- /dev/null
+++ b/config/morph.rb
@@ -0,0 +1,279 @@
+require 'fileutils'
+require 'cgi'
+require 'net/https'
+require 'yaml'
+require 'highline/import'
+load 'deploy'
+
+# The svn repository is used to export the code into the temporary directory before
+# uploading code into the Morph control panel. Currently only svn is supported,
+# but you could change it to fit your need by changing the get_code task
+set :repository, "." # Set here your repository! Example: 'https://www.myrepo.com/myapp/trunk'
+set :repo_line_number, __LINE__ - 1 # Needed to report missing repository later on
+
+# The version name to set in the control panel. Defautls to date and time, but can be altered by passing it
+# on the command line as -s version_name='The Version Name'
+set :version_name, Time.now.utc.strftime('%Y-%m-%d %H:%M:%S')
+
+# If you want to use a different scm or use a different export method, you can chane it here
+# Please note that the export to directory is removed before the checkout starts. If
+# You want it to work differently, change the code in the get_code task
+set :deploy_via, :export
+set :scm, :git
+
+# MORPH SETTINGS, please do not change
+set :morph_host, "panel.mor.ph"
+set :morph_port, 443
+set :morph_tmp_dir, 'morph_tmp'
+set :mex_key, "151aba3cc30502a4f5bafd2df827c23d0ff564fc"
+set :mv_cmd, PLATFORM.include?('mswin') ? 'ren' : 'mv'
+set :morph_tmp_dir, 'morph_tmp'
+set :release_path, morph_tmp_dir # needed in order to generate the correct scm command
+set :get_code_using, :get_code
+set :req_retries, 3
+
+
+namespace :morph do
+
+ abort('*** ERROR: You need a MeX key!') if !exists?(:mex_key) || mex_key.nil?
+
+ # This is the entry point task. It gets the new code, then upload it into S3
+ # to a special folder used later for deployment. Finally it mark the version
+ # Uploaded to be deployed
+ task :deploy do
+ transaction do
+ set :mex_key, mex_app_key if exists?(:mex_app_key)
+ abort('*** ERROR: You need a MeX key!') if !exists?(:mex_key) || mex_key.nil?
+ update_code
+ send_request(true, 'Post', morph_host, morph_port, '/api/deploy/deploy', {}, nil, "*** ERROR: Could not deploy the application!")
+ say("Deploy Done.")
+ end
+ end
+
+ # Specialized command to deploy from a packaged gem
+ task :deploy_from_gem do
+ set :get_code_using, :get_code_from_gem
+ deploy
+ end
+
+ # This task calls the get_code helper, then upload the code into S3
+ task :update_code do
+ transaction do
+ s3_obj_name = upload_code_to_s3
+ say("Creating new appspace version...")
+
+ #create a version in CP
+ req_flds = { 'morph-version-name' => version_name, 'morph-version-s3-object' => s3_obj_name }
+ send_request(true, 'Post', morph_host, morph_port, '/versions/create2', req_flds, nil, "*** ERROR: Could not create a new version!")
+ say("Code Upload Done.")
+ end
+ end
+
+ # A task that create a temp dir, export the code ouf ot svn and tar
+ # the code preparing it for upload.
+ # If you are not using svn, or using a different source control tool
+ # you can customize this file to work with it. The requirement is that
+ # It will export the whole structure into the temp directory as set in
+ # morph_tmp_dir.
+ #
+ # You can choose to release a different version than head by setting the
+ # Environment variable 'REL_VER' to the version to use.
+ task :get_code do
+ on_rollback do
+ remove_files([morph_tmp_dir, 'code_update.tar.gz'])
+ end
+
+ # Make sure we have a repo to work from!
+ abort("***ERROR: Must specify the repository to check out from! See line #{repo_line_number} in #{__FILE__}.") if !repository
+
+ transaction do
+ # Clean up previous deploys
+ remove_files([morph_tmp_dir, 'code_update.tar.gz'])
+
+ # unpack gems
+ system("rake RAILS_ENV=production gems:unpack")
+
+ #get latest code from from the repository
+ say("Downloading the code from the repository...")
+ system(strategy.send(:command))
+ abort('*** ERROR: Export from repository failed! Please check the repository setting at the start of the file') if $?.to_i != 0
+
+ # Verify that we have the expected rails structure
+ ['/app', '/public', '/config/environment.rb', '/lib'].each do |e|
+ abort "*** ERROR: Rails directories are missing. Please make sure your set :repository is correct!" if !File.exist?("#{morph_tmp_dir}#{e}")
+ end
+
+ #create archive
+ system("tar -C #{morph_tmp_dir} -czf code_update.tar.gz --exclude='./.*' .")
+ abort('*** ERROR: Failed to tar the file for upload.') if $?.to_i != 0
+
+ # Verify that we have the expected rails structure in the archive
+ flist = `tar tzf code_update.tar.gz`
+ all_in = flist.include?('lib/') && flist.include?('app/') && flist.include?('config/environment.rb')
+ abort "***ERROR: code archive is missing the rails directories. Please check your checkout and tar" if !all_in
+
+ remove_files([morph_tmp_dir])
+ end
+ end
+
+ # Get the code from a packaged gem. Name comes from a setting passed to the command
+ # using the -s form
+ task :get_code_from_gem do
+ # Make sure we have the gem defined and that we have the gem file
+ if !exists?(:gem_file) || gem_file.nil?
+ abort("***ERROR: The gem file must be provided on the command line using -s.\n For example: cap -f morph_deploy.rb -s gem_file=/home/morph/my_app.gem morph:deploy_from_gem")
+ end
+
+ abort("***ERROR: gem file not found! Please check the file location and try again") if !File.exists?(gem_file)
+
+ # Remove older file
+ remove_files(["code_update.tar.gz"])
+
+ # Extract the data.tar.gz code from the gem
+ system("tar xf #{gem_file} data.tar.gz")
+ abort("***ERROR: Couldn't find the data.tar.gz file in the gem file provided!") if !File.exists?('data.tar.gz')
+
+ # rename it to upload_code.tar.gz
+ system("#{mv_cmd} data.tar.gz code_update.tar.gz")
+ end
+
+ # A task to get the S3 connection info and upload code_update.tar.gz
+ # Assumes another task prepared the tar.gz file
+ task :upload_code_to_s3 do
+
+ self.send get_code_using
+
+ abort "*** ERROR: Could not find archive to upload." unless File.exist?('code_update.tar.gz')
+
+ s3_data = ''
+ say('Getting upload information')
+ send_request(true, 'Get', morph_host, morph_port, '/api/s3/connection_data', {}, nil, "*** ERROR: Could not get the S3 connection data!") do |req, res|
+ s3_data = YAML.load(res.body)
+ end
+
+ if !s3_data.empty?
+ say('Uploading code to S3...')
+ File.open('code_update.tar.gz', 'rb') do |up_file|
+ send_request(false, 'Put', s3_data[:host], morph_port, s3_data[:path], s3_data[:header], up_file, "*** ERROR: Could not upload the code!")
+ end
+ end
+
+ s3_data[:obj_name]
+ end
+
+ # Helper to add the mex auth fields to the requests
+ def add_mex_fields(req)
+ if exists?(:deploy_key) and mex_key
+ req['morph-deploy-key'] = deploy_key
+ else
+ req['morph-user'] = morph_user
+ req['morph-pass'] = morph_pass
+ end
+ req['morph-app'] = mex_key
+ end
+
+ # Helper to generate REST requests, handle authentication and errors
+ def send_request(is_mex, req_type, host, port, url, fields_hash, up_file, error_msg)
+ tries_done = 0
+ res = ''
+ while res != :ok
+ if is_mex and (!exists?(:deploy_key) or !exists?(:mex_key))
+ say("*** Getting info for Morph authentication ***") if !exists?(:morph_user) || morph_user.nil? || !exists?(:morph_pass) || morph_pass.nil?
+ set(:morph_user, ask("Morph user: ")) if !exists?(:morph_user) || morph_user.nil?
+ set(:morph_pass, ask("Password: ") { |q| q.echo = false }) if !exists?(:morph_pass) || morph_pass.nil?
+ end
+
+ conn_start(host, port) do |http|
+ request = Module.module_eval("Net::HTTP::#{req_type}").new(url)
+ add_mex_fields(request) if is_mex
+ fields_hash.each_pair{|n,v| request[n] = v} # Add user defined header fields
+ # If a file is passed we upload it.
+ if up_file
+ request.content_length = up_file.lstat.size
+ request.body_stream = up_file # For uploads using streaming
+ else
+ request.content_length = 0
+ end
+
+ begin
+ response = http.request(request)
+ rescue Exception => ex
+ response = ex.to_s
+ end
+
+ # Handle auth errors and other errors!
+ res = verify_response(request, response, is_mex)
+ if res == :ok
+ yield(request, response) if block_given?
+ elsif exists?(:deploy_key) #if via deploy key, just exit
+ say("Incorrect deploy_key or mex_app_key")
+ exit
+ elsif res != :auth_fail # On auth_fail we just loop around
+ tries_done += 1
+ abort(error_msg) if tries_done > req_retries
+ end
+ end
+ end
+ end
+
+
+ # Helper to create a connection with all the needed setting
+ # And yeals to the block
+ def conn_start host = morph_host, port = morph_port
+ con = Net::HTTP.new(host, port)
+ con.use_ssl = true
+ # If you have cert files to use, change this to OpenSSL::SSL::VERIFY_PEER
+ # And set the ca_cert of the connection
+ con.verify_mode = OpenSSL::SSL::VERIFY_NONE
+ con.start
+ if block_given?
+ begin
+ return yield(con)
+ ensure
+ con.finish
+ end
+ end
+ con
+ end
+
+ # Helper to verify if a response is valid. Also handles authentication failures into MeX
+ def verify_response(request, response, is_mex)
+ res = :ok
+ if !response.is_a?(Net::HTTPOK)
+ if response.is_a?(Net::HTTPForbidden) && is_mex
+ say("Authentication failed! Please try again.")
+ set :morph_user, nil
+ set :morph_pass, nil
+ res = :auth_fail
+ else
+ if response.is_a?(String)
+ say("*** ERROR: connection failure: #{response}")
+ else
+ output_request_param(request, response)
+ end
+ res = :failure
+ end
+ end
+ return res
+ end
+
+ # Helper to output the results of REST calls to our servers or S3
+ def output_request_param(request, response)
+ puts "\n========== ERROR TRACE =========="
+ puts "+++++++ REQUEST HEADERS +++++++++"
+ request.each {|e,r| puts "#{e}: #{r}"}
+ puts "+++++++ RESPONSE HEADERS +++++++++"
+ response.each {|e,r| puts "#{e}: #{r}"}
+ puts "+++++++ RESPONSE BODY +++++++++"
+ puts response.body
+ puts "+++++++ RESPONSE TYPE +++++++++"
+ puts "#{response.class} (#{response.code})"
+ puts "========= END OF TRACE ==========\n"
+ end
+
+ def remove_files(lists)
+ FileUtils.cd(FileUtils.pwd)
+ FileUtils.rm_r(lists, :force => true) rescue ''
+ end
+
+end
|
jcnetdev/yubnub
|
fd24fdfb6356f6ce061bf028666db5c2741bfa55
|
Fixing base project
|
diff --git a/app/controllers/sessions_controller.rb b/app/controllers/sessions_controller.rb
index 95d7ea0..0aa2f47 100644
--- a/app/controllers/sessions_controller.rb
+++ b/app/controllers/sessions_controller.rb
@@ -1,51 +1,51 @@
# This controller handles the login/logout function of the site.
class SessionsController < ApplicationController
# Be sure to include AuthenticationSystem in Application Controller instead
include AuthenticatedSystem
before_filter :check_login, :only => [:new, :create]
# render new.rhtml
def new
@login = Login.new
end
def create
@login = Login.new(params[:login])
self.current_user = User.login_with(@login)
-
+
if logged_in?
if @login.remember_me?
self.current_user.remember_me
cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
end
redirect_back_or_default('/')
flash[:notice] = "Logged in successfully"
else
render :action => 'new'
end
end
def destroy
self.current_user.forget_me if logged_in?
cookies.delete :auth_token
reset_session
flash[:notice] = "You have been logged out."
redirect_back_or_default('/')
end
def show
end
def index
redirect_to session_url
end
private
def check_login
if logged_in?
redirect_to session_url
return false
end
end
end
diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb
index fcaa758..8c0fb87 100644
--- a/app/helpers/application_helper.rb
+++ b/app/helpers/application_helper.rb
@@ -1,140 +1,145 @@
# Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
# display flash_boxes (unless its already been shown)
def flash_boxes
unless @flash_shown
@flash_shown = true
render :partial => "layouts/flash_boxes"
else
""
end
end
def clear(direction = nil)
"<div class=\"clear#{direction}\"></div>"
end
# returns the controller & action
def action_path
"#{params[:controller]}/#{params[:action]}"
end
# return the css class for the current controller and action
def body_class
classes = ""
classes << "container"
classes << " "
classes << controller.controller_name
classes << "-"
classes << controller.action_name
classes << " "
unless production?
classes << "debug"
end
return classes.strip
end
def production?
ENV["RAILS_ENV"] == "production"
end
# returns either the new_arg or the edit_arg depending on if the action is a new or edit action
def new_or_edit(new_arg, edit_arg, other = nil)
if is_new?
return new_arg
elsif is_edit?
return edit_arg
else
return other
end
end
def is_new?
action = params[:action]
action == "new" || action == "create"
end
def is_edit?
action = params[:action]
action == "edit" || action == "update"
end
+ # Whether or not to use caching
+ def use_cache?
+ ActionController::Base.perform_caching
+ end
+
def paging(page_data, style = :sabros)
return unless page_data.class == WillPaginate::Collection
will_paginate(page_data, :class => "pagination #{style}", :inner_window => 3)
end
def error_messages_for(name, options = {})
super(name, {:id => "error_explanation", :class => "error"}.merge(options))
end
def hide_if(condition)
if condition
{:style => "display:none"}
else
{}
end
end
def hide_unless(condition)
hide_if(!condition)
end
def br
"<br />"
end
def hr
"<hr />"
end
def space
"<hr class='space' />"
end
def anchor(anchor_name)
"<a name='#{anchor_name}'></a>"
end
def button(text, options = {})
submit_tag(text, options)
end
def clear_tag(tag, direction = nil)
"<#{tag} class=\"clear#{direction}\"></#{tag}>"
end
def clear(direction = nil)
clear_tag(:div, direction)
end
def lorem
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
end
def hidden
{:style => "display:none"}
end
def clearbit_icon(icon, color, options = {})
image_tag "clearbits/#{icon}.gif", {:class => "clearbits #{color}", :alt => icon}.merge(options)
end
def delete_link(*args)
options = {:method => :delete, :confirm => "Are you sure you want to delete this?"}.merge(args.extract_options!)
args << options
link_to *args
end
def link_to_block(*args, &block)
content = capture_haml(&block)
return link_to(content, *args)
end
# pixel spacing helper
def pixel(options = {})
image_tag "pixel.png", options
end
end
diff --git a/app/helpers/javascript_helper.rb b/app/helpers/javascript_helper.rb
index 900c47f..2db765d 100644
--- a/app/helpers/javascript_helper.rb
+++ b/app/helpers/javascript_helper.rb
@@ -1,37 +1,37 @@
module JavascriptHelper
# Add javascripts to page
def javascripts(options = {})
[
javascript("prototype"),
javascript("scriptaculous/scriptaculous"),
javascript("jquery"),
javascript_tag("$j = jQuery.noConflict();"),
javascript(include_javascripts("jquery.ext")),
javascript(include_javascripts("libraries")),
javascript(include_javascripts("common")),
javascript(include_javascripts("components")),
page_javascripts(options),
javascript("application")
].flatten.join("\n")
end
# returns a list of *css file paths* for a sass directory
def include_javascripts(path)
- if AppConfig.minimize
+ if use_cache?
"min/#{path}.js"
else
javascript_list = Dir["#{RAILS_ROOT}/public/javascripts/#{path}/*.js"]
result = []
javascript_list.each do |javascript|
result << javascript.gsub("#{RAILS_ROOT}/public/javascripts/", "")
end
return result
end
end
end
\ No newline at end of file
diff --git a/app/helpers/stylesheet_helper.rb b/app/helpers/stylesheet_helper.rb
index 53d0424..a767f95 100644
--- a/app/helpers/stylesheet_helper.rb
+++ b/app/helpers/stylesheet_helper.rb
@@ -1,40 +1,40 @@
module StylesheetHelper
# Include stylesheets
def stylesheets(options = {})
[
blueprint,
stylesheet("forms"),
stylesheet(sass_files),
page_stylesheets(options)
].join("\n")
end
# List of Sass FIles
def sass_files
- if AppConfig.minimize
+ if use_cache?
["min/application", "min/common", "min/components"]
else
["application", include_sass("common"), include_sass("components")]
end
end
# Include Blueprint CSS
def blueprint
stylesheet("blueprint", :media => "screen, projection")
end
# Returns a list of *css file paths* for a sass directory
def include_sass(path)
# include common and component sass
sass_styles = Dir["#{RAILS_ROOT}/public/stylesheets/sass/#{path}/*.sass"]
# convert to css paths
css_styles = []
sass_styles.each do |sass_path|
css_path = sass_path.gsub("#{RAILS_ROOT}/public/stylesheets/sass/", "").gsub(".sass", ".css")
css_styles << css_path
end
return css_styles
end
end
\ No newline at end of file
diff --git a/config/environment.rb b/config/environment.rb
index 61e2bc3..ab7ce35 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,207 +1,207 @@
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '>= 2.1.0' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_blank_session',
:secret => 'd27cc7f3bae1ef15fa00a9fad245f42057cff6113327d732a4dbd8e43c3eaba1a5bda246f882029653b71266c2015ef38ff4ce67616d8a0b2c220884edaba8c7'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
# standard gems
config.gem "haml", :version => ">= 2.0.0"
# ssl_requirement
# ------
# Allow controller actions to force SSL on specific parts of the site
# ------
config.gem 'jcnetdev-ssl_requirement', :version => '>= 1.0',
:lib => 'ssl_requirement',
:source => 'http://gems.github.com'
# exception_notification
# ------
# Allows unhandled exceptions to be emailed on production
# ------
config.gem 'jcnetdev-exception_notification', :version => '>= 1.1',
:lib => 'exception_notification',
:source => 'http://gems.github.com'
# Rails Plugins (via gems)
# active_record_without_table
# ------
# Allows creation of ActiveRecord models that work without any database backend
# ------
config.gem 'jcnetdev-active_record_without_table', :version => '>= 1.1',
:lib => 'active_record_without_table',
:source => 'http://gems.github.com'
# acts_as_state_machine
# ------
# Allows ActiveRecord models to define states and transition actions between them
# ------
config.gem 'jcnetdev-acts_as_state_machine', :version => '>= 2.1.0',
:lib => 'acts_as_state_machine',
:source => 'http://gems.github.com'
# app_config
# ------
# Allow application wide configuration settings via YML files
# ------
config.gem 'jcnetdev-app_config', :version => '>= 1.0',
:lib => 'app_config',
:source => 'http://gems.github.com'
- # auto_migrations
- # ------
- # Allows migrations to be run automatically based on updating the schema.rb
- # ------
- config.gem 'jcnetdev-auto_migrations', :version => '>= 1.1',
+ # # auto_migrations
+ # # ------
+ # # Allows migrations to be run automatically based on updating the schema.rb
+ # # ------
+ config.gem 'jcnetdev-auto_migrations', :version => '>= 1.2',
:lib => 'auto_migrations',
:source => 'http://gems.github.com'
# better_partials
# ------
# Makes calling partials in views look better and more fun
# ------
config.gem 'jcnetdev-better_partials', :version => '>= 1.0',
:lib => 'better_partials',
:source => 'http://gems.github.com'
# form_fu
# ------
# Allows easier rails form creation and processing
# ------
# config.gem 'neorails-form_fu', :version => '>= 1.0',
# :lib => 'form_fu',
# :source => 'http://gems.github.com'
# paperclip
# ------
# Allows easy uploading of files with no dependencies
# ------
config.gem 'jcnetdev-paperclip', :version => '>= 1.0',
:lib => 'paperclip',
:source => 'http://gems.github.com'
# seed-fu
# ------
# Allows easier database seeding of tables
# ------
config.gem 'jcnetdev-seed-fu', :version => '>= 1.0',
:lib => 'seed-fu',
:source => 'http://gems.github.com'
# subdomain-fu
# ------
# Allows easier subdomain selection
# ------
config.gem 'jcnetdev-subdomain-fu', :version => '>= 0.0.2',
:lib => 'subdomain-fu',
:source => 'http://gems.github.com'
# validates_as_email_address
# ------
# Allows for easy format validation of email addresses
# ------
config.gem 'jcnetdev-validates_as_email_address', :version => '>= 1.0',
:lib => 'validates_as_email_address',
:source => 'http://gems.github.com'
# will_paginate
# ------
# Allows nice and easy pagination
# ------
config.gem 'jcnetdev-will_paginate', :version => '>= 2.3.2',
:lib => 'will_paginate',
:source => 'http://gems.github.com'
# view_fu
# ------
# Adds view helpers for titles, stylesheets, javascripts, and common tags
# ------
# config.gem 'neorails-view_fu', :version => '>= 1.0',
# :lib => 'view_fu',
# :source => 'http://gems.github.com'
# OPTIONAL PLUGINS
# acts_as_list
# ------
# Allows ActiveRecord Models to be easily ordered via position attributes
# ------
# config.gem 'jcnetdev-acts_as_list', :version => '>= 1.0',
# :lib => 'acts_as_list',
# :source => 'http://gems.github.com'
# acts-as-readable
# ------
# Allows ActiveRecord Models to be easily marked as read / unread
# ------
# config.gem 'jcnetdev-acts-as-readable', :version => '>= 1.0',
# :lib => 'acts_as_readable',
# :source => 'http://gems.github.com'
# sms-fu
# ------
# Send SMS messages easily
# ------
# config.gem 'jcnetdev-sms-fu', :version => '>= 1.0',
# :lib => 'sms_fu',
# :source => 'http://gems.github.com'
end
diff --git a/config/environments/development.rb b/config/environments/development.rb
index f7a3636..84c8860 100644
--- a/config/environments/development.rb
+++ b/config/environments/development.rb
@@ -1,20 +1,19 @@
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
-config.action_view.cache_template_extensions = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
config.action_mailer.delivery_method = :test
\ No newline at end of file
diff --git a/config/initializers/inflections.rb b/config/initializers/inflections.rb
index a0ab6b5..cc40681 100644
--- a/config/initializers/inflections.rb
+++ b/config/initializers/inflections.rb
@@ -1,10 +1,11 @@
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format
# (all these examples are active by default):
Inflector.inflections do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
- # inflect.irregular 'person', 'people'
- inflect.uncountable %w( mail_incoming mail_outgoing )
+
+ inflect.irregular 'mail_outgoing', 'mail_outgoing'
+ inflect.irregular 'mail_incoming', 'mail_incoming'
end
diff --git a/db/schema.rb b/db/schema.rb
index f19b9c8..352cc87 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,56 +1,51 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 1) do
+ActiveRecord::Schema.define(:version => 0) do
create_table "mail_incoming", :force => true do |t|
t.text "mail"
t.datetime "created_on"
end
create_table "mail_outgoing", :force => true do |t|
t.string "from"
t.string "to"
t.integer "last_send_attempt", :limit => 11, :default => 0
t.text "mail"
t.datetime "created_on"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email"
t.string "crypted_password", :limit => 40
t.string "salt", :limit => 40
t.datetime "created_at"
t.datetime "updated_at"
t.string "remember_token"
t.datetime "remember_token_expires_at"
t.string "activation_code", :limit => 40
t.datetime "activated_at"
t.string "state", :default => "passive"
t.datetime "deleted_at"
end
create_table "widgets", :force => true do |t|
t.string "name"
t.integer "price", :limit => 10
t.text "description"
t.boolean "is_in_stock"
t.datetime "created_at"
t.datetime "updated_at"
end
- create_table :photos, :force => true do |t|
- t.string "url"
- t.timestamps
- end
-
end
diff --git a/lib/tasks/auto_migrations_tasks.rake b/lib/tasks/auto_migrations_tasks.rake
index 2ea0034..66b89d8 100644
--- a/lib/tasks/auto_migrations_tasks.rake
+++ b/lib/tasks/auto_migrations_tasks.rake
@@ -1,16 +1,16 @@
namespace :db do
namespace :auto do
desc "Use schema.rb to auto-migrate"
- task :migrate do
+ task :migrate => :environment do
AutoMigrations.run
end
end
namespace :schema do
desc "Create migration from schema.rb"
- task :to_migration do
+ task :to_migration => :environment do
AutoMigrations.schema_to_migration
end
end
end
diff --git a/lib/tasks/migrate.rake b/lib/tasks/migrate.rake
index 46c8ea7..ec18858 100644
--- a/lib/tasks/migrate.rake
+++ b/lib/tasks/migrate.rake
@@ -1,17 +1,21 @@
require 'rubygems'
require 'rake'
class Rake::Task
def overwrite(&block)
@actions.clear
enhance(&block)
end
end
# Overwrite migrate task
Rake::Task["db:migrate"].overwrite do
puts "Running Auto Migration and DB Seed..."
Rake::Task["db:auto:migrate"].invoke
Rake::Task["db:seed"].invoke
-end
\ No newline at end of file
+end
+#
+# task :wtf => :environment do
+# puts Rails.env
+# end
\ No newline at end of file
diff --git a/lib/tasks/sass.rake b/lib/tasks/sass.rake
index 8da108f..abdeb8b 100644
--- a/lib/tasks/sass.rake
+++ b/lib/tasks/sass.rake
@@ -1,92 +1,87 @@
# Make sure we load an environment (default to prod)
-
-RAILS_ENV="production" unless ENV["RAILS_ENV"]
-require File.dirname(__FILE__) + '/../../config/environment'
-
require 'haml'
require 'sass'
namespace :sass do
-
desc 'Clean and Build Sass Templates'
task :rebuild => [:clean, :build]
desc 'Find all Sass Templates and delete their related css files'
task :clean do
puts "Cleaning SASS Generated Files..."
find_sass.each do |sass_path|
css_path = css_path_for(sass_path)
# delete css file if it exists
if File.exists?(css_path)
File.delete(css_path)
puts "Deleted "+path_clean(css_path)
end
end
puts "\n"
puts "Clearing SASS Generated Directories..."
find_sass_directories.each do |sass_dir_path|
css_dir_path = css_path_for(sass_dir_path)
if File.exists?(css_dir_path)
FileUtils.remove_dir(css_dir_path)
puts "Deleted "+path_clean(css_dir_path)
end
end
puts "\n"
end
# Rebuild sass files without needing rails
desc 'Find all Sass Templates and render their related css file'
task :build do
puts "Building CSS Directories..."
find_sass_directories.each do |sass_dir_path|
css_dir_path = css_path_for(sass_dir_path)
puts "Creating Directory "+path_clean(css_dir_path)+" from "+path_clean(sass_dir_path)
FileUtils.mkdir_p(css_dir_path)
end
puts "\n"
puts "Building CSS Generated Files from SASS..."
find_sass.each do |sass_path|
puts "Generating "+path_clean(css_path_for(sass_path))+" from "+path_clean(sass_path)
render_sass(sass_path)
end
puts "\n"
end
# recursively search sass directory for sass files
def find_sass
Dir["#{RAILS_ROOT}/public/stylesheets/sass/**/*.sass"]
end
def find_sass_directories
Dir["#{RAILS_ROOT}/public/stylesheets/sass/**/*/"]
end
# Find the css path for a related sass file
def css_path_for(sass_path)
sass_path \
.gsub("#{RAILS_ROOT}/public/stylesheets/sass/","#{RAILS_ROOT}/public/stylesheets/") \
.gsub(".sass",".css")
end
# Removes RAILS_ROOT from a css path so we can display it
def path_clean(file_path)
file_path.gsub("#{RAILS_ROOT}/public/stylesheets/", "")
end
# Writing Sass
def render_sass(sass_path)
# template = File.load(sass_path)
import_statement = "@import "+path_clean(sass_path).gsub("sass/", "").gsub(".sass", "")
sass_engine = Sass::Engine.new(import_statement, {:load_paths => ["#{RAILS_ROOT}/public/stylesheets/sass"], :style => :compact})
# write output
File.open(css_path_for(sass_path), "w") do |f|
f.puts sass_engine.render
end
end
end
\ No newline at end of file
diff --git a/public/stylesheets/application.css b/public/stylesheets/application.css
index e69de29..8b13789 100644
--- a/public/stylesheets/application.css
+++ b/public/stylesheets/application.css
@@ -0,0 +1 @@
+
diff --git a/public/stylesheets/common/paging.css b/public/stylesheets/common/paging.css
index 40ad40d..d6b01ae 100644
--- a/public/stylesheets/common/paging.css
+++ b/public/stylesheets/common/paging.css
@@ -1,616 +1,142 @@
-.pagination {
- margin-top: 20px;
- float: right; }
-
-.pagination.badoo {
- background-color: #fff;
- color: #48b9ef;
- padding: 10px 0 10px 0;
- font-family: Arial, Helvetica, sans-serif;
- font-size: 13px;
- text-align: center; }
- .pagination.badoo a {
- color: #48b9ef;
- padding: 2px 5px;
- margin: 0 2px;
- text-decoration: none;
- border: 2px solid #f0f0f0; }
- .pagination.badoo a:hover, .pagination.badoo a:active {
- border: 2px solid #ff5a00;
- color: #ff5a00; }
- .pagination.badoo span.current {
- padding: 2px 5px;
- border: 2px solid #ff5a00;
- color: #fff;
- font-weight: bold;
- background-color: #ff6c16; }
- .pagination.badoo span.disabled {
- display: none; }
-
-.pagination.black_red {
- font-size: 11px;
- font-family: Tahoma, Arial, Helvetica, Sans-serif;
- background-color: #3e3e3e;
- color: #fff; }
- .pagination.black_red a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #3e3e3e;
- text-decoration: none;
- color: #fff; }
- .pagination.black_red a:hover, .pagination.black_red a:active {
- background-color: #ec5210;
- color: #fff; }
- .pagination.black_red span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- font-weight: bold;
- background-color: #313131;
- color: #fff; }
- .pagination.black_red span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #3e3e3e;
- color: #868686; }
-
-.pagination.blue {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- .pagination.blue a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #EEE;
- text-decoration: none;
- color: #036CB4; }
- .pagination.blue a:hover, .pagination.blue a:active {
- border: 1px solid #999;
- color: #666; }
- .pagination.blue .current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #036CB4;
- font-weight: bold;
- background-color: #036CB4;
- color: #FFF; }
- .pagination.blue .disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #EEE;
- color: #DDD; }
-
-.pagination.digg {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- .pagination.digg a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #AAAADD;
- text-decoration: none;
- color: #000099; }
- .pagination.digg a:hover, .pagination.digg div.digg a:active {
- border: 1px solid #000099;
- color: #000; }
- .pagination.digg span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #000099;
- font-weight: bold;
- background-color: #000099;
- color: #FFF; }
- .pagination.digg span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #EEE;
- color: #DDD; }
-
-.pagination.flickr {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- .pagination.flickr a {
- border: 1px solid #dedfde;
- margin-right: 3px;
- padding: 2px 6px;
- background-position: bottom;
- text-decoration: none;
- color: #0061de; }
- .pagination.flickr a:hover, .pagination.flickr a:active {
- border: 1px solid #000;
- background-image: none;
- background-color: #0061de;
- color: #fff; }
- .pagination.flickr span.current {
- margin-right: 3px;
- padding: 2px 6px;
- font-weight: bold;
- color: #ff0084; }
- .pagination.flickr span.disabled {
- margin-right: 3px;
- padding: 2px 6px;
- color: #adaaad; }
-
-.pagination.gray {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- .pagination.gray a {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #ddd;
- text-decoration: none;
- color: #aaa; }
- .pagination.gray a:hover, .pagination.gray a:active {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #a0a0a0; }
- .pagination.gray span.current {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #e0e0e0;
- font-weight: bold;
- background-color: #f0f0f0;
- color: #aaa; }
- .pagination.gray span.disabled {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #f3f3f3;
- color: #ccc; }
-
-div.pagination.gray2 {
- font-size: 11px;
- font-family: Tahoma, Arial, Helvetica, Sans-serif;
- padding: 2px;
- background-color: #c1c1c1; }
- div.pagination.gray2 a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #c1c1c1;
- text-decoration: none;
- color: #000; }
- div.pagination.gray2 a:hover, div.pagination.gray2 a:active {
- background-color: #99ffff;
- color: #000; }
- div.pagination.gray2 span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- font-weight: bold;
- background-color: #fff;
- color: #303030; }
- div.pagination.gray2 span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #c1c1c1;
- color: #797979; }
-
-div.pagination.green {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- div.pagination.green a {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #ddd;
- text-decoration: none;
- color: #88AF3F; }
- div.pagination.green a:hover, div.pagination.green a:active {
- border: 1px solid #85BD1E;
- color: #638425;
- background-color: #F1FFD6; }
- div.pagination.green span.current {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #B2E05D;
- font-weight: bold;
- background-color: #B2E05D;
- color: #FFF; }
- div.pagination.green span.disabled {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #f3f3f3;
- color: #ccc; }
-
-div.pagination.green_black {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- div.pagination.green_black a {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #2C2C2C;
- text-decoration: none;
- color: #fff;
- background: #2C2C2C url(/images/paging/green_black_bg1.gif); }
- div.pagination.green_black a:hover, div.pagination.green_black a:active {
- border: 1px solid #AAD83E;
- color: #FFF;
- background: #AAD83E url(/images/paging/green_black_bg2.gif); }
- div.pagination.green_black span.current {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #AAD83E;
- font-weight: bold;
- background: #AAD83E url(/images/paging/green_black_bg2.gif);
- color: #FFF; }
- div.pagination.green_black span.disabled {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #f3f3f3;
- color: #ccc; }
-
-div.pagination.jogger {
- font-family: "Lucida Sans Unicode" "Lucida Grande" LucidaGrande "Lucida Sans" Geneva Verdana sans-serif;
- padding: 2px;
- margin: 7px; }
- div.pagination.jogger a {
- margin: 2px;
- padding: 0.5em 0.64em 0.43em 0.64em;
- background-color: #ee4e4e;
- text-decoration: none;
- color: #fff; }
- div.pagination.jogger a:hover, div.pagination.jogger a:active {
- padding: 0.5em 0.64em 0.43em 0.64em;
- margin: 2px;
- background-color: #de1818;
- color: #fff; }
- div.pagination.jogger span.current {
- padding: 0.5em 0.64em 0.43em 0.64em;
- margin: 2px;
- background-color: #f6efcc;
- color: #6d643c; }
- div.pagination.jogger span.disabled {
- display: none; }
-
-.pagination.megas {
- text-align: center; }
- .pagination.megas a {
- border: 1px solid #dedfde;
- margin-right: 3px;
- padding: 2px 6px;
- background-position: bottom;
- text-decoration: none;
- color: #99210B; }
- .pagination.megas a:hover, .pagination.megas a:active {
- border: 1px solid #000;
- background-color: #777777;
- color: #fff; }
- .pagination.megas span.current {
- margin-right: 3px;
- padding: 2px 6px;
- font-weight: bold;
- color: #99210B; }
- .pagination.megas span.disabled {
- margin-right: 3px;
- padding: 2px 6px;
- color: #adaaad; }
-
-div.pagination.meneame {
- padding: 3px;
- margin: 3px;
- text-align: center;
- color: #ff6500;
- font-size: 80%; }
- div.pagination.meneame a {
- border: 1px solid #ff9600;
- margin-right: 3px;
- padding: 5px 7px;
- background-image: url(/images/paging/meneame_bg.jpg);
- background-position: bottom;
- text-decoration: none;
- color: #ff6500; }
- div.pagination.meneame a:hover, div.pagination.meneame a:active {
- border: 1px solid #ff9600;
- background-image: none;
- background-color: #ffc794;
- color: #ff6500; }
- div.pagination.meneame span.current {
- margin-right: 3px;
- padding: 5px 7px;
- border: 1px solid #ff6500;
- font-weight: bold;
- background-color: #ffbe94;
- color: #ff6500; }
- div.pagination.meneame span.disabled {
- margin-right: 3px;
- padding: 5px 7px;
- border: 1px solid #ffe3c6;
- color: #ffe3c6; }
-
-div.pagination.mis_algoritmos {
- text-align: center;
- padding: 7px;
- margin: 3px; }
- div.pagination.mis_algoritmos a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #000000;
- text-decoration: none;
- color: #000000; }
- div.pagination.mis_algoritmos a:hover, div.pagination.mis_algoritmos a:active {
- border: 1px solid #000000;
- background-color: #000000;
- color: #fff; }
- div.pagination.mis_algoritmos span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #000000;
- font-weight: bold;
- background-color: #000000;
- color: #FFF; }
- div.pagination.mis_algoritmos span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #EEE;
- color: #DDD; }
-
-div.pagination.msdn {
- background-color: #fff;
- color: #48b9ef;
- padding: 10px 0 10px 0;
- font-family: Arial Helvetica sans-serif;
- font-size: 13px;
- text-align: center; }
- div.pagination.msdn a {
- color: #48b9ef;
- padding: 2px 5px;
- margin: 0 2px;
- text-decoration: none;
- border: 2px solid #f0f0f0; }
- div.pagination.msdn a:hover, div.pagination.msdn a:active {
- border: 2px solid #ff5a00;
- color: #ff5a00; }
- div.pagination.msdn span.current {
- padding: 2px 5px;
- border: 2px solid #ff5a00;
- color: #fff;
- font-weight: bold;
- background-color: #ff6c16; }
- div.pagination.msdn span.disabled {
- display: none; }
-
-div.pagination.new_yahoo {
- padding: 3px;
- margin: 3px;
- text-align: center;
- font-family: TahomaHelveticasans-serif;
- font-size: .85em; }
- div.pagination.new_yahoo a {
- border: 1px solid #ccdbe4;
- margin-right: 3px;
- padding: 2px 8px;
- background-position: bottom;
- text-decoration: none;
- color: #0061de; }
- div.pagination.new_yahoo a:hover, div.pagination.new_yahoo a:active {
- border: 1px solid #2b55af;
- background-image: none;
- background-color: #3666d4;
- color: #fff; }
- div.pagination.new_yahoo span.current {
- margin-right: 3px;
- padding: 2px 6px;
- font-weight: bold;
- color: #000; }
- div.pagination.new_yahoo a.next {
- border: 2px solid #ccdbe4;
- margin: 0 0 0 10px; }
- div.pagination.new_yahoo a.next:hover {
- border: 2px solid #2b55af; }
- div.pagination.new_yahoo a.prev {
- border: 2px solid #ccdbe4;
- margin: 0 10px 0 0; }
- div.pagination.new_yahoo a.prev:hover {
- border: 2px solid #2b55af; }
-
-div.pagination.on_black {
- padding: 3px;
- margin: 3px;
- text-align: center;
- color: #a0a0a0;
- font-size: 80%; }
- div.pagination.on_black a {
- border: 1px solid #909090;
- margin-right: 3px;
- padding: 2px 5px;
- background-image: url(/images/paging/onblack_bg1.gif);
- background-position: bottom;
- text-decoration: none;
- color: #c0c0c0; }
- div.pagination.on_black a:hover, div.pagination.on_black a:active {
- border: 1px solid #f0f0f0;
- background-image: url(/images/paging/onblack_bg2.gif);
- background-color: #404040;
- color: #ffffff; }
- div.pagination.on_black span.current {
- margin-right: 3px;
- padding: 2px 5px;
- border: 1px solid #ffffff;
- font-weight: bold;
- background-color: #606060;
- color: #ffffff; }
- div.pagination.on_black span.disabled {
- margin-right: 3px;
- padding: 2px 5px;
- border: 1px solid #606060;
- color: #808080; }
-
-div.pagination.sabros {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- div.pagination.sabros a {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #9aafe5;
- text-decoration: none;
- color: #2e6ab1; }
- div.pagination.sabros a:hover, div.pagination.sabros a:active {
- border: 1px solid #2b66a5;
- color: #000;
- background-color: lightyellow; }
- div.pagination.sabros span.current {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid navy;
- font-weight: bold;
- background-color: #2e6ab1;
- color: #FFF; }
- div.pagination.sabros span.disabled {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #929292;
- color: #929292; }
-
-div.pagination.technorati {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- div.pagination.technorati a {
- border: 1px solid #ccc;
- margin-right: 3px;
- padding: 2px 6px;
- background-position: bottom;
- text-decoration: none;
- font-weight: bold;
- color: rgb(66,97,222); }
- div.pagination.technorati a:hover, div.pagination.technorati a:active {
- background-image: none;
- background-color: #4261DF;
- color: #fff; }
- div.pagination.technorati span.current {
- margin-right: 3px;
- padding: 2px 6px;
- font-weight: bold;
- color: #000; }
- div.pagination.technorati span.disabled {
- display: none; }
-
-div.pagination.tres {
- text-align: center;
- padding: 7px;
- margin: 3px;
- font-family: Arial, Helvetica, sans-serif;
- font-size: 13.2pt;
- font-weight: bold; }
- div.pagination.tres a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 2px solid #d9d300;
- text-decoration: none;
- color: #fff;
- background-color: #d90; }
- div.pagination.tres a:hover, div.pagination.tres a:active {
- border: 2px solid #ff0;
- background-color: #ff0;
- color: #000; }
- div.pagination.tres span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 2px solid #fff;
- font-weight: bold;
- color: #000; }
- div.pagination.tres span.disabled {
- display: none; }
-
-div.pagination.viciao2k3 {
- margin-top: 20px;
- margin-bottom: 10px; }
- div.pagination.viciao2k3 a {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #8DB5D7;
- text-decoration: none;
- color: #000; }
- div.pagination.viciao2k3 a:hover, div.pagination.viciao2k3 a:active {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid red; }
- div.pagination.viciao2k3 span.current {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #E89954;
- font-weight: bold;
- background-color: #FFCA7D;
- color: #000; }
- div.pagination.viciao2k3 span.disabled {
- padding: 2px 5px 2px 5px;
- margin-right: 2px;
- border: 1px solid #ccc;
- color: #ccc; }
-
-div.pagination.yahoo {
- padding: 3px;
- margin: 3px;
- text-align: center; }
- div.pagination.yahoo a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #fff;
- text-decoration: underline;
- color: #000099; }
- div.pagination.yahoo a:hover {
- border: 1px solid #000099;
- color: #000; }
- div.pagination.yahoo a:active {
- border: 1px solid #000099;
- color: #f00; }
- div.pagination.yahoo span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #fff;
- font-weight: bold;
- background-color: #fff;
- color: #000; }
- div.pagination.yahoo span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- border: 1px solid #EEE;
- color: #DDD; }
-
-div.pagination.yellow {
- font-size: 11px;
- font-family: Tahoma, Arial, Helvetica, Sans-serif;
- padding: 2px;
- background-color: #c1c1c1; }
- div.pagination.yellow a {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #c1c1c1;
- text-decoration: none;
- color: #000; }
- div.pagination.yellow a:hover, div.pagination.yellow a:active {
- background-color: #99ffff;
- color: #000; }
- div.pagination.yellow span.current {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- font-weight: bold;
- background-color: #fff;
- color: #303030; }
- div.pagination.yellow span.disabled {
- padding: 2px 5px 2px 5px;
- margin: 2px;
- background-color: #c1c1c1;
- color: #797979; }
-
-div.pagination.youtube {
- font-family: Arial, Helvetica, sans-serif;
- font-size: 13px;
- text-align: right;
- padding: 4px 6px 4px 0;
- background-color: #cecfce;
- border-top: 1px dotted #9c9a9c;
- color: #313031; }
- div.pagination.youtube a {
- font-weight: bold;
- color: #0030ce;
- text-decoration: underline;
- padding: 1px 3px 1px 3px;
- margin: 0 1px 0 1px; }
- div.pagination.youtube span.current {
- padding: 1px 2px 1px 2px;
- color: #000;
- background-color: #fff; }
- div.pagination.youtube span.disabled {
- display: none; }
+.pagination { margin-top: 20px; float: right; }
+
+.pagination.badoo { background-color: #fff; color: #48b9ef; padding: 10px 0 10px 0; font-family: Arial, Helvetica, sans-serif; font-size: 13px; text-align: center; }
+.pagination.badoo a { color: #48b9ef; padding: 2px 5px; margin: 0 2px; text-decoration: none; border: 2px solid #f0f0f0; }
+.pagination.badoo a:hover, .pagination.badoo a:active { border: 2px solid #ff5a00; color: #ff5a00; }
+.pagination.badoo span.current { padding: 2px 5px; border: 2px solid #ff5a00; color: #fff; font-weight: bold; background-color: #ff6c16; }
+.pagination.badoo span.disabled { display: none; }
+
+.pagination.black_red { font-size: 11px; font-family: Tahoma, Arial, Helvetica, Sans-serif; background-color: #3e3e3e; color: #fff; }
+.pagination.black_red a { padding: 2px 5px 2px 5px; margin: 2px; background-color: #3e3e3e; text-decoration: none; color: #fff; }
+.pagination.black_red a:hover, .pagination.black_red a:active { background-color: #ec5210; color: #fff; }
+.pagination.black_red span.current { padding: 2px 5px 2px 5px; margin: 2px; font-weight: bold; background-color: #313131; color: #fff; }
+.pagination.black_red span.disabled { padding: 2px 5px 2px 5px; margin: 2px; background-color: #3e3e3e; color: #868686; }
+
+.pagination.blue { padding: 3px; margin: 3px; text-align: center; }
+.pagination.blue a { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #EEE; text-decoration: none; color: #036CB4; }
+.pagination.blue a:hover, .pagination.blue a:active { border: 1px solid #999; color: #666; }
+.pagination.blue .current { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #036CB4; font-weight: bold; background-color: #036CB4; color: #FFF; }
+.pagination.blue .disabled { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #EEE; color: #DDD; }
+
+.pagination.digg { padding: 3px; margin: 3px; text-align: center; }
+.pagination.digg a { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #AAAADD; text-decoration: none; color: #000099; }
+.pagination.digg a:hover, .pagination.digg div.digg a:active { border: 1px solid #000099; color: #000; }
+.pagination.digg span.current { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #000099; font-weight: bold; background-color: #000099; color: #FFF; }
+.pagination.digg span.disabled { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #EEE; color: #DDD; }
+
+.pagination.flickr { padding: 3px; margin: 3px; text-align: center; }
+.pagination.flickr a { border: 1px solid #dedfde; margin-right: 3px; padding: 2px 6px; background-position: bottom; text-decoration: none; color: #0061de; }
+.pagination.flickr a:hover, .pagination.flickr a:active { border: 1px solid #000; background-image: none; background-color: #0061de; color: #fff; }
+.pagination.flickr span.current { margin-right: 3px; padding: 2px 6px; font-weight: bold; color: #ff0084; }
+.pagination.flickr span.disabled { margin-right: 3px; padding: 2px 6px; color: #adaaad; }
+
+.pagination.gray { padding: 3px; margin: 3px; text-align: center; }
+.pagination.gray a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #ddd; text-decoration: none; color: #aaa; }
+.pagination.gray a:hover, .pagination.gray a:active { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #a0a0a0; }
+.pagination.gray span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #e0e0e0; font-weight: bold; background-color: #f0f0f0; color: #aaa; }
+.pagination.gray span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #f3f3f3; color: #ccc; }
+
+div.pagination.gray2 { font-size: 11px; font-family: Tahoma, Arial, Helvetica, Sans-serif; padding: 2px; background-color: #c1c1c1; }
+div.pagination.gray2 a { padding: 2px 5px 2px 5px; margin: 2px; background-color: #c1c1c1; text-decoration: none; color: #000; }
+div.pagination.gray2 a:hover, div.pagination.gray2 a:active { background-color: #99ffff; color: #000; }
+div.pagination.gray2 span.current { padding: 2px 5px 2px 5px; margin: 2px; font-weight: bold; background-color: #fff; color: #303030; }
+div.pagination.gray2 span.disabled { padding: 2px 5px 2px 5px; margin: 2px; background-color: #c1c1c1; color: #797979; }
+
+div.pagination.green { padding: 3px; margin: 3px; text-align: center; }
+div.pagination.green a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #ddd; text-decoration: none; color: #88AF3F; }
+div.pagination.green a:hover, div.pagination.green a:active { border: 1px solid #85BD1E; color: #638425; background-color: #F1FFD6; }
+div.pagination.green span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #B2E05D; font-weight: bold; background-color: #B2E05D; color: #FFF; }
+div.pagination.green span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #f3f3f3; color: #ccc; }
+
+div.pagination.green_black { padding: 3px; margin: 3px; text-align: center; }
+div.pagination.green_black a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #2C2C2C; text-decoration: none; color: #fff; background: #2C2C2C url(/images/paging/green_black_bg1.gif); }
+div.pagination.green_black a:hover, div.pagination.green_black a:active { border: 1px solid #AAD83E; color: #FFF; background: #AAD83E url(/images/paging/green_black_bg2.gif); }
+div.pagination.green_black span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #AAD83E; font-weight: bold; background: #AAD83E url(/images/paging/green_black_bg2.gif); color: #FFF; }
+div.pagination.green_black span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #f3f3f3; color: #ccc; }
+
+div.pagination.jogger { font-family: "Lucida Sans Unicode" "Lucida Grande" LucidaGrande "Lucida Sans" Geneva Verdana sans-serif; padding: 2px; margin: 7px; }
+div.pagination.jogger a { margin: 2px; padding: 0.5em 0.64em 0.43em 0.64em; background-color: #ee4e4e; text-decoration: none; color: #fff; }
+div.pagination.jogger a:hover, div.pagination.jogger a:active { padding: 0.5em 0.64em 0.43em 0.64em; margin: 2px; background-color: #de1818; color: #fff; }
+div.pagination.jogger span.current { padding: 0.5em 0.64em 0.43em 0.64em; margin: 2px; background-color: #f6efcc; color: #6d643c; }
+div.pagination.jogger span.disabled { display: none; }
+
+.pagination.megas { text-align: center; }
+.pagination.megas a { border: 1px solid #dedfde; margin-right: 3px; padding: 2px 6px; background-position: bottom; text-decoration: none; color: #99210B; }
+.pagination.megas a:hover, .pagination.megas a:active { border: 1px solid #000; background-color: #777777; color: #fff; }
+.pagination.megas span.current { margin-right: 3px; padding: 2px 6px; font-weight: bold; color: #99210B; }
+.pagination.megas span.disabled { margin-right: 3px; padding: 2px 6px; color: #adaaad; }
+
+div.pagination.meneame { padding: 3px; margin: 3px; text-align: center; color: #ff6500; font-size: 80%; }
+div.pagination.meneame a { border: 1px solid #ff9600; margin-right: 3px; padding: 5px 7px; background-image: url(/images/paging/meneame_bg.jpg); background-position: bottom; text-decoration: none; color: #ff6500; }
+div.pagination.meneame a:hover, div.pagination.meneame a:active { border: 1px solid #ff9600; background-image: none; background-color: #ffc794; color: #ff6500; }
+div.pagination.meneame span.current { margin-right: 3px; padding: 5px 7px; border: 1px solid #ff6500; font-weight: bold; background-color: #ffbe94; color: #ff6500; }
+div.pagination.meneame span.disabled { margin-right: 3px; padding: 5px 7px; border: 1px solid #ffe3c6; color: #ffe3c6; }
+
+div.pagination.mis_algoritmos { text-align: center; padding: 7px; margin: 3px; }
+div.pagination.mis_algoritmos a { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #000000; text-decoration: none; color: #000000; }
+div.pagination.mis_algoritmos a:hover, div.pagination.mis_algoritmos a:active { border: 1px solid #000000; background-color: #000000; color: #fff; }
+div.pagination.mis_algoritmos span.current { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #000000; font-weight: bold; background-color: #000000; color: #FFF; }
+div.pagination.mis_algoritmos span.disabled { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #EEE; color: #DDD; }
+
+div.pagination.msdn { background-color: #fff; color: #48b9ef; padding: 10px 0 10px 0; font-family: Arial Helvetica sans-serif; font-size: 13px; text-align: center; }
+div.pagination.msdn a { color: #48b9ef; padding: 2px 5px; margin: 0 2px; text-decoration: none; border: 2px solid #f0f0f0; }
+div.pagination.msdn a:hover, div.pagination.msdn a:active { border: 2px solid #ff5a00; color: #ff5a00; }
+div.pagination.msdn span.current { padding: 2px 5px; border: 2px solid #ff5a00; color: #fff; font-weight: bold; background-color: #ff6c16; }
+div.pagination.msdn span.disabled { display: none; }
+
+div.pagination.new_yahoo { padding: 3px; margin: 3px; text-align: center; font-family: TahomaHelveticasans-serif; font-size: .85em; }
+div.pagination.new_yahoo a { border: 1px solid #ccdbe4; margin-right: 3px; padding: 2px 8px; background-position: bottom; text-decoration: none; color: #0061de; }
+div.pagination.new_yahoo a:hover, div.pagination.new_yahoo a:active { border: 1px solid #2b55af; background-image: none; background-color: #3666d4; color: #fff; }
+div.pagination.new_yahoo span.current { margin-right: 3px; padding: 2px 6px; font-weight: bold; color: #000; }
+div.pagination.new_yahoo a.next { border: 2px solid #ccdbe4; margin: 0 0 0 10px; }
+div.pagination.new_yahoo a.next:hover { border: 2px solid #2b55af; }
+div.pagination.new_yahoo a.prev { border: 2px solid #ccdbe4; margin: 0 10px 0 0; }
+div.pagination.new_yahoo a.prev:hover { border: 2px solid #2b55af; }
+
+div.pagination.on_black { padding: 3px; margin: 3px; text-align: center; color: #a0a0a0; font-size: 80%; }
+div.pagination.on_black a { border: 1px solid #909090; margin-right: 3px; padding: 2px 5px; background-image: url(/images/paging/onblack_bg1.gif); background-position: bottom; text-decoration: none; color: #c0c0c0; }
+div.pagination.on_black a:hover, div.pagination.on_black a:active { border: 1px solid #f0f0f0; background-image: url(/images/paging/onblack_bg2.gif); background-color: #404040; color: #ffffff; }
+div.pagination.on_black span.current { margin-right: 3px; padding: 2px 5px; border: 1px solid #ffffff; font-weight: bold; background-color: #606060; color: #ffffff; }
+div.pagination.on_black span.disabled { margin-right: 3px; padding: 2px 5px; border: 1px solid #606060; color: #808080; }
+
+div.pagination.sabros { padding: 3px; margin: 3px; text-align: center; }
+div.pagination.sabros a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #9aafe5; text-decoration: none; color: #2e6ab1; }
+div.pagination.sabros a:hover, div.pagination.sabros a:active { border: 1px solid #2b66a5; color: #000; background-color: lightyellow; }
+div.pagination.sabros span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid navy; font-weight: bold; background-color: #2e6ab1; color: #FFF; }
+div.pagination.sabros span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #929292; color: #929292; }
+
+div.pagination.technorati { padding: 3px; margin: 3px; text-align: center; }
+div.pagination.technorati a { border: 1px solid #ccc; margin-right: 3px; padding: 2px 6px; background-position: bottom; text-decoration: none; font-weight: bold; color: rgb(66,97,222); }
+div.pagination.technorati a:hover, div.pagination.technorati a:active { background-image: none; background-color: #4261DF; color: #fff; }
+div.pagination.technorati span.current { margin-right: 3px; padding: 2px 6px; font-weight: bold; color: #000; }
+div.pagination.technorati span.disabled { display: none; }
+
+div.pagination.tres { text-align: center; padding: 7px; margin: 3px; font-family: Arial, Helvetica, sans-serif; font-size: 13.2pt; font-weight: bold; }
+div.pagination.tres a { padding: 2px 5px 2px 5px; margin: 2px; border: 2px solid #d9d300; text-decoration: none; color: #fff; background-color: #d90; }
+div.pagination.tres a:hover, div.pagination.tres a:active { border: 2px solid #ff0; background-color: #ff0; color: #000; }
+div.pagination.tres span.current { padding: 2px 5px 2px 5px; margin: 2px; border: 2px solid #fff; font-weight: bold; color: #000; }
+div.pagination.tres span.disabled { display: none; }
+
+div.pagination.viciao2k3 { margin-top: 20px; margin-bottom: 10px; }
+div.pagination.viciao2k3 a { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #8DB5D7; text-decoration: none; color: #000; }
+div.pagination.viciao2k3 a:hover, div.pagination.viciao2k3 a:active { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid red; }
+div.pagination.viciao2k3 span.current { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #E89954; font-weight: bold; background-color: #FFCA7D; color: #000; }
+div.pagination.viciao2k3 span.disabled { padding: 2px 5px 2px 5px; margin-right: 2px; border: 1px solid #ccc; color: #ccc; }
+
+div.pagination.yahoo { padding: 3px; margin: 3px; text-align: center; }
+div.pagination.yahoo a { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #fff; text-decoration: underline; color: #000099; }
+div.pagination.yahoo a:hover { border: 1px solid #000099; color: #000; }
+div.pagination.yahoo a:active { border: 1px solid #000099; color: #f00; }
+div.pagination.yahoo span.current { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #fff; font-weight: bold; background-color: #fff; color: #000; }
+div.pagination.yahoo span.disabled { padding: 2px 5px 2px 5px; margin: 2px; border: 1px solid #EEE; color: #DDD; }
+
+div.pagination.yellow { font-size: 11px; font-family: Tahoma, Arial, Helvetica, Sans-serif; padding: 2px; background-color: #c1c1c1; }
+div.pagination.yellow a { padding: 2px 5px 2px 5px; margin: 2px; background-color: #c1c1c1; text-decoration: none; color: #000; }
+div.pagination.yellow a:hover, div.pagination.yellow a:active { background-color: #99ffff; color: #000; }
+div.pagination.yellow span.current { padding: 2px 5px 2px 5px; margin: 2px; font-weight: bold; background-color: #fff; color: #303030; }
+div.pagination.yellow span.disabled { padding: 2px 5px 2px 5px; margin: 2px; background-color: #c1c1c1; color: #797979; }
+
+div.pagination.youtube { font-family: Arial, Helvetica, sans-serif; font-size: 13px; text-align: right; padding: 4px 6px 4px 0; background-color: #cecfce; border-top: 1px dotted #9c9a9c; color: #313031; }
+div.pagination.youtube a { font-weight: bold; color: #0030ce; text-decoration: underline; padding: 1px 3px 1px 3px; margin: 0 1px 0 1px; }
+div.pagination.youtube span.current { padding: 1px 2px 1px 2px; color: #000; background-color: #fff; }
+div.pagination.youtube span.disabled { display: none; }
diff --git a/public/stylesheets/ie.css b/public/stylesheets/ie.css
new file mode 100644
index 0000000..267348c
--- /dev/null
+++ b/public/stylesheets/ie.css
@@ -0,0 +1,17 @@
+body { text-align: center; }
+
+.container { text-align: left; }
+
+* html .column { overflow-x: hidden; }
+
+* html legend { margin: -18px -8px 16px 0; padding: 0; }
+
+ol { margin-left: 2em; }
+
+sup { vertical-align: text-top; }
+
+sub { vertical-align: text-bottom; }
+
+html > body p code { *white-space: normal; }
+
+hr { margin: -8px auto 11px; }
diff --git a/test/fixtures/mail_incomings.yml b/test/fixtures/mail_incomings.yml
deleted file mode 100644
index 5bf0293..0000000
--- a/test/fixtures/mail_incomings.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-
-# one:
-# column: value
-#
-# two:
-# column: value
diff --git a/test/fixtures/mail_outgoings.yml b/test/fixtures/mail_outgoings.yml
deleted file mode 100644
index 5bf0293..0000000
--- a/test/fixtures/mail_outgoings.yml
+++ /dev/null
@@ -1,7 +0,0 @@
-# Read about fixtures at http://ar.rubyonrails.org/classes/Fixtures.html
-
-# one:
-# column: value
-#
-# two:
-# column: value
diff --git a/test/functional/sessions_controller_test.rb b/test/functional/sessions_controller_test.rb
index 3115d0f..e082bd0 100644
--- a/test/functional/sessions_controller_test.rb
+++ b/test/functional/sessions_controller_test.rb
@@ -1,85 +1,90 @@
require File.dirname(__FILE__) + '/../test_helper'
require 'sessions_controller'
# Re-raise errors caught by the controller.
class SessionsController; def rescue_action(e) raise e end; end
class SessionsControllerTest < Test::Unit::TestCase
# Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
# Then, you can remove it from this and the units test.
include AuthenticatedTestHelper
fixtures :users
def setup
@controller = SessionsController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_should_login_and_redirect
- post :create, :login => 'quentin', :password => 'test'
+ post :create, :login => {:username => "quentin", :password => "test"}
+
assert session[:user_id]
assert_response :redirect
end
def test_should_fail_login_and_not_redirect
- post :create, :login => 'quentin', :password => 'bad password'
+ post :create, :login => {:username => "quentin", :password => "bad password"}
+
assert_nil session[:user_id]
assert_response :success
end
def test_should_logout
login_as :quentin
get :destroy
+
assert_nil session[:user_id]
assert_response :redirect
end
def test_should_remember_me
- post :create, :login => 'quentin', :password => 'test', :remember_me => "1"
+ post :create, :login => {:username => "quentin", :password => "test", :remember_me => "1"}
+
assert_not_nil @response.cookies["auth_token"]
end
def test_should_not_remember_me
- post :create, :login => 'quentin', :password => 'test', :remember_me => "0"
+ post :create, :login => {:username => "quentin", :password => "test", :remember_me => "0"}
+
assert_nil @response.cookies["auth_token"]
end
def test_should_delete_token_on_logout
login_as :quentin
get :destroy
assert_equal @response.cookies["auth_token"], []
end
def test_should_login_with_cookie
users(:quentin).remember_me
@request.cookies["auth_token"] = cookie_for(:quentin)
get :new
assert @controller.send(:logged_in?)
end
def test_should_fail_expired_cookie_login
users(:quentin).remember_me
users(:quentin).update_attribute :remember_token_expires_at, 5.minutes.ago
@request.cookies["auth_token"] = cookie_for(:quentin)
get :new
assert [email protected](:logged_in?)
end
def test_should_fail_cookie_login
users(:quentin).remember_me
@request.cookies["auth_token"] = auth_token('invalid_auth_token')
get :new
assert [email protected](:logged_in?)
end
protected
def auth_token(token)
CGI::Cookie.new('name' => 'auth_token', 'value' => token)
end
def cookie_for(user)
auth_token users(user).remember_token
end
end
diff --git a/test/functional/users_controller_test.rb b/test/functional/users_controller_test.rb
index daf7ff9..be7d425 100644
--- a/test/functional/users_controller_test.rb
+++ b/test/functional/users_controller_test.rb
@@ -1,86 +1,87 @@
require File.dirname(__FILE__) + '/../test_helper'
require 'users_controller'
# Re-raise errors caught by the controller.
class UsersController; def rescue_action(e) raise e end; end
class UsersControllerTest < Test::Unit::TestCase
# Be sure to include AuthenticatedTestHelper in test/test_helper.rb instead
# Then, you can remove it from this and the units test.
include AuthenticatedTestHelper
fixtures :users
def setup
@controller = UsersController.new
@request = ActionController::TestRequest.new
@response = ActionController::TestResponse.new
end
def test_should_allow_signup
assert_difference 'User.count' do
create_user
assert_response :redirect
end
end
def test_should_require_login_on_signup
assert_no_difference 'User.count' do
create_user(:login => nil)
assert assigns(:user).errors.on(:login)
assert_response :success
end
end
def test_should_require_password_on_signup
assert_no_difference 'User.count' do
create_user(:password => nil)
assert assigns(:user).errors.on(:password)
assert_response :success
end
end
def test_should_require_password_confirmation_on_signup
assert_no_difference 'User.count' do
create_user(:password_confirmation => nil)
assert assigns(:user).errors.on(:password_confirmation)
assert_response :success
end
end
def test_should_require_email_on_signup
assert_no_difference 'User.count' do
create_user(:email => nil)
assert assigns(:user).errors.on(:email)
assert_response :success
end
end
def test_should_activate_user
+ AppConfig.require_email_activation = true
assert_nil User.authenticate('aaron', 'test')
- get :activate, :activation_code => users(:aaron).activation_code
+ get :activate, :id => users(:aaron).activation_code
assert_redirected_to '/'
assert_not_nil flash[:notice]
assert_equal users(:aaron), User.authenticate('aaron', 'test')
end
def test_should_not_activate_user_without_key
get :activate
assert_nil flash[:notice]
rescue ActionController::RoutingError
# in the event your routes deny this, we'll just bow out gracefully.
end
def test_should_not_activate_user_with_blank_key
get :activate, :activation_code => ''
assert_nil flash[:notice]
rescue ActionController::RoutingError
# well played, sir
end
protected
def create_user(options = {})
post :create, :user => { :login => 'quire', :email => '[email protected]',
:password => 'quire', :password_confirmation => 'quire' }.merge(options)
end
end
diff --git a/vendor/plugins/haml/init.rb b/vendor/plugins/haml/init.rb
new file mode 100644
index 0000000..d0c8798
--- /dev/null
+++ b/vendor/plugins/haml/init.rb
@@ -0,0 +1,7 @@
+begin
+ require File.join(File.dirname(__FILE__), 'lib', 'haml') # From here
+rescue LoadError
+ require 'haml' # From gem
+end
+
+Haml.init_rails(binding)
|
jcnetdev/yubnub
|
9dbbc4cc0706054361cb416864f5322a26a34b24
|
Updating
|
diff --git a/config/database.yml b/config/database.yml
index e0b81f7..8bb32f0 100644
--- a/config/database.yml
+++ b/config/database.yml
@@ -1,42 +1,42 @@
# MySQL (default setup). Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql
# On Mac OS X:
# sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
# On Mac OS X Leopard:
# sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
# This sets the ARCHFLAGS environment variable to your native architecture
# On Windows:
# gem install mysql
# Choose the win32 build.
# Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql
encoding: utf8
- database: blank_development
+ host: localhost
+ database: base_development
username: root
password:
- host: localhost
# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
encoding: utf8
- database: blank_test
+ host: localhost
+ database: base_test
username: root
password:
- host: localhost
production:
adapter: mysql
encoding: utf8
- database: blank_production
+ host: localhost
+ database: base_production
username: root
password:
- host: localhost
diff --git a/config/environment.rb b/config/environment.rb
index 22c5d18..61e2bc3 100644
--- a/config/environment.rb
+++ b/config/environment.rb
@@ -1,199 +1,207 @@
# Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '>= 2.1.0' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use (only works if using vendor/rails).
# To use Rails without a database, you must remove the Active Record framework
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_blank_session',
:secret => 'd27cc7f3bae1ef15fa00a9fad245f42057cff6113327d732a4dbd8e43c3eaba1a5bda246f882029653b71266c2015ef38ff4ce67616d8a0b2c220884edaba8c7'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with 'rake db:sessions:create')
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
# Make Active Record use UTC-base instead of local time
# config.active_record.default_timezone = :utc
+ # standard gems
+ config.gem "haml", :version => ">= 2.0.0"
+
+ # ssl_requirement
+ # ------
+ # Allow controller actions to force SSL on specific parts of the site
+ # ------
+ config.gem 'jcnetdev-ssl_requirement', :version => '>= 1.0',
+ :lib => 'ssl_requirement',
+ :source => 'http://gems.github.com'
+
+ # exception_notification
+ # ------
+ # Allows unhandled exceptions to be emailed on production
+ # ------
+ config.gem 'jcnetdev-exception_notification', :version => '>= 1.1',
+ :lib => 'exception_notification',
+ :source => 'http://gems.github.com'
+
+
# Rails Plugins (via gems)
# active_record_without_table
# ------
# Allows creation of ActiveRecord models that work without any database backend
# ------
config.gem 'jcnetdev-active_record_without_table', :version => '>= 1.1',
:lib => 'active_record_without_table',
:source => 'http://gems.github.com'
# acts_as_state_machine
# ------
# Allows ActiveRecord models to define states and transition actions between them
# ------
config.gem 'jcnetdev-acts_as_state_machine', :version => '>= 2.1.0',
:lib => 'acts_as_state_machine',
:source => 'http://gems.github.com'
# app_config
# ------
# Allow application wide configuration settings via YML files
# ------
config.gem 'jcnetdev-app_config', :version => '>= 1.0',
:lib => 'app_config',
:source => 'http://gems.github.com'
# auto_migrations
# ------
# Allows migrations to be run automatically based on updating the schema.rb
# ------
config.gem 'jcnetdev-auto_migrations', :version => '>= 1.1',
:lib => 'auto_migrations',
:source => 'http://gems.github.com'
-
+
# better_partials
# ------
# Makes calling partials in views look better and more fun
# ------
config.gem 'jcnetdev-better_partials', :version => '>= 1.0',
:lib => 'better_partials',
:source => 'http://gems.github.com'
- # exception_notification
- # ------
- # Allows unhandled exceptions to be emailed on production
- # ------
- config.gem 'jcnetdev-exception_notification', :version => '>= 1.0',
- :lib => 'exception_notification',
- :source => 'http://gems.github.com'
# form_fu
# ------
# Allows easier rails form creation and processing
# ------
- config.gem 'neorails-form_fu', :version => '>= 1.0',
- :lib => 'form_fu',
- :source => 'http://gems.github.com'
+ # config.gem 'neorails-form_fu', :version => '>= 1.0',
+ # :lib => 'form_fu',
+ # :source => 'http://gems.github.com'
# paperclip
# ------
# Allows easy uploading of files with no dependencies
# ------
config.gem 'jcnetdev-paperclip', :version => '>= 1.0',
:lib => 'paperclip',
:source => 'http://gems.github.com'
# seed-fu
# ------
# Allows easier database seeding of tables
# ------
config.gem 'jcnetdev-seed-fu', :version => '>= 1.0',
:lib => 'seed-fu',
:source => 'http://gems.github.com'
+
+
# subdomain-fu
# ------
# Allows easier subdomain selection
# ------
config.gem 'jcnetdev-subdomain-fu', :version => '>= 0.0.2',
:lib => 'subdomain-fu',
:source => 'http://gems.github.com'
# validates_as_email_address
# ------
# Allows for easy format validation of email addresses
# ------
config.gem 'jcnetdev-validates_as_email_address', :version => '>= 1.0',
:lib => 'validates_as_email_address',
:source => 'http://gems.github.com'
# will_paginate
# ------
# Allows nice and easy pagination
# ------
config.gem 'jcnetdev-will_paginate', :version => '>= 2.3.2',
:lib => 'will_paginate',
:source => 'http://gems.github.com'
# view_fu
# ------
# Adds view helpers for titles, stylesheets, javascripts, and common tags
# ------
- config.gem 'neorails-view_fu', :version => '>= 1.0',
- :lib => 'view_fu',
- :source => 'http://gems.github.com'
+ # config.gem 'neorails-view_fu', :version => '>= 1.0',
+ # :lib => 'view_fu',
+ # :source => 'http://gems.github.com'
# OPTIONAL PLUGINS
# acts_as_list
# ------
# Allows ActiveRecord Models to be easily ordered via position attributes
# ------
# config.gem 'jcnetdev-acts_as_list', :version => '>= 1.0',
# :lib => 'acts_as_list',
# :source => 'http://gems.github.com'
# acts-as-readable
# ------
# Allows ActiveRecord Models to be easily marked as read / unread
# ------
# config.gem 'jcnetdev-acts-as-readable', :version => '>= 1.0',
# :lib => 'acts_as_readable',
# :source => 'http://gems.github.com'
- # ssl_requirement
- # ------
- # Allow controller actions to force SSL on specific parts of the site
- # ------
- # config.gem 'jcnetdev-ssl_requirement', :version => '>= 1.0',
- # :lib => 'ssl_requirement',
- # :source => 'http://gems.github.com'
# sms-fu
# ------
# Send SMS messages easily
# ------
# config.gem 'jcnetdev-sms-fu', :version => '>= 1.0',
# :lib => 'sms_fu',
# :source => 'http://gems.github.com'
end
diff --git a/db/fixtures/SEED_FILES_GO_HERE b/db/fixtures/SEED_FILES_GO_HERE
new file mode 100644
index 0000000..e69de29
diff --git a/db/migrate/001_create_mail_outgoing.rb b/db/migrate/001_create_mail_outgoing.rb
deleted file mode 100644
index 3bec897..0000000
--- a/db/migrate/001_create_mail_outgoing.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-class CreateMailOutgoing < ActiveRecord::Migration
- def self.up
- create_table :mail_outgoing do |t|
- t.string :from
- t.string :to
- t.integer :last_send_attempt, :default => 0
- t.text :mail
- t.datetime :created_on
- end
- end
-
- def self.down
- drop_table :mail_outgoing
- end
-end
diff --git a/db/migrate/002_create_mail_incoming.rb b/db/migrate/002_create_mail_incoming.rb
deleted file mode 100644
index 5f35cce..0000000
--- a/db/migrate/002_create_mail_incoming.rb
+++ /dev/null
@@ -1,12 +0,0 @@
-class CreateMailIncoming < ActiveRecord::Migration
- def self.up
- create_table :mail_incoming do |t|
- t.text :mail
- t.datetime :created_on
- end
- end
-
- def self.down
- drop_table :mail_incoming
- end
-end
diff --git a/db/migrate/003_create_users.rb b/db/migrate/003_create_users.rb
deleted file mode 100644
index fad890c..0000000
--- a/db/migrate/003_create_users.rb
+++ /dev/null
@@ -1,22 +0,0 @@
-class CreateUsers < ActiveRecord::Migration
- def self.up
- create_table "users", :force => true do |t|
- t.column :login, :string
- t.column :email, :string
- t.column :crypted_password, :string, :limit => 40
- t.column :salt, :string, :limit => 40
- t.column :created_at, :datetime
- t.column :updated_at, :datetime
- t.column :remember_token, :string
- t.column :remember_token_expires_at, :datetime
- t.column :activation_code, :string, :limit => 40
- t.column :activated_at, :datetime
- t.column :state, :string, :null => :no, :default => 'passive'
- t.column :deleted_at, :datetime
- end
- end
-
- def self.down
- drop_table "users"
- end
-end
diff --git a/db/migrate/004_create_widgets.rb b/db/migrate/004_create_widgets.rb
deleted file mode 100644
index 580f7aa..0000000
--- a/db/migrate/004_create_widgets.rb
+++ /dev/null
@@ -1,15 +0,0 @@
-class CreateWidgets < ActiveRecord::Migration
- def self.up
- create_table :widgets do |t|
- t.string :name
- t.decimal :price
- t.text :description
- t.boolean :is_in_stock
- t.timestamps
- end
- end
-
- def self.down
- drop_table :widgets
- end
-end
diff --git a/db/schema.rb b/db/schema.rb
index 74a2e21..f19b9c8 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -1,51 +1,56 @@
# This file is auto-generated from the current state of the database. Instead of editing this file,
-# please use the migrations feature of ActiveRecord to incrementally modify your database, and
+# please use the migrations feature of Active Record to incrementally modify your database, and
# then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your database schema. If you need
# to create the application database on another system, you should be using db:schema:load, not running
# all the migrations from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended to check this file into your version control system.
-ActiveRecord::Schema.define(:version => 4) do
+ActiveRecord::Schema.define(:version => 1) do
create_table "mail_incoming", :force => true do |t|
t.text "mail"
t.datetime "created_on"
end
create_table "mail_outgoing", :force => true do |t|
t.string "from"
t.string "to"
- t.integer "last_send_attempt", :default => 0
+ t.integer "last_send_attempt", :limit => 11, :default => 0
t.text "mail"
t.datetime "created_on"
end
create_table "users", :force => true do |t|
t.string "login"
t.string "email"
t.string "crypted_password", :limit => 40
t.string "salt", :limit => 40
t.datetime "created_at"
t.datetime "updated_at"
t.string "remember_token"
t.datetime "remember_token_expires_at"
t.string "activation_code", :limit => 40
t.datetime "activated_at"
t.string "state", :default => "passive"
t.datetime "deleted_at"
end
create_table "widgets", :force => true do |t|
t.string "name"
- t.integer "price", :limit => 10, :precision => 10, :scale => 0
+ t.integer "price", :limit => 10
t.text "description"
t.boolean "is_in_stock"
t.datetime "created_at"
t.datetime "updated_at"
end
+ create_table :photos, :force => true do |t|
+ t.string "url"
+ t.timestamps
+ end
+
end
diff --git a/lib/tasks/auto_migrations_tasks.rake b/lib/tasks/auto_migrations_tasks.rake
index 4d32acd..2ea0034 100644
--- a/lib/tasks/auto_migrations_tasks.rake
+++ b/lib/tasks/auto_migrations_tasks.rake
@@ -1,15 +1,16 @@
namespace :db do
namespace :auto do
desc "Use schema.rb to auto-migrate"
- task :migrate => :environment do
+ task :migrate do
AutoMigrations.run
end
end
namespace :schema do
desc "Create migration from schema.rb"
- task :to_migration => :environment do
+ task :to_migration do
AutoMigrations.schema_to_migration
end
end
-end
\ No newline at end of file
+end
+
diff --git a/lib/tasks/migrate.rake b/lib/tasks/migrate.rake
new file mode 100644
index 0000000..46c8ea7
--- /dev/null
+++ b/lib/tasks/migrate.rake
@@ -0,0 +1,17 @@
+require 'rubygems'
+require 'rake'
+
+class Rake::Task
+ def overwrite(&block)
+ @actions.clear
+ enhance(&block)
+ end
+end
+
+# Overwrite migrate task
+Rake::Task["db:migrate"].overwrite do
+ puts "Running Auto Migration and DB Seed..."
+
+ Rake::Task["db:auto:migrate"].invoke
+ Rake::Task["db:seed"].invoke
+end
\ No newline at end of file
diff --git a/lib/tasks/paperclip_tasks.rake b/lib/tasks/paperclip_tasks.rake
index 64b7310..c4f1673 100644
--- a/lib/tasks/paperclip_tasks.rake
+++ b/lib/tasks/paperclip_tasks.rake
@@ -1,38 +1,38 @@
def obtain_class
class_name = ENV['CLASS'] || ENV['class']
raise "Must specify CLASS" unless class_name
@klass = Object.const_get(class_name)
end
def obtain_attachments
name = ENV['ATTACHMENT'] || ENV['attachment']
raise "Class #{@klass.name} has no attachments specified" unless @klass.respond_to?(:attachment_definitions)
if !name.blank? && @klass.attachment_definitions.keys.include?(name)
[ name ]
else
@klass.attachment_definitions.keys
end
end
namespace :paperclip do
desc "Regenerates thumbnails for a given CLASS (and optional ATTACHMENT)"
- task :refresh => :environment do
+ task :refresh do
klass = obtain_class
names = obtain_attachments
instances = klass.find(:all)
puts "Regenerating thumbnails for #{instances.length} instances of #{klass.name}:"
instances.each do |instance|
names.each do |name|
result = if instance.send("#{ name }?")
instance.send(name).reprocess!
instance.send(name).save
else
true
end
print result ? "." : "x"; $stdout.flush
end
end
puts " Done."
end
end
diff --git a/lib/tasks/seed_fu_tasks.rake b/lib/tasks/seed_fu_tasks.rake
index 56efa73..54af5ca 100644
--- a/lib/tasks/seed_fu_tasks.rake
+++ b/lib/tasks/seed_fu_tasks.rake
@@ -1,15 +1,15 @@
namespace :db do
desc "Loads seed data from db/fixtures for the current environment."
- task :seed => :environment do
+ task :seed do
Dir[File.join(RAILS_ROOT, 'db', 'fixtures', '*.rb')].sort.each { |fixture|
puts "\n== Seeding from #{File.split(fixture).last} " + ("=" * (60 - (17 + File.split(fixture).last.length)))
load fixture
puts "=" * 60 + "\n"
}
Dir[File.join(RAILS_ROOT, 'db', 'fixtures', RAILS_ENV, '*.rb')].sort.each { |fixture|
puts "\n== [#{RAILS_ENV}] Seeding from #{File.split(fixture).last} " + ("=" * (60 - (20 + File.split(fixture).last.length + RAILS_ENV.length)))
load fixture
puts "=" * 60 + "\n"
}
end
-end
\ No newline at end of file
+end
diff --git a/log/development.log b/log/development.log
index 644e0bc..67a5dae 100644
--- a/log/development.log
+++ b/log/development.log
@@ -3860,512 +3860,519 @@ Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mSQL (0.000675)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.17206 (5 reqs/sec) | DB: 0.08513 (49%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:47:09) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtzIGZvciBzaWduaW5n%0AIHVwIQY6CkB1c2VkewY7B1Q6DnJldHVybl90bzA%3D--66377d90710a9e737ea1ae56712acd9ca2057958
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001127)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004054)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.02166 (46 reqs/sec) | Rendering: 0.00988 (45%) | DB: 0.00518 (23%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:47:28) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--dcec315596d36623cb843160e09b73d04f5abeef
Parameters: {"action"=>"new", "controller"=>"users"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000229)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000178)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mUser Columns (0.003302)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00132)
Completed in 0.09237 (10 reqs/sec) | Rendering: 0.07603 (82%) | DB: 0.00371 (4%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:47:36) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--4d7f9c359fb30618422f243f6b8fb88244fcf536
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdfasdf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mUser Columns (0.005989)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000292)[0m [0;1mBEGIN[0m
[4;35;1mUser Load (0.002568)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdfasdf') LIMIT 1[0m
[4;36;1mUser Load (0.002660)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;35;1mSQL (0.000306)[0m [0mROLLBACK[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00044)
Completed in 0.03907 (25 reqs/sec) | Rendering: 0.01061 (27%) | DB: 0.01182 (30%) | 200 OK [http://127.0.0.1/users]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:47:38) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--4d7f9c359fb30618422f243f6b8fb88244fcf536
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdfasdfsfadsf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;36;1mUser Columns (0.004120)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.000193)[0m [0mBEGIN[0m
[4;36;1mUser Load (0.001378)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdfasdfsfadsf') LIMIT 1[0m
[4;35;1mUser Load (0.001245)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;36;1mUser Create (0.000351)[0m [0;1mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('bd0f63fda26bbdb9103dde45811ad6b30d61e515', NULL, '2008-01-12 06:47:38', '8a7e5095b7a2ad1c204eef7f7505b808947c942f', NULL, NULL, NULL, NULL, 'asdfasdfasdfasdfsfadsf', '2008-01-12 06:47:38', '[email protected]', 'passive')[0m
[4;35;1mSQL (0.000780)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000343)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000424)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:47:38', `login` = 'asdfasdfasdfasdfsfadsf', `crypted_password` = '8a7e5095b7a2ad1c204eef7f7505b808947c942f', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = 'bd0f63fda26bbdb9103dde45811ad6b30d61e515', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:47:38' WHERE `id` = 17[0m
[4;36;1mSQL (0.000652)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.02754 (36 reqs/sec) | DB: 0.00949 (34%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:47:38) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--fb9ca386af4504c415c3af83cc9274ba7d85b69a
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001138)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004652)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.08185 (12 reqs/sec) | Rendering: 0.01077 (13%) | DB: 0.00579 (7%) | 200 OK [http://127.0.0.1/]
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000162)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000131)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mUser Load (0.000824)[0m [0;1mSELECT * FROM `users` LIMIT 1[0m
[4;35;1mUser Columns (0.003111)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000632)[0m [0;1mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:48:35 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: asdfasdfasdfasdf
Password:
Visit this url to activate your account:
http://127.0.0.1:3000/users//activate
[4;35;1mMailOutgoing Columns (0.003513)[0m [0mSHOW FIELDS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.000200)[0m [0;1mBEGIN[0m
[4;35;1mMailOutgoing Create (0.000370)[0m [0mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES('2008-01-12 06:48:35', 'Admin', 'Date: Sat, 12 Jan 2008 06:48:35 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: asdfasdfasdfasdf\n Password: \n\nVisit this url to activate your account:\n\n http://127.0.0.1:3000/users//activate', '[email protected]', 0)[0m
[4;36;1mSQL (0.067444)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000267)[0m [0mBEGIN[0m
[4;36;1mUser Update (0.000451)[0m [0;1mUPDATE `users` SET `created_at` = '2008-01-12 06:47:09', `login` = 'asdfasdfasdfasdf', `crypted_password` = '6cc849b8cea017d6a07505df6a40c1e8d0f1e795', `activated_at` = '2008-01-12 14:48:35', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '6207aec6a64db5f666e258454eef52585c3db827', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:48:35' WHERE `id` = 16[0m
[4;35;1mSQL (0.000605)[0m [0mCOMMIT[0m
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:20) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkGIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--624025e9b0a0a68ef9ea877e0ea518bb584e850a
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000213)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000179)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.001067)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004855)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00143)
Completed in 0.09217 (10 reqs/sec) | Rendering: 0.07852 (85%) | DB: 0.00631 (6%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:23) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--07274a905179a765a6e9b05efde30cb248ecd26a
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001091)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004559)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00064)
Completed in 0.02085 (47 reqs/sec) | Rendering: 0.00883 (42%) | DB: 0.00565 (27%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:52:31) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--6821b97074e9fa81e4e13c4be7cbb7f2901389ee
Parameters: {"action"=>"new", "controller"=>"users"}
[4;36;1mUser Columns (0.005229)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00062)
Completed in 0.03293 (30 reqs/sec) | Rendering: 0.01657 (50%) | DB: 0.00523 (15%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:52:31) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkWOg5yZXR1cm5fdG8wIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--54d3ab3cb61c831af7d7582d3cc0c1a6c8bab637
Parameters: {"action"=>"new", "controller"=>"users"}
[4;35;1mUser Columns (0.005895)[0m [0mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00055)
Completed in 0.08563 (11 reqs/sec) | Rendering: 0.06832 (79%) | DB: 0.00589 (6%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:52:39) [POST]
Session ID: BAh7CDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--6821b97074e9fa81e4e13c4be7cbb7f2901389ee
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"tony", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;36;1mUser Columns (0.005908)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.000276)[0m [0mBEGIN[0m
[4;36;1mUser Load (0.002448)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.login) = 'tony') LIMIT 1[0m
[4;35;1mUser Load (0.001944)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;36;1mUser Create (0.000579)[0m [0;1mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', NULL, '2008-01-12 06:52:39', 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', NULL, NULL, NULL, NULL, 'tony', '2008-01-12 06:52:39', '[email protected]', 'passive')[0m
[4;35;1mSQL (0.000669)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000228)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000318)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:52:39', `login` = 'tony', `crypted_password` = 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:52:39' WHERE `id` = 18[0m
[4;36;1mSQL (0.000720)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000673)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:52:39 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: tony
Password: asdf
Visit this url to activate your account:
http://127.0.0.1:3000/users//activate
[4;36;1mMailOutgoing Columns (0.003946)[0m [0;1mSHOW FIELDS FROM `mail_outgoing`[0m
[4;35;1mSQL (0.000264)[0m [0mBEGIN[0m
[4;36;1mMailOutgoing Create (0.000461)[0m [0;1mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:52:39 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: tony\n Password: asdf\n\nVisit this url to activate your account:\n\n http://127.0.0.1:3000/users//activate', '[email protected]', 0)[0m
[4;35;1mSQL (0.000957)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000268)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000533)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:52:39', `login` = 'tony', `crypted_password` = 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', `activated_at` = '2008-01-12 14:52:39', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:52:39' WHERE `id` = 18[0m
[4;36;1mSQL (0.000677)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.05774 (17 reqs/sec) | DB: 0.02087 (36%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:39) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkXOg5yZXR1cm5fdG8wIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--f05c650061a50757fdd625a3128482437ae11670
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001075)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004046)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.02023 (49 reqs/sec) | Rendering: 0.00892 (44%) | DB: 0.00512 (25%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:15) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkXIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--51c73f97178e7b6d8e1a6d392d2009106f2933e3
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000205)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000176)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.001063)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004536)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00162)
Completed in 0.08904 (11 reqs/sec) | Rendering: 0.07624 (85%) | DB: 0.00598 (6%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:54:19) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoMdXNlcl9pZGkX--f95542e9d7c74ff238c0f82008e3702d814f9559
Parameters: {"action"=>"new", "controller"=>"users"}
[4;36;1mUser Columns (0.005178)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00058)
Completed in 0.03341 (29 reqs/sec) | Rendering: 0.01739 (52%) | DB: 0.00518 (15%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:54:24) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkXIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--9528283fffbd76ce1e102f064d814ceb5e4969d1
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mUser Columns (0.003277)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000419)[0m [0;1mBEGIN[0m
[4;35;1mUser Load (0.001455)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdf') LIMIT 1[0m
[4;36;1mUser Load (0.001270)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;35;1mUser Create (0.000312)[0m [0mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('60b8af27dc41816229578ed800c2b3f3cb8bd659', NULL, '2008-01-12 06:54:24', '422eaf202dd56dda25848ade485f044a80907f90', NULL, NULL, NULL, NULL, 'asdfasdfasdf', '2008-01-12 06:54:24', '[email protected]', 'passive')[0m
[4;36;1mSQL (0.000834)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.001068)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:54:24 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: asdfasdfasdf
Password: asdf
Visit this url to activate your account:
http://127.0.0.1:3000/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate
[4;36;1mMailOutgoing Columns (0.002753)[0m [0;1mSHOW FIELDS FROM `mail_outgoing`[0m
[4;35;1mSQL (0.000190)[0m [0mBEGIN[0m
[4;36;1mMailOutgoing Create (0.000311)[0m [0;1mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:54:24 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: asdfasdfasdf\n Password: asdf\n\nVisit this url to activate your account:\n http://127.0.0.1:3000/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate\n', '[email protected]', 0)[0m
[4;35;1mSQL (0.000693)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000164)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000338)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:54:24', `login` = 'asdfasdfasdf', `crypted_password` = '422eaf202dd56dda25848ade485f044a80907f90', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = 'd625da02fdec7785875e51b7f403ef0727e8b3e5', `salt` = '60b8af27dc41816229578ed800c2b3f3cb8bd659', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:54:24' WHERE `id` = 19[0m
[4;36;1mSQL (0.000688)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.05121 (19 reqs/sec) | DB: 0.01377 (26%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:24) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsGOgtub3RpY2UiG1RoYW5rcyBmb3Igc2lnbmlu%0AZyB1cCEGOgpAdXNlZHsGOwdUOgx1c2VyX2lkaRg%3D--bc834e021d7d4946b1ab4941eba9506b02bc52de
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001495)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004227)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00079)
Completed in 0.02238 (44 reqs/sec) | Rendering: 0.00951 (42%) | DB: 0.00572 (25%) | 200 OK [http://127.0.0.1/]
Processing UsersController#activate (for 127.0.0.1 at 2008-01-12 06:54:44) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkYIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--deeb569b42f2f3c648db0d77646a3615f2b7e94e
Parameters: {"action"=>"activate", "id"=>"d625da02fdec7785875e51b7f403ef0727e8b3e5", "controller"=>"users"}
[4;35;1mUser Columns (0.005259)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mUser Load (0.002199)[0m [0;1mSELECT * FROM `users` WHERE (`users`.`activation_code` = 'd625da02fdec7785875e51b7f403ef0727e8b3e5') LIMIT 1[0m
[4;35;1mSQL (0.000728)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:54:44 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Your account has been activated!
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
asdfasdfasdf, your account has been activated.
http://127.0.0.1:3000
[4;36;1mSQL (0.000222)[0m [0;1mBEGIN[0m
[4;35;1mMailOutgoing Create (0.000319)[0m [0mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:54:44 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Your account has been activated!\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nasdfasdfasdf, your account has been activated.\n\n http://127.0.0.1:3000', '[email protected]', 0)[0m
[4;36;1mSQL (0.000787)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000337)[0m [0mBEGIN[0m
[4;36;1mUser Update (0.000511)[0m [0;1mUPDATE `users` SET `created_at` = '2008-01-12 06:54:24', `login` = 'asdfasdfasdf', `crypted_password` = '422eaf202dd56dda25848ade485f044a80907f90', `activated_at` = '2008-01-12 14:54:44', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '60b8af27dc41816229578ed800c2b3f3cb8bd659', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:54:44' WHERE `id` = 19[0m
[4;35;1mSQL (0.025999)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.06709 (14 reqs/sec) | DB: 0.03636 (54%) | 302 Found [http://127.0.0.1/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:44) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsGOgtub3RpY2UiFVNpZ251cCBjb21wbGV0ZSEG%0AOgpAdXNlZHsGOwdUOgx1c2VyX2lkaRg%3D--058993c584c3563d1fae402d36f4461a1dd73206
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001090)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.002682)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00051)
Completed in 0.01669 (59 reqs/sec) | Rendering: 0.00674 (40%) | DB: 0.00377 (22%) | 200 OK [http://127.0.0.1/]
Processing SessionsController#show (for 127.0.0.1 at 2008-01-12 06:54:47) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkYIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--deeb569b42f2f3c648db0d77646a3615f2b7e94e
Parameters: {"action"=>"show", "controller"=>"sessions"}
Rendering template within layouts/application
Rendering sessions/show
[4;36;1mUser Columns (0.005322)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mUser Load (0.002175)[0m [0mSELECT * FROM `users` WHERE (`users`.`id` = 19) [0m
Rendered layouts/_flash_boxes (0.00052)
Completed in 0.03016 (33 reqs/sec) | Rendering: 0.02014 (66%) | DB: 0.00750 (24%) | 200 OK [http://127.0.0.1/session]
Processing SessionsController#show (for 127.0.0.1 at 2008-01-12 06:54:48) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoMdXNlcl9pZGkY--0ba00e61b47afb15eb74c504907842e53b6463fe
Parameters: {"action"=>"show", "controller"=>"sessions"}
Rendering template within layouts/application
Rendering sessions/show
[4;36;1mUser Columns (0.005577)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mUser Load (0.002152)[0m [0mSELECT * FROM `users` WHERE (`users`.`id` = 19) [0m
Rendered layouts/_flash_boxes (0.00042)
Completed in 0.02856 (35 reqs/sec) | Rendering: 0.01832 (64%) | DB: 0.00773 (27%) | 200 OK [http://127.0.0.1/session]
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:04:40) [GET]
Session ID: 6fb05f63ec994b0fe020504aa28bd39f
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000247)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000183)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.000000)[0m [0;1mMysql::Error: #42S02Table 'blank_development.widgets' doesn't exist: SELECT * FROM `widgets` [0m
ActiveRecord::StatementInvalid (Mysql::Error: #42S02Table 'blank_development.widgets' doesn't exist: SELECT * FROM `widgets` ):
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract_adapter.rb:150:in `log'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:281:in `execute'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:481:in `select'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:53:in `select_all'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:74:in `cache_sql'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:53:in `select_all'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:532:in `find_by_sql'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:1233:in `find_every'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:503:in `find'
/app/controllers/widgets_controller.rb:6:in `index'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `send'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `perform_action_without_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:697:in `call_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:689:in `perform_action_without_benchmark'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:293:in `measure'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/rescue.rb:199:in `perform_action_without_caching'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/caching.rb:678:in `perform_action'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/query_cache.rb:8:in `cache'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/caching.rb:677:in `perform_action'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `send'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `process_without_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:685:in `process_without_session_management_support'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/session_management.rb:123:in `sass_old_process'
/Library/Ruby/Gems/1.8/gems/haml-1.8.1/lib/sass/plugin/rails.rb:15:in `process'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:388:in `process'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:171:in `handle_request'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:115:in `dispatch'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:126:in `dispatch_cgi'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:9:in `dispatch'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:76:in `process'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:74:in `synchronize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:74:in `process'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:159:in `process_client'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:158:in `each'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:158:in `process_client'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `initialize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `new'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `initialize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `new'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:282:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:281:in `each'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:281:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/mongrel_rails:128:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/command.rb:212:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/mongrel_rails:281
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:64
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/Library/Ruby/Gems/1.8/gems/rails-2.0.2/lib/commands/server.rb:39
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require'
./script/server:3
Rendering /Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/templates/rescues/layout.erb (internal_server_error)
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000164)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000147)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mSQL (0.078302)[0m [0;1mDROP DATABASE IF EXISTS `blank_development`[0m
[4;35;1mSQL (0.000160)[0m [0mSET NAMES 'utf8'[0m
[4;36;1mSQL (0.000121)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
[4;35;1mSQL (0.000414)[0m [0mCREATE DATABASE `blank_development` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_general_ci`[0m
[4;36;1mSQL (0.000157)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000144)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mSQL (0.001951)[0m [0;1mCREATE TABLE `schema_info` (version int(11))[0m
[4;35;1mSQL (0.001290)[0m [0mINSERT INTO `schema_info` (version) VALUES(0)[0m
[4;36;1mSQL (0.000000)[0m [0;1mMysql::Error: #42S01Table 'schema_info' already exists: CREATE TABLE `schema_info` (version int(11))[0m
[4;35;1mSQL (0.000397)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateMailOutgoing (1)
[4;36;1mSQL (0.002603)[0m [0;1mCREATE TABLE `mail_outgoing` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `from` varchar(255) DEFAULT NULL, `to` varchar(255) DEFAULT NULL, `last_send_attempt` int(11) DEFAULT 0, `mail` text DEFAULT NULL, `created_on` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;35;1mSQL (0.000396)[0m [0mUPDATE schema_info SET version = 1[0m
[4;36;1mSQL (0.000385)[0m [0;1mSELECT version FROM schema_info[0m
Migrating to CreateMailIncoming (2)
[4;35;1mSQL (0.019655)[0m [0mCREATE TABLE `mail_incoming` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `mail` text DEFAULT NULL, `created_on` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;36;1mSQL (0.000649)[0m [0;1mUPDATE schema_info SET version = 2[0m
[4;35;1mSQL (0.000480)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateUsers (3)
[4;36;1mSQL (0.000000)[0m [0;1mMysql::Error: #42S02Unknown table 'users': DROP TABLE `users`[0m
[4;35;1mSQL (0.002884)[0m [0mCREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `login` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `crypted_password` varchar(40) DEFAULT NULL, `salt` varchar(40) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `remember_token` varchar(255) DEFAULT NULL, `remember_token_expires_at` datetime DEFAULT NULL, `activation_code` varchar(40) DEFAULT NULL, `activated_at` datetime DEFAULT NULL, `state` varchar(255) DEFAULT 'passive', `deleted_at` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;36;1mSQL (0.000392)[0m [0;1mUPDATE schema_info SET version = 3[0m
[4;35;1mSQL (0.000430)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateWidgets (4)
[4;36;1mSQL (0.003225)[0m [0;1mCREATE TABLE `widgets` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255) DEFAULT NULL, `price` decimal DEFAULT NULL, `description` text DEFAULT NULL, `is_in_stock` tinyint(1) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;35;1mSQL (0.000570)[0m [0mUPDATE schema_info SET version = 4[0m
[4;36;1mSQL (0.000518)[0m [0;1mSELECT * FROM schema_info[0m
[4;35;1mSQL (0.000702)[0m [0mSHOW TABLES[0m
[4;36;1mSQL (0.002509)[0m [0;1mSHOW FIELDS FROM `mail_incoming`[0m
[4;35;1mSQL (0.168535)[0m [0mdescribe `mail_incoming`[0m
[4;36;1mSQL (0.002351)[0m [0;1mSHOW KEYS FROM `mail_incoming`[0m
[4;35;1mSQL (0.013056)[0m [0mSHOW FIELDS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.009690)[0m [0;1mdescribe `mail_outgoing`[0m
[4;35;1mSQL (0.001372)[0m [0mSHOW KEYS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.058650)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.021349)[0m [0mdescribe `users`[0m
[4;36;1mSQL (0.001383)[0m [0;1mSHOW KEYS FROM `users`[0m
[4;35;1mSQL (0.028185)[0m [0mSHOW FIELDS FROM `widgets`[0m
[4;36;1mSQL (0.007471)[0m [0;1mdescribe `widgets`[0m
[4;35;1mSQL (0.002707)[0m [0mSHOW KEYS FROM `widgets`[0m
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:04:54) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000212)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000196)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.000904)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
Rendered layouts/_flash_boxes (0.00134)
Completed in 0.01683 (59 reqs/sec) | Rendering: 0.00921 (54%) | DB: 0.00131 (7%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#new (for 127.0.0.1 at 2008-02-27 00:04:55) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"new", "controller"=>"widgets"}
[4;35;1mWidget Columns (0.004371)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendering template within layouts/application
Rendering widgets/new
Rendered widgets/_form (0.01059)
Rendered layouts/_flash_boxes (0.00031)
Completed in 0.02842 (35 reqs/sec) | Rendering: 0.01740 (61%) | DB: 0.00437 (15%) | 200 OK [http://127.0.0.1/widgets/new]
Processing WidgetsController#create (for 127.0.0.1 at 2008-02-27 00:05:00) [POST]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"commit"=>"Submit", "action"=>"create", "controller"=>"widgets", "widget"=>{"name"=>"asdfdasf", "price"=>"adsfadsfasdf", "description"=>"asdfasdfadsf"}}
[4;36;1mWidget Columns (0.005818)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
[4;35;1mSQL (0.000297)[0m [0mBEGIN[0m
[4;36;1mWidget Create (0.002032)[0m [0;1mINSERT INTO `widgets` (`name`, `updated_at`, `price`, `description`, `is_in_stock`, `created_at`) VALUES('asdfdasf', '2008-02-27 00:05:00', 0, 'asdfasdfadsf', NULL, '2008-02-27 00:05:00')[0m
[4;35;1mSQL (0.000845)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/widgets
Completed in 0.02027 (49 reqs/sec) | DB: 0.00899 (44%) | 302 Found [http://127.0.0.1/widgets]
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:05:00) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsGOgtub3RpY2UiHVdpZGdldCBoYXMgYmVlbiBjcmVhdGVkLgY6CkB1%0Ac2VkewY7BlQ%3D--c6a65a1e072c9d8905e34d1354a3256929c0b510
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001061)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.003840)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00174)
Completed in 0.02420 (41 reqs/sec) | Rendering: 0.00990 (40%) | DB: 0.00490 (20%) | 200 OK [http://127.0.0.1/widgets]
Processing WidgetsController#new (for 127.0.0.1 at 2008-02-27 00:05:01) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"new", "controller"=>"widgets"}
[4;36;1mWidget Columns (0.004752)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendering template within layouts/application
Rendering widgets/new
Rendered widgets/_form (0.00729)
Rendered layouts/_flash_boxes (0.00026)
Completed in 0.02462 (40 reqs/sec) | Rendering: 0.01305 (53%) | DB: 0.00475 (19%) | 200 OK [http://127.0.0.1/widgets/new]
DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
** SubdomainFu: initialized properly
DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
** SubdomainFu: initialized properly
+DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
+** SubdomainFu: initialized properly
+WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
+DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
+** SubdomainFu: initialized properly
+DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
+** SubdomainFu: initialized properly
|
jcnetdev/yubnub
|
f1323203a3a2c2e58f6fba8eb3c1d8b825ea9257
|
Tweaks
|
diff --git a/config/app_config.yml b/config/app_config.yml
index 74306d2..1caea91 100644
--- a/config/app_config.yml
+++ b/config/app_config.yml
@@ -1,4 +1,5 @@
+# CHANGE ME
site_name: "[Your Site]"
site_url: "http://YOURSITE"
require_email_activation: true
\ No newline at end of file
diff --git a/config/environments/development.rb b/config/environments/development.rb
index 7ce23fc..f7a3636 100644
--- a/config/environments/development.rb
+++ b/config/environments/development.rb
@@ -1,20 +1,20 @@
# Settings specified here will take precedence over those in config/environment.rb
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the webserver when you make code changes.
config.cache_classes = false
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# Show full error reports and disable caching
config.action_controller.consider_all_requests_local = true
config.action_view.debug_rjs = true
config.action_controller.perform_caching = false
config.action_view.cache_template_extensions = false
# Don't care if the mailer can't send
config.action_mailer.raise_delivery_errors = false
-config.app_config.site_url = "http://127.0.0.1:3000"
\ No newline at end of file
+config.action_mailer.delivery_method = :test
\ No newline at end of file
diff --git a/config/environments/development.yml b/config/environments/development.yml
new file mode 100644
index 0000000..7866328
--- /dev/null
+++ b/config/environments/development.yml
@@ -0,0 +1 @@
+site_url: http://127.0.0.1:3000
\ No newline at end of file
diff --git a/config/mailer.yml b/config/mailer.yml
new file mode 100644
index 0000000..ab64f5a
--- /dev/null
+++ b/config/mailer.yml
@@ -0,0 +1,8 @@
+# CHANGE ME
+domain: "[YOUR DOMAIN].com"
+
+address: "mail.authsmtp.com"
+port: 587
+user_name: "ac31919"
+password: "cdfw2mcct"
+authentication: :login
\ No newline at end of file
diff --git a/config/mailer.yml.changeme b/config/mailer.yml.changeme
deleted file mode 100644
index 206bfde..0000000
--- a/config/mailer.yml.changeme
+++ /dev/null
@@ -1,7 +0,0 @@
----
-:address: "[SMTP]"
-:port: 587
-:domain: "[domain]"
-:user_name: "[username]"
-:password: "[password]"
-:authentication: :login
\ No newline at end of file
diff --git a/config/sms_fu.yml b/config/sms_fu.yml
index bacd37d..d6cc6af 100644
--- a/config/sms_fu.yml
+++ b/config/sms_fu.yml
@@ -1,52 +1,53 @@
config:
- from_address: [email protected]
+ # CHANGE ME
+ from_address: [email protected]
carriers:
# US Carriers
alltell: @message.alltell.com
ameritech: @paging.acswireless.com
at&t: @txt.att.net
bellsouthmobility: @blsdcs.net
blueskyfrog: @blueskyfrog.com
boost: @myboostmobile.com
cellularsouth: @csouth1.com
kajeet: @mobile.kajeet.net
metropcs: @mymetropcs.com
powertel: @ptel.net
pscwireless: @sms.pscel.com
qwest: @qwestmp.com
southernlink: @page.southernlinc.com
sprint: @messaging.sprintpcs.com
suncom: @tms.suncom.com
t-mobile: @tmomail.net
virgin: @vmobl.net
verizon: @vtext.com
# International Carriers
e-plus-germany: @smsmail.eplus.de
fido-canada: @fido.ca
o2-germany: @o2online.de
o2-uk: @mmail.co.uk
orange-netherlands: @sms.orange.nl
orange-uk: @orange.net
t-mobile-austria: @sms.t-mobile.at
t-mobile-germany: @t-d1-sms.de
t-mobile-uk: @t-mobile.uk.net
telefonica-spain: @movistar.net
vodafone-germany: @vodafone-sms.de
vodafone-uk: @sms.vodafone.net
vodafone-italy: @sms.vodafone.it
vodafone-jp-chuugoku: @n.vodafone.ne.jp
vodafone-jp-hokkaido: @d.vodafone.ne.jp
vodafone-jp-hokuriko: @r.vodafone.ne.jp
vodafone-jp-kansai: @k.vodafone.ne.jp
vodafone-jp-osaka: @k.vodafone.ne.jp
vodafone-jp-kanto: @k.vodafone.ne.jp
vodafone-jp-koushin: @k.vodafone.ne.jp
vodafone-jp-tokyo: @k.vodafone.ne.jp
vodafone-jp-kyuushu: @q.vodafone.ne.jp
vodafone-jp-okinawa: @q.vodafone.ne.jp
vodafone-jp-shikoku: @s.vodafone.ne.jp
vodafone-jp-touhoku: @h.vodafone.ne.jp
vodafone-jp-niigata: @h.vodafone.ne.jp
vodafone-jp-toukai: @h.vodafone.ne.jp
vodafone-spain: @vodafone.es
diff --git a/doc/README_FOR_APP b/doc/README_FOR_APP
deleted file mode 100644
index fe41f5c..0000000
--- a/doc/README_FOR_APP
+++ /dev/null
@@ -1,2 +0,0 @@
-Use this README file to introduce your application and point to useful places in the API for learning more.
-Run "rake doc:app" to generate API documentation for your models, controllers, helpers, and libraries.
diff --git a/log/development.log b/log/development.log
index 3cdb411..644e0bc 100644
--- a/log/development.log
+++ b/log/development.log
@@ -3856,512 +3856,516 @@ Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mUser Create (0.000376)[0m [0mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('6207aec6a64db5f666e258454eef52585c3db827', NULL, '2008-01-12 06:47:09', '6cc849b8cea017d6a07505df6a40c1e8d0f1e795', NULL, NULL, NULL, NULL, 'asdfasdfasdfasdf', '2008-01-12 06:47:09', '[email protected]', 'passive')[0m
[4;36;1mSQL (0.001055)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000183)[0m [0mBEGIN[0m
[4;36;1mUser Update (0.000367)[0m [0;1mUPDATE `users` SET `created_at` = '2008-01-12 06:47:09', `login` = 'asdfasdfasdfasdf', `crypted_password` = '6cc849b8cea017d6a07505df6a40c1e8d0f1e795', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '6207aec6a64db5f666e258454eef52585c3db827', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:47:09' WHERE `id` = 16[0m
[4;35;1mSQL (0.000675)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.17206 (5 reqs/sec) | DB: 0.08513 (49%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:47:09) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtzIGZvciBzaWduaW5n%0AIHVwIQY6CkB1c2VkewY7B1Q6DnJldHVybl90bzA%3D--66377d90710a9e737ea1ae56712acd9ca2057958
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001127)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004054)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.02166 (46 reqs/sec) | Rendering: 0.00988 (45%) | DB: 0.00518 (23%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:47:28) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--dcec315596d36623cb843160e09b73d04f5abeef
Parameters: {"action"=>"new", "controller"=>"users"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000229)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000178)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mUser Columns (0.003302)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00132)
Completed in 0.09237 (10 reqs/sec) | Rendering: 0.07603 (82%) | DB: 0.00371 (4%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:47:36) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--4d7f9c359fb30618422f243f6b8fb88244fcf536
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdfasdf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mUser Columns (0.005989)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000292)[0m [0;1mBEGIN[0m
[4;35;1mUser Load (0.002568)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdfasdf') LIMIT 1[0m
[4;36;1mUser Load (0.002660)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;35;1mSQL (0.000306)[0m [0mROLLBACK[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00044)
Completed in 0.03907 (25 reqs/sec) | Rendering: 0.01061 (27%) | DB: 0.01182 (30%) | 200 OK [http://127.0.0.1/users]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:47:38) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkVIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--4d7f9c359fb30618422f243f6b8fb88244fcf536
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdfasdfsfadsf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;36;1mUser Columns (0.004120)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.000193)[0m [0mBEGIN[0m
[4;36;1mUser Load (0.001378)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdfasdfsfadsf') LIMIT 1[0m
[4;35;1mUser Load (0.001245)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;36;1mUser Create (0.000351)[0m [0;1mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('bd0f63fda26bbdb9103dde45811ad6b30d61e515', NULL, '2008-01-12 06:47:38', '8a7e5095b7a2ad1c204eef7f7505b808947c942f', NULL, NULL, NULL, NULL, 'asdfasdfasdfasdfsfadsf', '2008-01-12 06:47:38', '[email protected]', 'passive')[0m
[4;35;1mSQL (0.000780)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000343)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000424)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:47:38', `login` = 'asdfasdfasdfasdfsfadsf', `crypted_password` = '8a7e5095b7a2ad1c204eef7f7505b808947c942f', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = 'bd0f63fda26bbdb9103dde45811ad6b30d61e515', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:47:38' WHERE `id` = 17[0m
[4;36;1mSQL (0.000652)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.02754 (36 reqs/sec) | DB: 0.00949 (34%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:47:38) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--fb9ca386af4504c415c3af83cc9274ba7d85b69a
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001138)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004652)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.08185 (12 reqs/sec) | Rendering: 0.01077 (13%) | DB: 0.00579 (7%) | 200 OK [http://127.0.0.1/]
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000162)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000131)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mUser Load (0.000824)[0m [0;1mSELECT * FROM `users` LIMIT 1[0m
[4;35;1mUser Columns (0.003111)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000632)[0m [0;1mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:48:35 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: asdfasdfasdfasdf
Password:
Visit this url to activate your account:
http://127.0.0.1:3000/users//activate
[4;35;1mMailOutgoing Columns (0.003513)[0m [0mSHOW FIELDS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.000200)[0m [0;1mBEGIN[0m
[4;35;1mMailOutgoing Create (0.000370)[0m [0mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES('2008-01-12 06:48:35', 'Admin', 'Date: Sat, 12 Jan 2008 06:48:35 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: asdfasdfasdfasdf\n Password: \n\nVisit this url to activate your account:\n\n http://127.0.0.1:3000/users//activate', '[email protected]', 0)[0m
[4;36;1mSQL (0.067444)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000267)[0m [0mBEGIN[0m
[4;36;1mUser Update (0.000451)[0m [0;1mUPDATE `users` SET `created_at` = '2008-01-12 06:47:09', `login` = 'asdfasdfasdfasdf', `crypted_password` = '6cc849b8cea017d6a07505df6a40c1e8d0f1e795', `activated_at` = '2008-01-12 14:48:35', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '6207aec6a64db5f666e258454eef52585c3db827', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:48:35' WHERE `id` = 16[0m
[4;35;1mSQL (0.000605)[0m [0mCOMMIT[0m
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:20) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkGIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--624025e9b0a0a68ef9ea877e0ea518bb584e850a
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000213)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000179)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.001067)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004855)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00143)
Completed in 0.09217 (10 reqs/sec) | Rendering: 0.07852 (85%) | DB: 0.00631 (6%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:23) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--07274a905179a765a6e9b05efde30cb248ecd26a
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001091)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004559)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00064)
Completed in 0.02085 (47 reqs/sec) | Rendering: 0.00883 (42%) | DB: 0.00565 (27%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:52:31) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--6821b97074e9fa81e4e13c4be7cbb7f2901389ee
Parameters: {"action"=>"new", "controller"=>"users"}
[4;36;1mUser Columns (0.005229)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00062)
Completed in 0.03293 (30 reqs/sec) | Rendering: 0.01657 (50%) | DB: 0.00523 (15%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:52:31) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkWOg5yZXR1cm5fdG8wIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--54d3ab3cb61c831af7d7582d3cc0c1a6c8bab637
Parameters: {"action"=>"new", "controller"=>"users"}
[4;35;1mUser Columns (0.005895)[0m [0mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00055)
Completed in 0.08563 (11 reqs/sec) | Rendering: 0.06832 (79%) | DB: 0.00589 (6%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:52:39) [POST]
Session ID: BAh7CDoMdXNlcl9pZGkWIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--6821b97074e9fa81e4e13c4be7cbb7f2901389ee
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"tony", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;36;1mUser Columns (0.005908)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.000276)[0m [0mBEGIN[0m
[4;36;1mUser Load (0.002448)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.login) = 'tony') LIMIT 1[0m
[4;35;1mUser Load (0.001944)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;36;1mUser Create (0.000579)[0m [0;1mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', NULL, '2008-01-12 06:52:39', 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', NULL, NULL, NULL, NULL, 'tony', '2008-01-12 06:52:39', '[email protected]', 'passive')[0m
[4;35;1mSQL (0.000669)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000228)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000318)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:52:39', `login` = 'tony', `crypted_password` = 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:52:39' WHERE `id` = 18[0m
[4;36;1mSQL (0.000720)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000673)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:52:39 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: tony
Password: asdf
Visit this url to activate your account:
http://127.0.0.1:3000/users//activate
[4;36;1mMailOutgoing Columns (0.003946)[0m [0;1mSHOW FIELDS FROM `mail_outgoing`[0m
[4;35;1mSQL (0.000264)[0m [0mBEGIN[0m
[4;36;1mMailOutgoing Create (0.000461)[0m [0;1mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:52:39 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: tony\n Password: asdf\n\nVisit this url to activate your account:\n\n http://127.0.0.1:3000/users//activate', '[email protected]', 0)[0m
[4;35;1mSQL (0.000957)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000268)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000533)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:52:39', `login` = 'tony', `crypted_password` = 'ca12d84007f52b8afd2a179c9f3d9002ce193b1d', `activated_at` = '2008-01-12 14:52:39', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '2b708a35d6875b1f88a57c1fb03a23c2ad5238e1', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:52:39' WHERE `id` = 18[0m
[4;36;1mSQL (0.000677)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.05774 (17 reqs/sec) | DB: 0.02087 (36%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:52:39) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkXOg5yZXR1cm5fdG8wIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewY6C25vdGljZSIbVGhhbmtz%0AIGZvciBzaWduaW5nIHVwIQY6CkB1c2VkewY7CFQ%3D--f05c650061a50757fdd625a3128482437ae11670
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001075)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004046)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00071)
Completed in 0.02023 (49 reqs/sec) | Rendering: 0.00892 (44%) | DB: 0.00512 (25%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:15) [GET]
Session ID: BAh7CDoMdXNlcl9pZGkXIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVyOjpG%0AbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsAOg5yZXR1cm5fdG8w--51c73f97178e7b6d8e1a6d392d2009106f2933e3
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000205)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000176)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.001063)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.004536)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00162)
Completed in 0.08904 (11 reqs/sec) | Rendering: 0.07624 (85%) | DB: 0.00598 (6%) | 200 OK [http://127.0.0.1/]
Processing UsersController#new (for 127.0.0.1 at 2008-01-12 06:54:19) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoMdXNlcl9pZGkX--f95542e9d7c74ff238c0f82008e3702d814f9559
Parameters: {"action"=>"new", "controller"=>"users"}
[4;36;1mUser Columns (0.005178)[0m [0;1mSHOW FIELDS FROM `users`[0m
Rendering template within layouts/application
Rendering users/new
Rendered layouts/_flash_boxes (0.00058)
Completed in 0.03341 (29 reqs/sec) | Rendering: 0.01739 (52%) | DB: 0.00518 (15%) | 200 OK [http://127.0.0.1/users/new]
Processing UsersController#create (for 127.0.0.1 at 2008-01-12 06:54:24) [POST]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkXIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--9528283fffbd76ce1e102f064d814ceb5e4969d1
Parameters: {"user"=>{"password_confirmation"=>"asdf", "login"=>"asdfasdfasdf", "password"=>"asdf", "email"=>"[email protected]"}, "commit"=>"Submit", "action"=>"create", "controller"=>"users"}
Cookie set: auth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT
[4;35;1mUser Columns (0.003277)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mSQL (0.000419)[0m [0;1mBEGIN[0m
[4;35;1mUser Load (0.001455)[0m [0mSELECT * FROM `users` WHERE (LOWER(users.login) = 'asdfasdfasdf') LIMIT 1[0m
[4;36;1mUser Load (0.001270)[0m [0;1mSELECT * FROM `users` WHERE (LOWER(users.email) = '[email protected]') LIMIT 1[0m
[4;35;1mUser Create (0.000312)[0m [0mINSERT INTO `users` (`salt`, `activated_at`, `updated_at`, `crypted_password`, `deleted_at`, `activation_code`, `remember_token_expires_at`, `remember_token`, `login`, `created_at`, `email`, `state`) VALUES('60b8af27dc41816229578ed800c2b3f3cb8bd659', NULL, '2008-01-12 06:54:24', '422eaf202dd56dda25848ade485f044a80907f90', NULL, NULL, NULL, NULL, 'asdfasdfasdf', '2008-01-12 06:54:24', '[email protected]', 'passive')[0m
[4;36;1mSQL (0.000834)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.001068)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:54:24 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Please activate your new account
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
Your account has been created.
Username: asdfasdfasdf
Password: asdf
Visit this url to activate your account:
http://127.0.0.1:3000/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate
[4;36;1mMailOutgoing Columns (0.002753)[0m [0;1mSHOW FIELDS FROM `mail_outgoing`[0m
[4;35;1mSQL (0.000190)[0m [0mBEGIN[0m
[4;36;1mMailOutgoing Create (0.000311)[0m [0;1mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:54:24 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Please activate your new account\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nYour account has been created.\n\n Username: asdfasdfasdf\n Password: asdf\n\nVisit this url to activate your account:\n http://127.0.0.1:3000/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate\n', '[email protected]', 0)[0m
[4;35;1mSQL (0.000693)[0m [0mCOMMIT[0m
[4;36;1mSQL (0.000164)[0m [0;1mBEGIN[0m
[4;35;1mUser Update (0.000338)[0m [0mUPDATE `users` SET `created_at` = '2008-01-12 06:54:24', `login` = 'asdfasdfasdf', `crypted_password` = '422eaf202dd56dda25848ade485f044a80907f90', `activated_at` = NULL, `remember_token_expires_at` = NULL, `activation_code` = 'd625da02fdec7785875e51b7f403ef0727e8b3e5', `salt` = '60b8af27dc41816229578ed800c2b3f3cb8bd659', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'pending', `email` = '[email protected]', `updated_at` = '2008-01-12 06:54:24' WHERE `id` = 19[0m
[4;36;1mSQL (0.000688)[0m [0;1mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.05121 (19 reqs/sec) | DB: 0.01377 (26%) | 302 Found [http://127.0.0.1/users]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:24) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsGOgtub3RpY2UiG1RoYW5rcyBmb3Igc2lnbmlu%0AZyB1cCEGOgpAdXNlZHsGOwdUOgx1c2VyX2lkaRg%3D--bc834e021d7d4946b1ab4941eba9506b02bc52de
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;35;1mWidget Load (0.001495)[0m [0mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;36;1mWidget Columns (0.004227)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00079)
Completed in 0.02238 (44 reqs/sec) | Rendering: 0.00951 (42%) | DB: 0.00572 (25%) | 200 OK [http://127.0.0.1/]
Processing UsersController#activate (for 127.0.0.1 at 2008-01-12 06:54:44) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkYIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--deeb569b42f2f3c648db0d77646a3615f2b7e94e
Parameters: {"action"=>"activate", "id"=>"d625da02fdec7785875e51b7f403ef0727e8b3e5", "controller"=>"users"}
[4;35;1mUser Columns (0.005259)[0m [0mSHOW FIELDS FROM `users`[0m
[4;36;1mUser Load (0.002199)[0m [0;1mSELECT * FROM `users` WHERE (`users`.`activation_code` = 'd625da02fdec7785875e51b7f403ef0727e8b3e5') LIMIT 1[0m
[4;35;1mSQL (0.000728)[0m [0mSHOW TABLES[0m
Sent mail:
Date: Sat, 12 Jan 2008 06:54:44 -0800
From: Admin
To: [email protected]
Subject: [Your Site] - Your account has been activated!
Mime-Version: 1.0
Content-Type: text/plain; charset=utf-8
asdfasdfasdf, your account has been activated.
http://127.0.0.1:3000
[4;36;1mSQL (0.000222)[0m [0;1mBEGIN[0m
[4;35;1mMailOutgoing Create (0.000319)[0m [0mINSERT INTO `mail_outgoing` (`created_on`, `from`, `mail`, `to`, `last_send_attempt`) VALUES(NULL, 'Admin', 'Date: Sat, 12 Jan 2008 06:54:44 -0800\r\nFrom: Admin\r\nTo: [email protected]\r\nSubject: [Your Site] - Your account has been activated!\r\nMime-Version: 1.0\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nasdfasdfasdf, your account has been activated.\n\n http://127.0.0.1:3000', '[email protected]', 0)[0m
[4;36;1mSQL (0.000787)[0m [0;1mCOMMIT[0m
[4;35;1mSQL (0.000337)[0m [0mBEGIN[0m
[4;36;1mUser Update (0.000511)[0m [0;1mUPDATE `users` SET `created_at` = '2008-01-12 06:54:24', `login` = 'asdfasdfasdf', `crypted_password` = '422eaf202dd56dda25848ade485f044a80907f90', `activated_at` = '2008-01-12 14:54:44', `remember_token_expires_at` = NULL, `activation_code` = NULL, `salt` = '60b8af27dc41816229578ed800c2b3f3cb8bd659', `remember_token` = NULL, `deleted_at` = NULL, `state` = 'active', `email` = '[email protected]', `updated_at` = '2008-01-12 06:54:44' WHERE `id` = 19[0m
[4;35;1mSQL (0.025999)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/
Completed in 0.06709 (14 reqs/sec) | DB: 0.03636 (54%) | 302 Found [http://127.0.0.1/users/d625da02fdec7785875e51b7f403ef0727e8b3e5/activate]
Processing WidgetsController#index (for 127.0.0.1 at 2008-01-12 06:54:44) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsGOgtub3RpY2UiFVNpZ251cCBjb21wbGV0ZSEG%0AOgpAdXNlZHsGOwdUOgx1c2VyX2lkaRg%3D--058993c584c3563d1fae402d36f4461a1dd73206
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001090)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.002682)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00051)
Completed in 0.01669 (59 reqs/sec) | Rendering: 0.00674 (40%) | DB: 0.00377 (22%) | 200 OK [http://127.0.0.1/]
Processing SessionsController#show (for 127.0.0.1 at 2008-01-12 06:54:47) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMDoMdXNlcl9pZGkYIgpmbGFzaElDOidBY3Rpb25D%0Ab250cm9sbGVyOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--deeb569b42f2f3c648db0d77646a3615f2b7e94e
Parameters: {"action"=>"show", "controller"=>"sessions"}
Rendering template within layouts/application
Rendering sessions/show
[4;36;1mUser Columns (0.005322)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mUser Load (0.002175)[0m [0mSELECT * FROM `users` WHERE (`users`.`id` = 19) [0m
Rendered layouts/_flash_boxes (0.00052)
Completed in 0.03016 (33 reqs/sec) | Rendering: 0.02014 (66%) | DB: 0.00750 (24%) | 200 OK [http://127.0.0.1/session]
Processing SessionsController#show (for 127.0.0.1 at 2008-01-12 06:54:48) [GET]
Session ID: BAh7CDoOcmV0dXJuX3RvMCIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6%0ARmxhc2g6OkZsYXNoSGFzaHsABjoKQHVzZWR7ADoMdXNlcl9pZGkY--0ba00e61b47afb15eb74c504907842e53b6463fe
Parameters: {"action"=>"show", "controller"=>"sessions"}
Rendering template within layouts/application
Rendering sessions/show
[4;36;1mUser Columns (0.005577)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mUser Load (0.002152)[0m [0mSELECT * FROM `users` WHERE (`users`.`id` = 19) [0m
Rendered layouts/_flash_boxes (0.00042)
Completed in 0.02856 (35 reqs/sec) | Rendering: 0.01832 (64%) | DB: 0.00773 (27%) | 200 OK [http://127.0.0.1/session]
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:04:40) [GET]
Session ID: 6fb05f63ec994b0fe020504aa28bd39f
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000247)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000183)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.000000)[0m [0;1mMysql::Error: #42S02Table 'blank_development.widgets' doesn't exist: SELECT * FROM `widgets` [0m
ActiveRecord::StatementInvalid (Mysql::Error: #42S02Table 'blank_development.widgets' doesn't exist: SELECT * FROM `widgets` ):
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract_adapter.rb:150:in `log'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:281:in `execute'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/mysql_adapter.rb:481:in `select'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:53:in `select_all'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:74:in `cache_sql'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:53:in `select_all'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:532:in `find_by_sql'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:1233:in `find_every'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/base.rb:503:in `find'
/app/controllers/widgets_controller.rb:6:in `index'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `send'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:1158:in `perform_action_without_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:697:in `call_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:689:in `perform_action_without_benchmark'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/benchmark.rb:293:in `measure'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/benchmarking.rb:68:in `perform_action_without_rescue'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/rescue.rb:199:in `perform_action_without_caching'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/caching.rb:678:in `perform_action'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/connection_adapters/abstract/query_cache.rb:33:in `cache'
/Library/Ruby/Gems/1.8/gems/activerecord-2.0.2/lib/active_record/query_cache.rb:8:in `cache'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/caching.rb:677:in `perform_action'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `send'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:524:in `process_without_filters'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/filters.rb:685:in `process_without_session_management_support'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/session_management.rb:123:in `sass_old_process'
/Library/Ruby/Gems/1.8/gems/haml-1.8.1/lib/sass/plugin/rails.rb:15:in `process'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/base.rb:388:in `process'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:171:in `handle_request'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:115:in `dispatch'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:126:in `dispatch_cgi'
/Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/dispatcher.rb:9:in `dispatch'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:76:in `process'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:74:in `synchronize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/../lib/mongrel/rails.rb:74:in `process'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:159:in `process_client'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:158:in `each'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:158:in `process_client'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `initialize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `new'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:285:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `initialize'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `new'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel.rb:268:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:282:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:281:in `each'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/configurator.rb:281:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/mongrel_rails:128:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/lib/mongrel/command.rb:212:in `run'
/Library/Ruby/Gems/1.8/gems/mongrel-1.1.3/bin/mongrel_rails:281
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:489:in `load'
/Library/Ruby/Gems/1.8/gems/rails-2.0.2/lib/commands/servers/mongrel.rb:64
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:342:in `new_constants_in'
/Library/Ruby/Gems/1.8/gems/activesupport-2.0.2/lib/active_support/dependencies.rb:496:in `require'
/Library/Ruby/Gems/1.8/gems/rails-2.0.2/lib/commands/server.rb:39
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `gem_original_require'
/Library/Ruby/Site/1.8/rubygems/custom_require.rb:27:in `require'
./script/server:3
Rendering /Library/Ruby/Gems/1.8/gems/actionpack-2.0.2/lib/action_controller/templates/rescues/layout.erb (internal_server_error)
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000164)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000147)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mSQL (0.078302)[0m [0;1mDROP DATABASE IF EXISTS `blank_development`[0m
[4;35;1mSQL (0.000160)[0m [0mSET NAMES 'utf8'[0m
[4;36;1mSQL (0.000121)[0m [0;1mSET SQL_AUTO_IS_NULL=0[0m
[4;35;1mSQL (0.000414)[0m [0mCREATE DATABASE `blank_development` DEFAULT CHARACTER SET `utf8` COLLATE `utf8_general_ci`[0m
[4;36;1mSQL (0.000157)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000144)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mSQL (0.001951)[0m [0;1mCREATE TABLE `schema_info` (version int(11))[0m
[4;35;1mSQL (0.001290)[0m [0mINSERT INTO `schema_info` (version) VALUES(0)[0m
[4;36;1mSQL (0.000000)[0m [0;1mMysql::Error: #42S01Table 'schema_info' already exists: CREATE TABLE `schema_info` (version int(11))[0m
[4;35;1mSQL (0.000397)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateMailOutgoing (1)
[4;36;1mSQL (0.002603)[0m [0;1mCREATE TABLE `mail_outgoing` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `from` varchar(255) DEFAULT NULL, `to` varchar(255) DEFAULT NULL, `last_send_attempt` int(11) DEFAULT 0, `mail` text DEFAULT NULL, `created_on` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;35;1mSQL (0.000396)[0m [0mUPDATE schema_info SET version = 1[0m
[4;36;1mSQL (0.000385)[0m [0;1mSELECT version FROM schema_info[0m
Migrating to CreateMailIncoming (2)
[4;35;1mSQL (0.019655)[0m [0mCREATE TABLE `mail_incoming` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `mail` text DEFAULT NULL, `created_on` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;36;1mSQL (0.000649)[0m [0;1mUPDATE schema_info SET version = 2[0m
[4;35;1mSQL (0.000480)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateUsers (3)
[4;36;1mSQL (0.000000)[0m [0;1mMysql::Error: #42S02Unknown table 'users': DROP TABLE `users`[0m
[4;35;1mSQL (0.002884)[0m [0mCREATE TABLE `users` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `login` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `crypted_password` varchar(40) DEFAULT NULL, `salt` varchar(40) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL, `remember_token` varchar(255) DEFAULT NULL, `remember_token_expires_at` datetime DEFAULT NULL, `activation_code` varchar(40) DEFAULT NULL, `activated_at` datetime DEFAULT NULL, `state` varchar(255) DEFAULT 'passive', `deleted_at` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;36;1mSQL (0.000392)[0m [0;1mUPDATE schema_info SET version = 3[0m
[4;35;1mSQL (0.000430)[0m [0mSELECT version FROM schema_info[0m
Migrating to CreateWidgets (4)
[4;36;1mSQL (0.003225)[0m [0;1mCREATE TABLE `widgets` (`id` int(11) DEFAULT NULL auto_increment PRIMARY KEY, `name` varchar(255) DEFAULT NULL, `price` decimal DEFAULT NULL, `description` text DEFAULT NULL, `is_in_stock` tinyint(1) DEFAULT NULL, `created_at` datetime DEFAULT NULL, `updated_at` datetime DEFAULT NULL) ENGINE=InnoDB[0m
[4;35;1mSQL (0.000570)[0m [0mUPDATE schema_info SET version = 4[0m
[4;36;1mSQL (0.000518)[0m [0;1mSELECT * FROM schema_info[0m
[4;35;1mSQL (0.000702)[0m [0mSHOW TABLES[0m
[4;36;1mSQL (0.002509)[0m [0;1mSHOW FIELDS FROM `mail_incoming`[0m
[4;35;1mSQL (0.168535)[0m [0mdescribe `mail_incoming`[0m
[4;36;1mSQL (0.002351)[0m [0;1mSHOW KEYS FROM `mail_incoming`[0m
[4;35;1mSQL (0.013056)[0m [0mSHOW FIELDS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.009690)[0m [0;1mdescribe `mail_outgoing`[0m
[4;35;1mSQL (0.001372)[0m [0mSHOW KEYS FROM `mail_outgoing`[0m
[4;36;1mSQL (0.058650)[0m [0;1mSHOW FIELDS FROM `users`[0m
[4;35;1mSQL (0.021349)[0m [0mdescribe `users`[0m
[4;36;1mSQL (0.001383)[0m [0;1mSHOW KEYS FROM `users`[0m
[4;35;1mSQL (0.028185)[0m [0mSHOW FIELDS FROM `widgets`[0m
[4;36;1mSQL (0.007471)[0m [0;1mdescribe `widgets`[0m
[4;35;1mSQL (0.002707)[0m [0mSHOW KEYS FROM `widgets`[0m
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:04:54) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"index", "controller"=>"widgets"}
WARNING: You're using the Ruby-based MySQL library that ships with Rails. This library is not suited for production. Please install the C-based MySQL library instead (gem install mysql).
[4;36;1mSQL (0.000212)[0m [0;1mSET NAMES 'utf8'[0m
[4;35;1mSQL (0.000196)[0m [0mSET SQL_AUTO_IS_NULL=0[0m
[4;36;1mWidget Load (0.000904)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
Rendered layouts/_flash_boxes (0.00134)
Completed in 0.01683 (59 reqs/sec) | Rendering: 0.00921 (54%) | DB: 0.00131 (7%) | 200 OK [http://127.0.0.1/]
Processing WidgetsController#new (for 127.0.0.1 at 2008-02-27 00:04:55) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"new", "controller"=>"widgets"}
[4;35;1mWidget Columns (0.004371)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendering template within layouts/application
Rendering widgets/new
Rendered widgets/_form (0.01059)
Rendered layouts/_flash_boxes (0.00031)
Completed in 0.02842 (35 reqs/sec) | Rendering: 0.01740 (61%) | DB: 0.00437 (15%) | 200 OK [http://127.0.0.1/widgets/new]
Processing WidgetsController#create (for 127.0.0.1 at 2008-02-27 00:05:00) [POST]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"commit"=>"Submit", "action"=>"create", "controller"=>"widgets", "widget"=>{"name"=>"asdfdasf", "price"=>"adsfadsfasdf", "description"=>"asdfasdfadsf"}}
[4;36;1mWidget Columns (0.005818)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
[4;35;1mSQL (0.000297)[0m [0mBEGIN[0m
[4;36;1mWidget Create (0.002032)[0m [0;1mINSERT INTO `widgets` (`name`, `updated_at`, `price`, `description`, `is_in_stock`, `created_at`) VALUES('asdfdasf', '2008-02-27 00:05:00', 0, 'asdfasdfadsf', NULL, '2008-02-27 00:05:00')[0m
[4;35;1mSQL (0.000845)[0m [0mCOMMIT[0m
Redirected to http://127.0.0.1:3000/widgets
Completed in 0.02027 (49 reqs/sec) | DB: 0.00899 (44%) | 302 Found [http://127.0.0.1/widgets]
Processing WidgetsController#index (for 127.0.0.1 at 2008-02-27 00:05:00) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsGOgtub3RpY2UiHVdpZGdldCBoYXMgYmVlbiBjcmVhdGVkLgY6CkB1%0Ac2VkewY7BlQ%3D--c6a65a1e072c9d8905e34d1354a3256929c0b510
Parameters: {"action"=>"index", "controller"=>"widgets"}
[4;36;1mWidget Load (0.001061)[0m [0;1mSELECT * FROM `widgets` [0m
Rendering template within layouts/application
Rendering widgets/index
[4;35;1mWidget Columns (0.003840)[0m [0mSHOW FIELDS FROM `widgets`[0m
Rendered layouts/_flash_boxes (0.00174)
Completed in 0.02420 (41 reqs/sec) | Rendering: 0.00990 (40%) | DB: 0.00490 (20%) | 200 OK [http://127.0.0.1/widgets]
Processing WidgetsController#new (for 127.0.0.1 at 2008-02-27 00:05:01) [GET]
Session ID: BAh7BiIKZmxhc2hJQzonQWN0aW9uQ29udHJvbGxlcjo6Rmxhc2g6OkZsYXNo%0ASGFzaHsABjoKQHVzZWR7AA%3D%3D--5cc2241c34f1a1816cf1a36c5c735684ad01427e
Parameters: {"action"=>"new", "controller"=>"widgets"}
[4;36;1mWidget Columns (0.004752)[0m [0;1mSHOW FIELDS FROM `widgets`[0m
Rendering template within layouts/application
Rendering widgets/new
Rendered widgets/_form (0.00729)
Rendered layouts/_flash_boxes (0.00026)
Completed in 0.02462 (40 reqs/sec) | Rendering: 0.01305 (53%) | DB: 0.00475 (19%) | 200 OK [http://127.0.0.1/widgets/new]
+DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
+** SubdomainFu: initialized properly
+DEPRECATION WARNING: config.action_view.cache_template_extensions option has been deprecated and has no affect. Please remove it from your config files. See http://www.rubyonrails.org/deprecation for details. (called from send at /Library/Ruby/Gems/1.8/gems/rails-2.1.0/lib/initializer.rb:455)
+** SubdomainFu: initialized properly
|
treep/named-features
|
7b44937840f0c023ec0b287e518361c5a8fb68ce
|
version 0.1
|
diff --git a/.gitignore b/.gitignore
index ca949df..48066db 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,4 @@
+
*~
-.fasls
+\#*
+*.fasl
diff --git a/README b/README
index f7455e1..c3a15f8 100644
--- a/README
+++ b/README
@@ -1,24 +1,21 @@
- * CL-FEATURES *
+NAMED-FEATURES
- This library contain:
+ This library allow to create special list of features with reader macro.
+Just like *features* with #+/#- readers but separeted.
- * Trivial-features from popular `trivial-features' library.
+EXAMPLE
- * Local features - for creating special lists of features with macro readers.
+ (named-features:define-features-list *my-features*
+ :documentation "My features list. Used with #h+/#h- reader macros."
+ :macro-character #\h)
- * Macroes for detecting features environment
+ (pushnew :sbcl *my-features*)
- * Mapping mechanism for variouse features.
+ #h+sbcl (format t "This is SBCL backend.~%")
- Examples:
+ (pushnew :linux *my-features*)
- (define-features-list *hunchentoot-features*
- :documentation "Features list for Hunchentoot. Used with #h+/#h- reader macroes."
- :macro-character #\h)
+ #h+(and sbcl linux) (format t "This is SBCL on Linux backend.~%")
- #h+:sbcl (print "This is SBCL backend.")
-
- **********
-
-This library is not finished yet.
+ #h-(and sbcl (not linux)) (format t "This not SBCL not on Linux backend.~%")
diff --git a/cl-features.asd b/cl-features.asd
deleted file mode 100644
index d3df633..0000000
--- a/cl-features.asd
+++ /dev/null
@@ -1,16 +0,0 @@
-;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
-;;;
-;;; cl-features.asd -- ASDF definition for CL-FEATURES system.
-;;;
-
-(asdf:defsystem :cl-features
- :description "Features managment for CL."
- :licence "Public domain"
- :version "0.0.1"
- :pathname (merge-pathnames "src/" *load-truename*)
- :serial t
- :depends-on (:trivial-features)
- :components ((:file "package")
- (:file "readers")
- (:file "macroes")
- (:file "mapping")))
diff --git a/definition.lisp b/definition.lisp
new file mode 100644
index 0000000..9d1ee40
--- /dev/null
+++ b/definition.lisp
@@ -0,0 +1,54 @@
+
+(defpackage #:named-features
+ (:use #:common-lisp)
+ (:export #:feature-match-p
+ #:define-features-list))
+
+(in-package #:named-features)
+
+(defun feature-match-p (feature list)
+ "Is FEATURE (symbol or expression) match with features LIST?"
+ (etypecase feature
+ (keyword (find feature list))
+ (symbol (find (intern (string feature) (find-package "KEYWORD")) list))
+ (cons (flet ((subfeature-match-p (subfeature)
+ (feature-match-p subfeature list)))
+ (ecase (first feature)
+ ((:or or)
+ (some #'subfeature-match-p (rest feature)))
+ ((:and and)
+ (every #'subfeature-match-p (rest feature)))
+ ((:not not)
+ (let ((rest (rest feature)))
+ (if (or (null (first rest))
+ (rest rest))
+ (error "wrong number of terms in compound feature ~S"
+ feature)
+ (not (subfeature-match-p (second feature)))))))))))
+
+(defmacro define-features-list (name &key initial-value documentation macro-character)
+ "Define a new features list called NAME with related reader macro."
+ `(progn
+ (defparameter ,name ,initial-value ,documentation)
+ (set-dispatch-macro-character
+ #\#
+ ,macro-character
+ #'(lambda (stream sub-character infix-parameter)
+ (when infix-parameter
+ (error "illegal read syntax: #~D~C" infix-parameter sub-character))
+ (let* ((next-char (read-char stream))
+ (plus-p
+ (case next-char
+ (#\+ t)
+ (#\- nil)
+ (t (error "illegal read syntax: #~C~C" sub-character next-char))))
+ (feature (read stream))
+ (match-p (not (null (feature-match-p feature ,name))))
+ (result (read stream t nil t)))
+ (if match-p
+ (if plus-p
+ result
+ (values))
+ (if plus-p
+ (values)
+ result)))))))
diff --git a/named-features.asd b/named-features.asd
new file mode 100644
index 0000000..8ef96c9
--- /dev/null
+++ b/named-features.asd
@@ -0,0 +1,8 @@
+
+(defsystem named-features
+ :description "Library for creating features lists."
+ :licence "Public domain / 0-clause MIT"
+ :version "0.1"
+ :serial t
+ :components
+ ((:file "definition")))
diff --git a/src/macroes.lisp b/src/macroes.lisp
deleted file mode 100644
index bbaddee..0000000
--- a/src/macroes.lisp
+++ /dev/null
@@ -1,30 +0,0 @@
-;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
-;;;
-;;; macroes.lisp -- top-level macroes for work with various features lists.
-;;;
-
-(in-package #:cl-features)
-
-;;; top-level macro for define new features list.
-
-(defmacro define-features-list (name &key value documentation macro-character)
- "Define a new features list called NAME and its related readers."
- `(progn
- (declaim (type list ,name))
- (defparameter ,name ,value ,documentation)
- (set-dispatch-macro-character #\# ,macro-character #'features-reader)))
-
-;;; when-* macroes
-
-;;; when-features
-;;; when-not-features
-;;; when-some-features
-;;; when-not-some-features
-
-;(when-features ((*features* :sbcl :linux)
-; (*my-features* :all :good))
-; (do-something))
-
-;;; with-features
-
-
diff --git a/src/mapping.lisp b/src/mapping.lisp
deleted file mode 100644
index fb2416b..0000000
--- a/src/mapping.lisp
+++ /dev/null
@@ -1,6 +0,0 @@
-;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
-;;;
-;;; mapping.lisp -- mapping keys from one features list to another.
-;;;
-
-(in-package #:cl-features)
diff --git a/src/package.lisp b/src/package.lisp
deleted file mode 100644
index 5f22a37..0000000
--- a/src/package.lisp
+++ /dev/null
@@ -1,10 +0,0 @@
-;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
-;;;
-;;; package.lisp -- package difinition for CL-FEATURES system.
-;;;
-
-(defpackage #:cl-features
- (:use #:cl)
- (:export #:define-features-list
-
- ))
diff --git a/src/readers.lisp b/src/readers.lisp
deleted file mode 100644
index 79311b1..0000000
--- a/src/readers.lisp
+++ /dev/null
@@ -1,46 +0,0 @@
-;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
-;;;
-;;; readers.lisp -- reader macroes for features list.
-;;;
-
-(in-package #:cl-features)
-
-;;; helper function which know about how to calculate :or/:and/:not predicates
-;;; in test list.
-
-(declaim (ftype (function ((or keyword cons) list) boolean) feature-in-list-p))
-(defun feature-in-list-p (feature list)
- "Is FEATURE or FEATURES-EXPR in LIST?"
- (etypecase feature
- (symbol (member feature list :test #'eq))
- (cons (flet ((subfeature-in-list-p (subfeature)
- (feature-in-list-p subfeature list)))
- (ecase (first feature)
- (:or (some #'subfeature-in-list-p (rest feature)))
- (:and (every #'subfeature-in-list-p (rest feature)))
- (:not (let ((rest (cdr feature)))
- (if (or (null (car rest)) (cdr rest))
- (error "wrong number of terms in compound feature ~S"
- feature)
- (not (subfeature-in-list-p (second feature)))))))))))
-
-;;; reader macro.
-
-(defun features-reader (stream sub-character infix-parameter)
- "Definition of #<.>+ and #<.>- reader macroes."
- (declare (type stream stream) (type character sub-character))
- (when infix-parameter
- (error "illegal read syntax: #~D~C" infix-parameter sub-character))
- (let ((next-char (read-char stream)))
- (unless (find next-char "+-")
- (error "illegal read syntax: #~C~C" sub-character next-char))
- (when (let* ((*package* (find-package "KEYWORD"))
- (*read-suppress* nil)
- (not-p (char= next-char #\-))
- (feature (read stream)))
- (if (feature-in-list-p feature *hunchentoot-features*)
- not-p
- (not not-p)))
- (let ((*read-suppress* t))
- (read stream t nil t))))
- (values))
|
treep/named-features
|
c5c97fbe721967132e96a6df90ae9b20ffe3e623
|
bff one error.
|
diff --git a/src/macroes.lisp b/src/macroes.lisp
index 8ce690a..bbaddee 100644
--- a/src/macroes.lisp
+++ b/src/macroes.lisp
@@ -1,30 +1,30 @@
;;;; -*- Mode: Lisp; Syntax: ANSI-Common-Lisp; indent-tabs-mode: nil -*-
;;;
;;; macroes.lisp -- top-level macroes for work with various features lists.
;;;
(in-package #:cl-features)
;;; top-level macro for define new features list.
(defmacro define-features-list (name &key value documentation macro-character)
"Define a new features list called NAME and its related readers."
`(progn
(declaim (type list ,name))
(defparameter ,name ,value ,documentation)
- (set-dispatch-macro-character #\# ,macro-character #'h-reader)))
+ (set-dispatch-macro-character #\# ,macro-character #'features-reader)))
;;; when-* macroes
;;; when-features
;;; when-not-features
;;; when-some-features
;;; when-not-some-features
;(when-features ((*features* :sbcl :linux)
; (*my-features* :all :good))
; (do-something))
;;; with-features
|
jasonroelofs/dev
|
75b68e33a7485f87578be219f11a1da42fd44e75
|
Change from Vundle to vim-plug and also add COC
|
diff --git a/profile b/profile
index 42796de..d5e5c6c 100644
--- a/profile
+++ b/profile
@@ -1,37 +1,40 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
+# No homebrew, you cannot send analytics
+export HOMEBREW_NO_ANALYTICS=1
+export PATH="/opt/homebrew/bin:/Users/jasonroelofs/.volta/bin:$PATH"
+
if [ -f `brew --prefix`/etc/profile.d/bash_completion.sh ]; then
. `brew --prefix`/etc/profile.d/bash_completion.sh
fi
export EDITOR=vim
-# No homebrew, you cannot send analytics
-export HOMEBREW_NO_ANALYTICS=1
-
# Enable kernel history in Erlang/Elixir (OTP 20 and later)
export ERL_AFLAGS="-kernel shell_history enabled"
# Shut up macOS, I know
export BASH_SILENCE_DEPRECATION_WARNING=1
# Make mvim available on the command line
export PATH="/Applications/MacVim.app/Contents/bin:$PATH"
-# ASDF
-export PATH="~/.asdf/shims:$PATH"
+# Ruby from Homebrew
+export PATH="/opt/homebrew/opt/ruby/bin:/opt/homebrew/lib/ruby/gems/3.3.0/bin:$PATH"
+export LDFLAGS="-L/opt/homebrew/opt/ruby/lib"
+export CPPFLAGS="-I/opt/homebrew/opt/ruby/include"
# Client-specific environment variables that we don't check into `dev`
if [ -f ~/.client-env ]; then
. ~/.client-env
fi
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
diff --git a/vim/autoload/plug.vim b/vim/autoload/plug.vim
new file mode 100644
index 0000000..940811a
--- /dev/null
+++ b/vim/autoload/plug.vim
@@ -0,0 +1,2858 @@
+" vim-plug: Vim plugin manager
+" ============================
+"
+" Download plug.vim and put it in ~/.vim/autoload
+"
+" curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
+" https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
+"
+" Edit your .vimrc
+"
+" call plug#begin('~/.vim/plugged')
+"
+" " Make sure you use single quotes
+"
+" " Shorthand notation; fetches https://github.com/junegunn/vim-easy-align
+" Plug 'junegunn/vim-easy-align'
+"
+" " Any valid git URL is allowed
+" Plug 'https://github.com/junegunn/vim-github-dashboard.git'
+"
+" " Multiple Plug commands can be written in a single line using | separators
+" Plug 'SirVer/ultisnips' | Plug 'honza/vim-snippets'
+"
+" " On-demand loading
+" Plug 'preservim/nerdtree', { 'on': 'NERDTreeToggle' }
+" Plug 'tpope/vim-fireplace', { 'for': 'clojure' }
+"
+" " Using a non-default branch
+" Plug 'rdnetto/YCM-Generator', { 'branch': 'stable' }
+"
+" " Using a tagged release; wildcard allowed (requires git 1.9.2 or above)
+" Plug 'fatih/vim-go', { 'tag': '*' }
+"
+" " Plugin options
+" Plug 'nsf/gocode', { 'tag': 'v.20150303', 'rtp': 'vim' }
+"
+" " Plugin outside ~/.vim/plugged with post-update hook
+" Plug 'junegunn/fzf', { 'dir': '~/.fzf', 'do': './install --all' }
+"
+" " Unmanaged plugin (manually installed and updated)
+" Plug '~/my-prototype-plugin'
+"
+" " Initialize plugin system
+" call plug#end()
+"
+" Then reload .vimrc and :PlugInstall to install plugins.
+"
+" Plug options:
+"
+"| Option | Description |
+"| ----------------------- | ------------------------------------------------ |
+"| `branch`/`tag`/`commit` | Branch/tag/commit of the repository to use |
+"| `rtp` | Subdirectory that contains Vim plugin |
+"| `dir` | Custom directory for the plugin |
+"| `as` | Use different name for the plugin |
+"| `do` | Post-update hook (string or funcref) |
+"| `on` | On-demand loading: Commands or `<Plug>`-mappings |
+"| `for` | On-demand loading: File types |
+"| `frozen` | Do not update unless explicitly specified |
+"
+" More information: https://github.com/junegunn/vim-plug
+"
+"
+" Copyright (c) 2017 Junegunn Choi
+"
+" MIT License
+"
+" Permission is hereby granted, free of charge, to any person obtaining
+" a copy of this software and associated documentation files (the
+" "Software"), to deal in the Software without restriction, including
+" without limitation the rights to use, copy, modify, merge, publish,
+" distribute, sublicense, and/or sell copies of the Software, and to
+" permit persons to whom the Software is furnished to do so, subject to
+" the following conditions:
+"
+" The above copyright notice and this permission notice shall be
+" included in all copies or substantial portions of the Software.
+"
+" THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+" EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+" MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+" NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+" LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+" OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+" WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+if exists('g:loaded_plug')
+ finish
+endif
+let g:loaded_plug = 1
+
+let s:cpo_save = &cpo
+set cpo&vim
+
+let s:plug_src = 'https://github.com/junegunn/vim-plug.git'
+let s:plug_tab = get(s:, 'plug_tab', -1)
+let s:plug_buf = get(s:, 'plug_buf', -1)
+let s:mac_gui = has('gui_macvim') && has('gui_running')
+let s:is_win = has('win32')
+let s:nvim = has('nvim-0.2') || (has('nvim') && exists('*jobwait') && !s:is_win)
+let s:vim8 = has('patch-8.0.0039') && exists('*job_start')
+if s:is_win && &shellslash
+ set noshellslash
+ let s:me = resolve(expand('<sfile>:p'))
+ set shellslash
+else
+ let s:me = resolve(expand('<sfile>:p'))
+endif
+let s:base_spec = { 'branch': '', 'frozen': 0 }
+let s:TYPE = {
+\ 'string': type(''),
+\ 'list': type([]),
+\ 'dict': type({}),
+\ 'funcref': type(function('call'))
+\ }
+let s:loaded = get(s:, 'loaded', {})
+let s:triggers = get(s:, 'triggers', {})
+
+function! s:is_powershell(shell)
+ return a:shell =~# 'powershell\(\.exe\)\?$' || a:shell =~# 'pwsh\(\.exe\)\?$'
+endfunction
+
+function! s:isabsolute(dir) abort
+ return a:dir =~# '^/' || (has('win32') && a:dir =~? '^\%(\\\|[A-Z]:\)')
+endfunction
+
+function! s:git_dir(dir) abort
+ let gitdir = s:trim(a:dir) . '/.git'
+ if isdirectory(gitdir)
+ return gitdir
+ endif
+ if !filereadable(gitdir)
+ return ''
+ endif
+ let gitdir = matchstr(get(readfile(gitdir), 0, ''), '^gitdir: \zs.*')
+ if len(gitdir) && !s:isabsolute(gitdir)
+ let gitdir = a:dir . '/' . gitdir
+ endif
+ return isdirectory(gitdir) ? gitdir : ''
+endfunction
+
+function! s:git_origin_url(dir) abort
+ let gitdir = s:git_dir(a:dir)
+ let config = gitdir . '/config'
+ if empty(gitdir) || !filereadable(config)
+ return ''
+ endif
+ return matchstr(join(readfile(config)), '\[remote "origin"\].\{-}url\s*=\s*\zs\S*\ze')
+endfunction
+
+function! s:git_revision(dir) abort
+ let gitdir = s:git_dir(a:dir)
+ let head = gitdir . '/HEAD'
+ if empty(gitdir) || !filereadable(head)
+ return ''
+ endif
+
+ let line = get(readfile(head), 0, '')
+ let ref = matchstr(line, '^ref: \zs.*')
+ if empty(ref)
+ return line
+ endif
+
+ if filereadable(gitdir . '/' . ref)
+ return get(readfile(gitdir . '/' . ref), 0, '')
+ endif
+
+ if filereadable(gitdir . '/packed-refs')
+ for line in readfile(gitdir . '/packed-refs')
+ if line =~# ' ' . ref
+ return matchstr(line, '^[0-9a-f]*')
+ endif
+ endfor
+ endif
+
+ return ''
+endfunction
+
+function! s:git_local_branch(dir) abort
+ let gitdir = s:git_dir(a:dir)
+ let head = gitdir . '/HEAD'
+ if empty(gitdir) || !filereadable(head)
+ return ''
+ endif
+ let branch = matchstr(get(readfile(head), 0, ''), '^ref: refs/heads/\zs.*')
+ return len(branch) ? branch : 'HEAD'
+endfunction
+
+function! s:git_origin_branch(spec)
+ if len(a:spec.branch)
+ return a:spec.branch
+ endif
+
+ " The file may not be present if this is a local repository
+ let gitdir = s:git_dir(a:spec.dir)
+ let origin_head = gitdir.'/refs/remotes/origin/HEAD'
+ if len(gitdir) && filereadable(origin_head)
+ return matchstr(get(readfile(origin_head), 0, ''),
+ \ '^ref: refs/remotes/origin/\zs.*')
+ endif
+
+ " The command may not return the name of a branch in detached HEAD state
+ let result = s:lines(s:system('git symbolic-ref --short HEAD', a:spec.dir))
+ return v:shell_error ? '' : result[-1]
+endfunction
+
+if s:is_win
+ function! s:plug_call(fn, ...)
+ let shellslash = &shellslash
+ try
+ set noshellslash
+ return call(a:fn, a:000)
+ finally
+ let &shellslash = shellslash
+ endtry
+ endfunction
+else
+ function! s:plug_call(fn, ...)
+ return call(a:fn, a:000)
+ endfunction
+endif
+
+function! s:plug_getcwd()
+ return s:plug_call('getcwd')
+endfunction
+
+function! s:plug_fnamemodify(fname, mods)
+ return s:plug_call('fnamemodify', a:fname, a:mods)
+endfunction
+
+function! s:plug_expand(fmt)
+ return s:plug_call('expand', a:fmt, 1)
+endfunction
+
+function! s:plug_tempname()
+ return s:plug_call('tempname')
+endfunction
+
+function! plug#begin(...)
+ if a:0 > 0
+ let home = s:path(s:plug_fnamemodify(s:plug_expand(a:1), ':p'))
+ elseif exists('g:plug_home')
+ let home = s:path(g:plug_home)
+ elseif has('nvim')
+ let home = stdpath('data') . '/plugged'
+ elseif !empty(&rtp)
+ let home = s:path(split(&rtp, ',')[0]) . '/plugged'
+ else
+ return s:err('Unable to determine plug home. Try calling plug#begin() with a path argument.')
+ endif
+ if s:plug_fnamemodify(home, ':t') ==# 'plugin' && s:plug_fnamemodify(home, ':h') ==# s:first_rtp
+ return s:err('Invalid plug home. '.home.' is a standard Vim runtime path and is not allowed.')
+ endif
+
+ let g:plug_home = home
+ let g:plugs = {}
+ let g:plugs_order = []
+ let s:triggers = {}
+
+ call s:define_commands()
+ return 1
+endfunction
+
+function! s:define_commands()
+ command! -nargs=+ -bar Plug call plug#(<args>)
+ if !executable('git')
+ return s:err('`git` executable not found. Most commands will not be available. To suppress this message, prepend `silent!` to `call plug#begin(...)`.')
+ endif
+ if has('win32')
+ \ && &shellslash
+ \ && (&shell =~# 'cmd\(\.exe\)\?$' || s:is_powershell(&shell))
+ return s:err('vim-plug does not support shell, ' . &shell . ', when shellslash is set.')
+ endif
+ if !has('nvim')
+ \ && (has('win32') || has('win32unix'))
+ \ && !has('multi_byte')
+ return s:err('Vim needs +multi_byte feature on Windows to run shell commands. Enable +iconv for best results.')
+ endif
+ command! -nargs=* -bar -bang -complete=customlist,s:names PlugInstall call s:install(<bang>0, [<f-args>])
+ command! -nargs=* -bar -bang -complete=customlist,s:names PlugUpdate call s:update(<bang>0, [<f-args>])
+ command! -nargs=0 -bar -bang PlugClean call s:clean(<bang>0)
+ command! -nargs=0 -bar PlugUpgrade if s:upgrade() | execute 'source' s:esc(s:me) | endif
+ command! -nargs=0 -bar PlugStatus call s:status()
+ command! -nargs=0 -bar PlugDiff call s:diff()
+ command! -nargs=? -bar -bang -complete=file PlugSnapshot call s:snapshot(<bang>0, <f-args>)
+endfunction
+
+function! s:to_a(v)
+ return type(a:v) == s:TYPE.list ? a:v : [a:v]
+endfunction
+
+function! s:to_s(v)
+ return type(a:v) == s:TYPE.string ? a:v : join(a:v, "\n") . "\n"
+endfunction
+
+function! s:glob(from, pattern)
+ return s:lines(globpath(a:from, a:pattern))
+endfunction
+
+function! s:source(from, ...)
+ let found = 0
+ for pattern in a:000
+ for vim in s:glob(a:from, pattern)
+ execute 'source' s:esc(vim)
+ let found = 1
+ endfor
+ endfor
+ return found
+endfunction
+
+function! s:assoc(dict, key, val)
+ let a:dict[a:key] = add(get(a:dict, a:key, []), a:val)
+endfunction
+
+function! s:ask(message, ...)
+ call inputsave()
+ echohl WarningMsg
+ let answer = input(a:message.(a:0 ? ' (y/N/a) ' : ' (y/N) '))
+ echohl None
+ call inputrestore()
+ echo "\r"
+ return (a:0 && answer =~? '^a') ? 2 : (answer =~? '^y') ? 1 : 0
+endfunction
+
+function! s:ask_no_interrupt(...)
+ try
+ return call('s:ask', a:000)
+ catch
+ return 0
+ endtry
+endfunction
+
+function! s:lazy(plug, opt)
+ return has_key(a:plug, a:opt) &&
+ \ (empty(s:to_a(a:plug[a:opt])) ||
+ \ !isdirectory(a:plug.dir) ||
+ \ len(s:glob(s:rtp(a:plug), 'plugin')) ||
+ \ len(s:glob(s:rtp(a:plug), 'after/plugin')))
+endfunction
+
+function! plug#end()
+ if !exists('g:plugs')
+ return s:err('plug#end() called without calling plug#begin() first')
+ endif
+
+ if exists('#PlugLOD')
+ augroup PlugLOD
+ autocmd!
+ augroup END
+ augroup! PlugLOD
+ endif
+ let lod = { 'ft': {}, 'map': {}, 'cmd': {} }
+
+ if get(g:, 'did_load_filetypes', 0)
+ filetype off
+ endif
+ for name in g:plugs_order
+ if !has_key(g:plugs, name)
+ continue
+ endif
+ let plug = g:plugs[name]
+ if get(s:loaded, name, 0) || !s:lazy(plug, 'on') && !s:lazy(plug, 'for')
+ let s:loaded[name] = 1
+ continue
+ endif
+
+ if has_key(plug, 'on')
+ let s:triggers[name] = { 'map': [], 'cmd': [] }
+ for cmd in s:to_a(plug.on)
+ if cmd =~? '^<Plug>.\+'
+ if empty(mapcheck(cmd)) && empty(mapcheck(cmd, 'i'))
+ call s:assoc(lod.map, cmd, name)
+ endif
+ call add(s:triggers[name].map, cmd)
+ elseif cmd =~# '^[A-Z]'
+ let cmd = substitute(cmd, '!*$', '', '')
+ if exists(':'.cmd) != 2
+ call s:assoc(lod.cmd, cmd, name)
+ endif
+ call add(s:triggers[name].cmd, cmd)
+ else
+ call s:err('Invalid `on` option: '.cmd.
+ \ '. Should start with an uppercase letter or `<Plug>`.')
+ endif
+ endfor
+ endif
+
+ if has_key(plug, 'for')
+ let types = s:to_a(plug.for)
+ if !empty(types)
+ augroup filetypedetect
+ call s:source(s:rtp(plug), 'ftdetect/**/*.vim', 'after/ftdetect/**/*.vim')
+ if has('nvim-0.5.0')
+ call s:source(s:rtp(plug), 'ftdetect/**/*.lua', 'after/ftdetect/**/*.lua')
+ endif
+ augroup END
+ endif
+ for type in types
+ call s:assoc(lod.ft, type, name)
+ endfor
+ endif
+ endfor
+
+ for [cmd, names] in items(lod.cmd)
+ execute printf(
+ \ 'command! -nargs=* -range -bang -complete=file %s call s:lod_cmd(%s, "<bang>", <line1>, <line2>, <q-args>, %s)',
+ \ cmd, string(cmd), string(names))
+ endfor
+
+ for [map, names] in items(lod.map)
+ for [mode, map_prefix, key_prefix] in
+ \ [['i', '<C-\><C-O>', ''], ['n', '', ''], ['v', '', 'gv'], ['o', '', '']]
+ execute printf(
+ \ '%snoremap <silent> %s %s:<C-U>call <SID>lod_map(%s, %s, %s, "%s")<CR>',
+ \ mode, map, map_prefix, string(map), string(names), mode != 'i', key_prefix)
+ endfor
+ endfor
+
+ for [ft, names] in items(lod.ft)
+ augroup PlugLOD
+ execute printf('autocmd FileType %s call <SID>lod_ft(%s, %s)',
+ \ ft, string(ft), string(names))
+ augroup END
+ endfor
+
+ call s:reorg_rtp()
+ filetype plugin indent on
+ if has('vim_starting')
+ if has('syntax') && !exists('g:syntax_on')
+ syntax enable
+ end
+ else
+ call s:reload_plugins()
+ endif
+endfunction
+
+function! s:loaded_names()
+ return filter(copy(g:plugs_order), 'get(s:loaded, v:val, 0)')
+endfunction
+
+function! s:load_plugin(spec)
+ call s:source(s:rtp(a:spec), 'plugin/**/*.vim', 'after/plugin/**/*.vim')
+ if has('nvim-0.5.0')
+ call s:source(s:rtp(a:spec), 'plugin/**/*.lua', 'after/plugin/**/*.lua')
+ endif
+endfunction
+
+function! s:reload_plugins()
+ for name in s:loaded_names()
+ call s:load_plugin(g:plugs[name])
+ endfor
+endfunction
+
+function! s:trim(str)
+ return substitute(a:str, '[\/]\+$', '', '')
+endfunction
+
+function! s:version_requirement(val, min)
+ for idx in range(0, len(a:min) - 1)
+ let v = get(a:val, idx, 0)
+ if v < a:min[idx] | return 0
+ elseif v > a:min[idx] | return 1
+ endif
+ endfor
+ return 1
+endfunction
+
+function! s:git_version_requirement(...)
+ if !exists('s:git_version')
+ let s:git_version = map(split(split(s:system(['git', '--version']))[2], '\.'), 'str2nr(v:val)')
+ endif
+ return s:version_requirement(s:git_version, a:000)
+endfunction
+
+function! s:progress_opt(base)
+ return a:base && !s:is_win &&
+ \ s:git_version_requirement(1, 7, 1) ? '--progress' : ''
+endfunction
+
+function! s:rtp(spec)
+ return s:path(a:spec.dir . get(a:spec, 'rtp', ''))
+endfunction
+
+if s:is_win
+ function! s:path(path)
+ return s:trim(substitute(a:path, '/', '\', 'g'))
+ endfunction
+
+ function! s:dirpath(path)
+ return s:path(a:path) . '\'
+ endfunction
+
+ function! s:is_local_plug(repo)
+ return a:repo =~? '^[a-z]:\|^[%~]'
+ endfunction
+
+ " Copied from fzf
+ function! s:wrap_cmds(cmds)
+ let cmds = [
+ \ '@echo off',
+ \ 'setlocal enabledelayedexpansion']
+ \ + (type(a:cmds) == type([]) ? a:cmds : [a:cmds])
+ \ + ['endlocal']
+ if has('iconv')
+ if !exists('s:codepage')
+ let s:codepage = libcallnr('kernel32.dll', 'GetACP', 0)
+ endif
+ return map(cmds, printf('iconv(v:val."\r", "%s", "cp%d")', &encoding, s:codepage))
+ endif
+ return map(cmds, 'v:val."\r"')
+ endfunction
+
+ function! s:batchfile(cmd)
+ let batchfile = s:plug_tempname().'.bat'
+ call writefile(s:wrap_cmds(a:cmd), batchfile)
+ let cmd = plug#shellescape(batchfile, {'shell': &shell, 'script': 0})
+ if s:is_powershell(&shell)
+ let cmd = '& ' . cmd
+ endif
+ return [batchfile, cmd]
+ endfunction
+else
+ function! s:path(path)
+ return s:trim(a:path)
+ endfunction
+
+ function! s:dirpath(path)
+ return substitute(a:path, '[/\\]*$', '/', '')
+ endfunction
+
+ function! s:is_local_plug(repo)
+ return a:repo[0] =~ '[/$~]'
+ endfunction
+endif
+
+function! s:err(msg)
+ echohl ErrorMsg
+ echom '[vim-plug] '.a:msg
+ echohl None
+endfunction
+
+function! s:warn(cmd, msg)
+ echohl WarningMsg
+ execute a:cmd 'a:msg'
+ echohl None
+endfunction
+
+function! s:esc(path)
+ return escape(a:path, ' ')
+endfunction
+
+function! s:escrtp(path)
+ return escape(a:path, ' ,')
+endfunction
+
+function! s:remove_rtp()
+ for name in s:loaded_names()
+ let rtp = s:rtp(g:plugs[name])
+ execute 'set rtp-='.s:escrtp(rtp)
+ let after = globpath(rtp, 'after')
+ if isdirectory(after)
+ execute 'set rtp-='.s:escrtp(after)
+ endif
+ endfor
+endfunction
+
+function! s:reorg_rtp()
+ if !empty(s:first_rtp)
+ execute 'set rtp-='.s:first_rtp
+ execute 'set rtp-='.s:last_rtp
+ endif
+
+ " &rtp is modified from outside
+ if exists('s:prtp') && s:prtp !=# &rtp
+ call s:remove_rtp()
+ unlet! s:middle
+ endif
+
+ let s:middle = get(s:, 'middle', &rtp)
+ let rtps = map(s:loaded_names(), 's:rtp(g:plugs[v:val])')
+ let afters = filter(map(copy(rtps), 'globpath(v:val, "after")'), '!empty(v:val)')
+ let rtp = join(map(rtps, 'escape(v:val, ",")'), ',')
+ \ . ','.s:middle.','
+ \ . join(map(afters, 'escape(v:val, ",")'), ',')
+ let &rtp = substitute(substitute(rtp, ',,*', ',', 'g'), '^,\|,$', '', 'g')
+ let s:prtp = &rtp
+
+ if !empty(s:first_rtp)
+ execute 'set rtp^='.s:first_rtp
+ execute 'set rtp+='.s:last_rtp
+ endif
+endfunction
+
+function! s:doautocmd(...)
+ if exists('#'.join(a:000, '#'))
+ execute 'doautocmd' ((v:version > 703 || has('patch442')) ? '<nomodeline>' : '') join(a:000)
+ endif
+endfunction
+
+function! s:dobufread(names)
+ for name in a:names
+ let path = s:rtp(g:plugs[name])
+ for dir in ['ftdetect', 'ftplugin', 'after/ftdetect', 'after/ftplugin']
+ if len(finddir(dir, path))
+ if exists('#BufRead')
+ doautocmd BufRead
+ endif
+ return
+ endif
+ endfor
+ endfor
+endfunction
+
+function! plug#load(...)
+ if a:0 == 0
+ return s:err('Argument missing: plugin name(s) required')
+ endif
+ if !exists('g:plugs')
+ return s:err('plug#begin was not called')
+ endif
+ let names = a:0 == 1 && type(a:1) == s:TYPE.list ? a:1 : a:000
+ let unknowns = filter(copy(names), '!has_key(g:plugs, v:val)')
+ if !empty(unknowns)
+ let s = len(unknowns) > 1 ? 's' : ''
+ return s:err(printf('Unknown plugin%s: %s', s, join(unknowns, ', ')))
+ end
+ let unloaded = filter(copy(names), '!get(s:loaded, v:val, 0)')
+ if !empty(unloaded)
+ for name in unloaded
+ call s:lod([name], ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ endfor
+ call s:dobufread(unloaded)
+ return 1
+ end
+ return 0
+endfunction
+
+function! s:remove_triggers(name)
+ if !has_key(s:triggers, a:name)
+ return
+ endif
+ for cmd in s:triggers[a:name].cmd
+ execute 'silent! delc' cmd
+ endfor
+ for map in s:triggers[a:name].map
+ execute 'silent! unmap' map
+ execute 'silent! iunmap' map
+ endfor
+ call remove(s:triggers, a:name)
+endfunction
+
+function! s:lod(names, types, ...)
+ for name in a:names
+ call s:remove_triggers(name)
+ let s:loaded[name] = 1
+ endfor
+ call s:reorg_rtp()
+
+ for name in a:names
+ let rtp = s:rtp(g:plugs[name])
+ for dir in a:types
+ call s:source(rtp, dir.'/**/*.vim')
+ if has('nvim-0.5.0') " see neovim#14686
+ call s:source(rtp, dir.'/**/*.lua')
+ endif
+ endfor
+ if a:0
+ if !s:source(rtp, a:1) && !empty(s:glob(rtp, a:2))
+ execute 'runtime' a:1
+ endif
+ call s:source(rtp, a:2)
+ endif
+ call s:doautocmd('User', name)
+ endfor
+endfunction
+
+function! s:lod_ft(pat, names)
+ let syn = 'syntax/'.a:pat.'.vim'
+ call s:lod(a:names, ['plugin', 'after/plugin'], syn, 'after/'.syn)
+ execute 'autocmd! PlugLOD FileType' a:pat
+ call s:doautocmd('filetypeplugin', 'FileType')
+ call s:doautocmd('filetypeindent', 'FileType')
+endfunction
+
+function! s:lod_cmd(cmd, bang, l1, l2, args, names)
+ call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ call s:dobufread(a:names)
+ execute printf('%s%s%s %s', (a:l1 == a:l2 ? '' : (a:l1.','.a:l2)), a:cmd, a:bang, a:args)
+endfunction
+
+function! s:lod_map(map, names, with_prefix, prefix)
+ call s:lod(a:names, ['ftdetect', 'after/ftdetect', 'plugin', 'after/plugin'])
+ call s:dobufread(a:names)
+ let extra = ''
+ while 1
+ let c = getchar(0)
+ if c == 0
+ break
+ endif
+ let extra .= nr2char(c)
+ endwhile
+
+ if a:with_prefix
+ let prefix = v:count ? v:count : ''
+ let prefix .= '"'.v:register.a:prefix
+ if mode(1) == 'no'
+ if v:operator == 'c'
+ let prefix = "\<esc>" . prefix
+ endif
+ let prefix .= v:operator
+ endif
+ call feedkeys(prefix, 'n')
+ endif
+ call feedkeys(substitute(a:map, '^<Plug>', "\<Plug>", '') . extra)
+endfunction
+
+function! plug#(repo, ...)
+ if a:0 > 1
+ return s:err('Invalid number of arguments (1..2)')
+ endif
+
+ try
+ let repo = s:trim(a:repo)
+ let opts = a:0 == 1 ? s:parse_options(a:1) : s:base_spec
+ let name = get(opts, 'as', s:plug_fnamemodify(repo, ':t:s?\.git$??'))
+ let spec = extend(s:infer_properties(name, repo), opts)
+ if !has_key(g:plugs, name)
+ call add(g:plugs_order, name)
+ endif
+ let g:plugs[name] = spec
+ let s:loaded[name] = get(s:loaded, name, 0)
+ catch
+ return s:err(repo . ' ' . v:exception)
+ endtry
+endfunction
+
+function! s:parse_options(arg)
+ let opts = copy(s:base_spec)
+ let type = type(a:arg)
+ let opt_errfmt = 'Invalid argument for "%s" option of :Plug (expected: %s)'
+ if type == s:TYPE.string
+ if empty(a:arg)
+ throw printf(opt_errfmt, 'tag', 'string')
+ endif
+ let opts.tag = a:arg
+ elseif type == s:TYPE.dict
+ for opt in ['branch', 'tag', 'commit', 'rtp', 'dir', 'as']
+ if has_key(a:arg, opt)
+ \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt]))
+ throw printf(opt_errfmt, opt, 'string')
+ endif
+ endfor
+ for opt in ['on', 'for']
+ if has_key(a:arg, opt)
+ \ && type(a:arg[opt]) != s:TYPE.list
+ \ && (type(a:arg[opt]) != s:TYPE.string || empty(a:arg[opt]))
+ throw printf(opt_errfmt, opt, 'string or list')
+ endif
+ endfor
+ if has_key(a:arg, 'do')
+ \ && type(a:arg.do) != s:TYPE.funcref
+ \ && (type(a:arg.do) != s:TYPE.string || empty(a:arg.do))
+ throw printf(opt_errfmt, 'do', 'string or funcref')
+ endif
+ call extend(opts, a:arg)
+ if has_key(opts, 'dir')
+ let opts.dir = s:dirpath(s:plug_expand(opts.dir))
+ endif
+ else
+ throw 'Invalid argument type (expected: string or dictionary)'
+ endif
+ return opts
+endfunction
+
+function! s:infer_properties(name, repo)
+ let repo = a:repo
+ if s:is_local_plug(repo)
+ return { 'dir': s:dirpath(s:plug_expand(repo)) }
+ else
+ if repo =~ ':'
+ let uri = repo
+ else
+ if repo !~ '/'
+ throw printf('Invalid argument: %s (implicit `vim-scripts'' expansion is deprecated)', repo)
+ endif
+ let fmt = get(g:, 'plug_url_format', 'https://git::@github.com/%s.git')
+ let uri = printf(fmt, repo)
+ endif
+ return { 'dir': s:dirpath(g:plug_home.'/'.a:name), 'uri': uri }
+ endif
+endfunction
+
+function! s:install(force, names)
+ call s:update_impl(0, a:force, a:names)
+endfunction
+
+function! s:update(force, names)
+ call s:update_impl(1, a:force, a:names)
+endfunction
+
+function! plug#helptags()
+ if !exists('g:plugs')
+ return s:err('plug#begin was not called')
+ endif
+ for spec in values(g:plugs)
+ let docd = join([s:rtp(spec), 'doc'], '/')
+ if isdirectory(docd)
+ silent! execute 'helptags' s:esc(docd)
+ endif
+ endfor
+ return 1
+endfunction
+
+function! s:syntax()
+ syntax clear
+ syntax region plug1 start=/\%1l/ end=/\%2l/ contains=plugNumber
+ syntax region plug2 start=/\%2l/ end=/\%3l/ contains=plugBracket,plugX
+ syn match plugNumber /[0-9]\+[0-9.]*/ contained
+ syn match plugBracket /[[\]]/ contained
+ syn match plugX /x/ contained
+ syn match plugDash /^-\{1}\ /
+ syn match plugPlus /^+/
+ syn match plugStar /^*/
+ syn match plugMessage /\(^- \)\@<=.*/
+ syn match plugName /\(^- \)\@<=[^ ]*:/
+ syn match plugSha /\%(: \)\@<=[0-9a-f]\{4,}$/
+ syn match plugTag /(tag: [^)]\+)/
+ syn match plugInstall /\(^+ \)\@<=[^:]*/
+ syn match plugUpdate /\(^* \)\@<=[^:]*/
+ syn match plugCommit /^ \X*[0-9a-f]\{7,9} .*/ contains=plugRelDate,plugEdge,plugTag
+ syn match plugEdge /^ \X\+$/
+ syn match plugEdge /^ \X*/ contained nextgroup=plugSha
+ syn match plugSha /[0-9a-f]\{7,9}/ contained
+ syn match plugRelDate /([^)]*)$/ contained
+ syn match plugNotLoaded /(not loaded)$/
+ syn match plugError /^x.*/
+ syn region plugDeleted start=/^\~ .*/ end=/^\ze\S/
+ syn match plugH2 /^.*:\n-\+$/
+ syn match plugH2 /^-\{2,}/
+ syn keyword Function PlugInstall PlugStatus PlugUpdate PlugClean
+ hi def link plug1 Title
+ hi def link plug2 Repeat
+ hi def link plugH2 Type
+ hi def link plugX Exception
+ hi def link plugBracket Structure
+ hi def link plugNumber Number
+
+ hi def link plugDash Special
+ hi def link plugPlus Constant
+ hi def link plugStar Boolean
+
+ hi def link plugMessage Function
+ hi def link plugName Label
+ hi def link plugInstall Function
+ hi def link plugUpdate Type
+
+ hi def link plugError Error
+ hi def link plugDeleted Ignore
+ hi def link plugRelDate Comment
+ hi def link plugEdge PreProc
+ hi def link plugSha Identifier
+ hi def link plugTag Constant
+
+ hi def link plugNotLoaded Comment
+endfunction
+
+function! s:lpad(str, len)
+ return a:str . repeat(' ', a:len - len(a:str))
+endfunction
+
+function! s:lines(msg)
+ return split(a:msg, "[\r\n]")
+endfunction
+
+function! s:lastline(msg)
+ return get(s:lines(a:msg), -1, '')
+endfunction
+
+function! s:new_window()
+ execute get(g:, 'plug_window', '-tabnew')
+endfunction
+
+function! s:plug_window_exists()
+ let buflist = tabpagebuflist(s:plug_tab)
+ return !empty(buflist) && index(buflist, s:plug_buf) >= 0
+endfunction
+
+function! s:switch_in()
+ if !s:plug_window_exists()
+ return 0
+ endif
+
+ if winbufnr(0) != s:plug_buf
+ let s:pos = [tabpagenr(), winnr(), winsaveview()]
+ execute 'normal!' s:plug_tab.'gt'
+ let winnr = bufwinnr(s:plug_buf)
+ execute winnr.'wincmd w'
+ call add(s:pos, winsaveview())
+ else
+ let s:pos = [winsaveview()]
+ endif
+
+ setlocal modifiable
+ return 1
+endfunction
+
+function! s:switch_out(...)
+ call winrestview(s:pos[-1])
+ setlocal nomodifiable
+ if a:0 > 0
+ execute a:1
+ endif
+
+ if len(s:pos) > 1
+ execute 'normal!' s:pos[0].'gt'
+ execute s:pos[1] 'wincmd w'
+ call winrestview(s:pos[2])
+ endif
+endfunction
+
+function! s:finish_bindings()
+ nnoremap <silent> <buffer> R :call <SID>retry()<cr>
+ nnoremap <silent> <buffer> D :PlugDiff<cr>
+ nnoremap <silent> <buffer> S :PlugStatus<cr>
+ nnoremap <silent> <buffer> U :call <SID>status_update()<cr>
+ xnoremap <silent> <buffer> U :call <SID>status_update()<cr>
+ nnoremap <silent> <buffer> ]] :silent! call <SID>section('')<cr>
+ nnoremap <silent> <buffer> [[ :silent! call <SID>section('b')<cr>
+endfunction
+
+function! s:prepare(...)
+ if empty(s:plug_getcwd())
+ throw 'Invalid current working directory. Cannot proceed.'
+ endif
+
+ for evar in ['$GIT_DIR', '$GIT_WORK_TREE']
+ if exists(evar)
+ throw evar.' detected. Cannot proceed.'
+ endif
+ endfor
+
+ call s:job_abort()
+ if s:switch_in()
+ if b:plug_preview == 1
+ pc
+ endif
+ enew
+ else
+ call s:new_window()
+ endif
+
+ nnoremap <silent> <buffer> q :call <SID>close_pane()<cr>
+ if a:0 == 0
+ call s:finish_bindings()
+ endif
+ let b:plug_preview = -1
+ let s:plug_tab = tabpagenr()
+ let s:plug_buf = winbufnr(0)
+ call s:assign_name()
+
+ for k in ['<cr>', 'L', 'o', 'X', 'd', 'dd']
+ execute 'silent! unmap <buffer>' k
+ endfor
+ setlocal buftype=nofile bufhidden=wipe nobuflisted nolist noswapfile nowrap cursorline modifiable nospell
+ if exists('+colorcolumn')
+ setlocal colorcolumn=
+ endif
+ setf vim-plug
+ if exists('g:syntax_on')
+ call s:syntax()
+ endif
+endfunction
+
+function! s:close_pane()
+ if b:plug_preview == 1
+ pc
+ let b:plug_preview = -1
+ else
+ bd
+ endif
+endfunction
+
+function! s:assign_name()
+ " Assign buffer name
+ let prefix = '[Plugins]'
+ let name = prefix
+ let idx = 2
+ while bufexists(name)
+ let name = printf('%s (%s)', prefix, idx)
+ let idx = idx + 1
+ endwhile
+ silent! execute 'f' fnameescape(name)
+endfunction
+
+function! s:chsh(swap)
+ let prev = [&shell, &shellcmdflag, &shellredir]
+ if !s:is_win
+ set shell=sh
+ endif
+ if a:swap
+ if s:is_powershell(&shell)
+ let &shellredir = '2>&1 | Out-File -Encoding UTF8 %s'
+ elseif &shell =~# 'sh' || &shell =~# 'cmd\(\.exe\)\?$'
+ set shellredir=>%s\ 2>&1
+ endif
+ endif
+ return prev
+endfunction
+
+function! s:bang(cmd, ...)
+ let batchfile = ''
+ try
+ let [sh, shellcmdflag, shrd] = s:chsh(a:0)
+ " FIXME: Escaping is incomplete. We could use shellescape with eval,
+ " but it won't work on Windows.
+ let cmd = a:0 ? s:with_cd(a:cmd, a:1) : a:cmd
+ if s:is_win
+ let [batchfile, cmd] = s:batchfile(cmd)
+ endif
+ let g:_plug_bang = (s:is_win && has('gui_running') ? 'silent ' : '').'!'.escape(cmd, '#!%')
+ execute "normal! :execute g:_plug_bang\<cr>\<cr>"
+ finally
+ unlet g:_plug_bang
+ let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
+ if s:is_win && filereadable(batchfile)
+ call delete(batchfile)
+ endif
+ endtry
+ return v:shell_error ? 'Exit status: ' . v:shell_error : ''
+endfunction
+
+function! s:regress_bar()
+ let bar = substitute(getline(2)[1:-2], '.*\zs=', 'x', '')
+ call s:progress_bar(2, bar, len(bar))
+endfunction
+
+function! s:is_updated(dir)
+ return !empty(s:system_chomp(['git', 'log', '--pretty=format:%h', 'HEAD...HEAD@{1}'], a:dir))
+endfunction
+
+function! s:do(pull, force, todo)
+ if has('nvim')
+ " Reset &rtp to invalidate Neovim cache of loaded Lua modules
+ " See https://github.com/junegunn/vim-plug/pull/1157#issuecomment-1809226110
+ let &rtp = &rtp
+ endif
+ for [name, spec] in items(a:todo)
+ if !isdirectory(spec.dir)
+ continue
+ endif
+ let installed = has_key(s:update.new, name)
+ let updated = installed ? 0 :
+ \ (a:pull && index(s:update.errors, name) < 0 && s:is_updated(spec.dir))
+ if a:force || installed || updated
+ execute 'cd' s:esc(spec.dir)
+ call append(3, '- Post-update hook for '. name .' ... ')
+ let error = ''
+ let type = type(spec.do)
+ if type == s:TYPE.string
+ if spec.do[0] == ':'
+ if !get(s:loaded, name, 0)
+ let s:loaded[name] = 1
+ call s:reorg_rtp()
+ endif
+ call s:load_plugin(spec)
+ try
+ execute spec.do[1:]
+ catch
+ let error = v:exception
+ endtry
+ if !s:plug_window_exists()
+ cd -
+ throw 'Warning: vim-plug was terminated by the post-update hook of '.name
+ endif
+ else
+ let error = s:bang(spec.do)
+ endif
+ elseif type == s:TYPE.funcref
+ try
+ call s:load_plugin(spec)
+ let status = installed ? 'installed' : (updated ? 'updated' : 'unchanged')
+ call spec.do({ 'name': name, 'status': status, 'force': a:force })
+ catch
+ let error = v:exception
+ endtry
+ else
+ let error = 'Invalid hook type'
+ endif
+ call s:switch_in()
+ call setline(4, empty(error) ? (getline(4) . 'OK')
+ \ : ('x' . getline(4)[1:] . error))
+ if !empty(error)
+ call add(s:update.errors, name)
+ call s:regress_bar()
+ endif
+ cd -
+ endif
+ endfor
+endfunction
+
+function! s:hash_match(a, b)
+ return stridx(a:a, a:b) == 0 || stridx(a:b, a:a) == 0
+endfunction
+
+function! s:checkout(spec)
+ let sha = a:spec.commit
+ let output = s:git_revision(a:spec.dir)
+ let error = 0
+ if !empty(output) && !s:hash_match(sha, s:lines(output)[0])
+ let credential_helper = s:git_version_requirement(2) ? '-c credential.helper= ' : ''
+ let output = s:system(
+ \ 'git '.credential_helper.'fetch --depth 999999 && git checkout '.plug#shellescape(sha).' --', a:spec.dir)
+ let error = v:shell_error
+ endif
+ return [output, error]
+endfunction
+
+function! s:finish(pull)
+ let new_frozen = len(filter(keys(s:update.new), 'g:plugs[v:val].frozen'))
+ if new_frozen
+ let s = new_frozen > 1 ? 's' : ''
+ call append(3, printf('- Installed %d frozen plugin%s', new_frozen, s))
+ endif
+ call append(3, '- Finishing ... ') | 4
+ redraw
+ call plug#helptags()
+ call plug#end()
+ call setline(4, getline(4) . 'Done!')
+ redraw
+ let msgs = []
+ if !empty(s:update.errors)
+ call add(msgs, "Press 'R' to retry.")
+ endif
+ if a:pull && len(s:update.new) < len(filter(getline(5, '$'),
+ \ "v:val =~ '^- ' && v:val !~# 'Already up.to.date'"))
+ call add(msgs, "Press 'D' to see the updated changes.")
+ endif
+ echo join(msgs, ' ')
+ call s:finish_bindings()
+endfunction
+
+function! s:retry()
+ if empty(s:update.errors)
+ return
+ endif
+ echo
+ call s:update_impl(s:update.pull, s:update.force,
+ \ extend(copy(s:update.errors), [s:update.threads]))
+endfunction
+
+function! s:is_managed(name)
+ return has_key(g:plugs[a:name], 'uri')
+endfunction
+
+function! s:names(...)
+ return sort(filter(keys(g:plugs), 'stridx(v:val, a:1) == 0 && s:is_managed(v:val)'))
+endfunction
+
+function! s:check_ruby()
+ silent! ruby require 'thread'; VIM::command("let g:plug_ruby = '#{RUBY_VERSION}'")
+ if !exists('g:plug_ruby')
+ redraw!
+ return s:warn('echom', 'Warning: Ruby interface is broken')
+ endif
+ let ruby_version = split(g:plug_ruby, '\.')
+ unlet g:plug_ruby
+ return s:version_requirement(ruby_version, [1, 8, 7])
+endfunction
+
+function! s:update_impl(pull, force, args) abort
+ let sync = index(a:args, '--sync') >= 0 || has('vim_starting')
+ let args = filter(copy(a:args), 'v:val != "--sync"')
+ let threads = (len(args) > 0 && args[-1] =~ '^[1-9][0-9]*$') ?
+ \ remove(args, -1) : get(g:, 'plug_threads', 16)
+
+ let managed = filter(deepcopy(g:plugs), 's:is_managed(v:key)')
+ let todo = empty(args) ? filter(managed, '!v:val.frozen || !isdirectory(v:val.dir)') :
+ \ filter(managed, 'index(args, v:key) >= 0')
+
+ if empty(todo)
+ return s:warn('echo', 'No plugin to '. (a:pull ? 'update' : 'install'))
+ endif
+
+ if !s:is_win && s:git_version_requirement(2, 3)
+ let s:git_terminal_prompt = exists('$GIT_TERMINAL_PROMPT') ? $GIT_TERMINAL_PROMPT : ''
+ let $GIT_TERMINAL_PROMPT = 0
+ for plug in values(todo)
+ let plug.uri = substitute(plug.uri,
+ \ '^https://git::@github\.com', 'https://github.com', '')
+ endfor
+ endif
+
+ if !isdirectory(g:plug_home)
+ try
+ call mkdir(g:plug_home, 'p')
+ catch
+ return s:err(printf('Invalid plug directory: %s. '.
+ \ 'Try to call plug#begin with a valid directory', g:plug_home))
+ endtry
+ endif
+
+ if has('nvim') && !exists('*jobwait') && threads > 1
+ call s:warn('echom', '[vim-plug] Update Neovim for parallel installer')
+ endif
+
+ let use_job = s:nvim || s:vim8
+ let python = (has('python') || has('python3')) && !use_job
+ let ruby = has('ruby') && !use_job && (v:version >= 703 || v:version == 702 && has('patch374')) && !(s:is_win && has('gui_running')) && threads > 1 && s:check_ruby()
+
+ let s:update = {
+ \ 'start': reltime(),
+ \ 'all': todo,
+ \ 'todo': copy(todo),
+ \ 'errors': [],
+ \ 'pull': a:pull,
+ \ 'force': a:force,
+ \ 'new': {},
+ \ 'threads': (python || ruby || use_job) ? min([len(todo), threads]) : 1,
+ \ 'bar': '',
+ \ 'fin': 0
+ \ }
+
+ call s:prepare(1)
+ call append(0, ['', ''])
+ normal! 2G
+ silent! redraw
+
+ " Set remote name, overriding a possible user git config's clone.defaultRemoteName
+ let s:clone_opt = ['--origin', 'origin']
+ if get(g:, 'plug_shallow', 1)
+ call extend(s:clone_opt, ['--depth', '1'])
+ if s:git_version_requirement(1, 7, 10)
+ call add(s:clone_opt, '--no-single-branch')
+ endif
+ endif
+
+ if has('win32unix') || has('wsl')
+ call extend(s:clone_opt, ['-c', 'core.eol=lf', '-c', 'core.autocrlf=input'])
+ endif
+
+ let s:submodule_opt = s:git_version_requirement(2, 8) ? ' --jobs='.threads : ''
+
+ " Python version requirement (>= 2.7)
+ if python && !has('python3') && !ruby && !use_job && s:update.threads > 1
+ redir => pyv
+ silent python import platform; print platform.python_version()
+ redir END
+ let python = s:version_requirement(
+ \ map(split(split(pyv)[0], '\.'), 'str2nr(v:val)'), [2, 6])
+ endif
+
+ if (python || ruby) && s:update.threads > 1
+ try
+ let imd = &imd
+ if s:mac_gui
+ set noimd
+ endif
+ if ruby
+ call s:update_ruby()
+ else
+ call s:update_python()
+ endif
+ catch
+ let lines = getline(4, '$')
+ let printed = {}
+ silent! 4,$d _
+ for line in lines
+ let name = s:extract_name(line, '.', '')
+ if empty(name) || !has_key(printed, name)
+ call append('$', line)
+ if !empty(name)
+ let printed[name] = 1
+ if line[0] == 'x' && index(s:update.errors, name) < 0
+ call add(s:update.errors, name)
+ end
+ endif
+ endif
+ endfor
+ finally
+ let &imd = imd
+ call s:update_finish()
+ endtry
+ else
+ call s:update_vim()
+ while use_job && sync
+ sleep 100m
+ if s:update.fin
+ break
+ endif
+ endwhile
+ endif
+endfunction
+
+function! s:log4(name, msg)
+ call setline(4, printf('- %s (%s)', a:msg, a:name))
+ redraw
+endfunction
+
+function! s:update_finish()
+ if exists('s:git_terminal_prompt')
+ let $GIT_TERMINAL_PROMPT = s:git_terminal_prompt
+ endif
+ if s:switch_in()
+ call append(3, '- Updating ...') | 4
+ for [name, spec] in items(filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && (s:update.force || s:update.pull || has_key(s:update.new, v:key))'))
+ let [pos, _] = s:logpos(name)
+ if !pos
+ continue
+ endif
+ let out = ''
+ let error = 0
+ if has_key(spec, 'commit')
+ call s:log4(name, 'Checking out '.spec.commit)
+ let [out, error] = s:checkout(spec)
+ elseif has_key(spec, 'tag')
+ let tag = spec.tag
+ if tag =~ '\*'
+ let tags = s:lines(s:system('git tag --list '.plug#shellescape(tag).' --sort -version:refname 2>&1', spec.dir))
+ if !v:shell_error && !empty(tags)
+ let tag = tags[0]
+ call s:log4(name, printf('Latest tag for %s -> %s', spec.tag, tag))
+ call append(3, '')
+ endif
+ endif
+ call s:log4(name, 'Checking out '.tag)
+ let out = s:system('git checkout -q '.plug#shellescape(tag).' -- 2>&1', spec.dir)
+ let error = v:shell_error
+ endif
+ if !error && filereadable(spec.dir.'/.gitmodules') &&
+ \ (s:update.force || has_key(s:update.new, name) || s:is_updated(spec.dir))
+ call s:log4(name, 'Updating submodules. This may take a while.')
+ let out .= s:bang('git submodule update --init --recursive'.s:submodule_opt.' 2>&1', spec.dir)
+ let error = v:shell_error
+ endif
+ let msg = s:format_message(v:shell_error ? 'x': '-', name, out)
+ if error
+ call add(s:update.errors, name)
+ call s:regress_bar()
+ silent execute pos 'd _'
+ call append(4, msg) | 4
+ elseif !empty(out)
+ call setline(pos, msg[0])
+ endif
+ redraw
+ endfor
+ silent 4 d _
+ try
+ call s:do(s:update.pull, s:update.force, filter(copy(s:update.all), 'index(s:update.errors, v:key) < 0 && has_key(v:val, "do")'))
+ catch
+ call s:warn('echom', v:exception)
+ call s:warn('echo', '')
+ return
+ endtry
+ call s:finish(s:update.pull)
+ call setline(1, 'Updated. Elapsed time: ' . split(reltimestr(reltime(s:update.start)))[0] . ' sec.')
+ call s:switch_out('normal! gg')
+ endif
+endfunction
+
+function! s:job_abort()
+ if (!s:nvim && !s:vim8) || !exists('s:jobs')
+ return
+ endif
+
+ for [name, j] in items(s:jobs)
+ if s:nvim
+ silent! call jobstop(j.jobid)
+ elseif s:vim8
+ silent! call job_stop(j.jobid)
+ endif
+ if j.new
+ call s:rm_rf(g:plugs[name].dir)
+ endif
+ endfor
+ let s:jobs = {}
+endfunction
+
+function! s:last_non_empty_line(lines)
+ let len = len(a:lines)
+ for idx in range(len)
+ let line = a:lines[len-idx-1]
+ if !empty(line)
+ return line
+ endif
+ endfor
+ return ''
+endfunction
+
+function! s:job_out_cb(self, data) abort
+ let self = a:self
+ let data = remove(self.lines, -1) . a:data
+ let lines = map(split(data, "\n", 1), 'split(v:val, "\r", 1)[-1]')
+ call extend(self.lines, lines)
+ " To reduce the number of buffer updates
+ let self.tick = get(self, 'tick', -1) + 1
+ if !self.running || self.tick % len(s:jobs) == 0
+ let bullet = self.running ? (self.new ? '+' : '*') : (self.error ? 'x' : '-')
+ let result = self.error ? join(self.lines, "\n") : s:last_non_empty_line(self.lines)
+ if len(result)
+ call s:log(bullet, self.name, result)
+ endif
+ endif
+endfunction
+
+function! s:job_exit_cb(self, data) abort
+ let a:self.running = 0
+ let a:self.error = a:data != 0
+ call s:reap(a:self.name)
+ call s:tick()
+endfunction
+
+function! s:job_cb(fn, job, ch, data)
+ if !s:plug_window_exists() " plug window closed
+ return s:job_abort()
+ endif
+ call call(a:fn, [a:job, a:data])
+endfunction
+
+function! s:nvim_cb(job_id, data, event) dict abort
+ return (a:event == 'stdout' || a:event == 'stderr') ?
+ \ s:job_cb('s:job_out_cb', self, 0, join(a:data, "\n")) :
+ \ s:job_cb('s:job_exit_cb', self, 0, a:data)
+endfunction
+
+function! s:spawn(name, spec, queue, opts)
+ let job = { 'name': a:name, 'spec': a:spec, 'running': 1, 'error': 0, 'lines': [''],
+ \ 'new': get(a:opts, 'new', 0), 'queue': copy(a:queue) }
+ let Item = remove(job.queue, 0)
+ let argv = type(Item) == s:TYPE.funcref ? call(Item, [a:spec]) : Item
+ let s:jobs[a:name] = job
+
+ if s:nvim
+ if has_key(a:opts, 'dir')
+ let job.cwd = a:opts.dir
+ endif
+ call extend(job, {
+ \ 'on_stdout': function('s:nvim_cb'),
+ \ 'on_stderr': function('s:nvim_cb'),
+ \ 'on_exit': function('s:nvim_cb'),
+ \ })
+ let jid = s:plug_call('jobstart', argv, job)
+ if jid > 0
+ let job.jobid = jid
+ else
+ let job.running = 0
+ let job.error = 1
+ let job.lines = [jid < 0 ? argv[0].' is not executable' :
+ \ 'Invalid arguments (or job table is full)']
+ endif
+ elseif s:vim8
+ let cmd = join(map(copy(argv), 'plug#shellescape(v:val, {"script": 0})'))
+ if has_key(a:opts, 'dir')
+ let cmd = s:with_cd(cmd, a:opts.dir, 0)
+ endif
+ let argv = s:is_win ? ['cmd', '/s', '/c', '"'.cmd.'"'] : ['sh', '-c', cmd]
+ let jid = job_start(s:is_win ? join(argv, ' ') : argv, {
+ \ 'out_cb': function('s:job_cb', ['s:job_out_cb', job]),
+ \ 'err_cb': function('s:job_cb', ['s:job_out_cb', job]),
+ \ 'exit_cb': function('s:job_cb', ['s:job_exit_cb', job]),
+ \ 'err_mode': 'raw',
+ \ 'out_mode': 'raw'
+ \})
+ if job_status(jid) == 'run'
+ let job.jobid = jid
+ else
+ let job.running = 0
+ let job.error = 1
+ let job.lines = ['Failed to start job']
+ endif
+ else
+ let job.lines = s:lines(call('s:system', has_key(a:opts, 'dir') ? [argv, a:opts.dir] : [argv]))
+ let job.error = v:shell_error != 0
+ let job.running = 0
+ endif
+endfunction
+
+function! s:reap(name)
+ let job = remove(s:jobs, a:name)
+ if job.error
+ call add(s:update.errors, a:name)
+ elseif get(job, 'new', 0)
+ let s:update.new[a:name] = 1
+ endif
+
+ let more = len(get(job, 'queue', []))
+ let bullet = job.error ? 'x' : more ? (job.new ? '+' : '*') : '-'
+ let result = job.error ? join(job.lines, "\n") : s:last_non_empty_line(job.lines)
+ if len(result)
+ call s:log(bullet, a:name, result)
+ endif
+
+ if !job.error && more
+ let job.spec.queue = job.queue
+ let s:update.todo[a:name] = job.spec
+ else
+ let s:update.bar .= job.error ? 'x' : '='
+ call s:bar()
+ endif
+endfunction
+
+function! s:bar()
+ if s:switch_in()
+ let total = len(s:update.all)
+ call setline(1, (s:update.pull ? 'Updating' : 'Installing').
+ \ ' plugins ('.len(s:update.bar).'/'.total.')')
+ call s:progress_bar(2, s:update.bar, total)
+ call s:switch_out()
+ endif
+endfunction
+
+function! s:logpos(name)
+ let max = line('$')
+ for i in range(4, max > 4 ? max : 4)
+ if getline(i) =~# '^[-+x*] '.a:name.':'
+ for j in range(i + 1, max > 5 ? max : 5)
+ if getline(j) !~ '^ '
+ return [i, j - 1]
+ endif
+ endfor
+ return [i, i]
+ endif
+ endfor
+ return [0, 0]
+endfunction
+
+function! s:log(bullet, name, lines)
+ if s:switch_in()
+ let [b, e] = s:logpos(a:name)
+ if b > 0
+ silent execute printf('%d,%d d _', b, e)
+ if b > winheight('.')
+ let b = 4
+ endif
+ else
+ let b = 4
+ endif
+ " FIXME For some reason, nomodifiable is set after :d in vim8
+ setlocal modifiable
+ call append(b - 1, s:format_message(a:bullet, a:name, a:lines))
+ call s:switch_out()
+ endif
+endfunction
+
+function! s:update_vim()
+ let s:jobs = {}
+
+ call s:bar()
+ call s:tick()
+endfunction
+
+function! s:checkout_command(spec)
+ let a:spec.branch = s:git_origin_branch(a:spec)
+ return ['git', 'checkout', '-q', a:spec.branch, '--']
+endfunction
+
+function! s:merge_command(spec)
+ let a:spec.branch = s:git_origin_branch(a:spec)
+ return ['git', 'merge', '--ff-only', 'origin/'.a:spec.branch]
+endfunction
+
+function! s:tick()
+ let pull = s:update.pull
+ let prog = s:progress_opt(s:nvim || s:vim8)
+while 1 " Without TCO, Vim stack is bound to explode
+ if empty(s:update.todo)
+ if empty(s:jobs) && !s:update.fin
+ call s:update_finish()
+ let s:update.fin = 1
+ endif
+ return
+ endif
+
+ let name = keys(s:update.todo)[0]
+ let spec = remove(s:update.todo, name)
+ let queue = get(spec, 'queue', [])
+ let new = empty(globpath(spec.dir, '.git', 1))
+
+ if empty(queue)
+ call s:log(new ? '+' : '*', name, pull ? 'Updating ...' : 'Installing ...')
+ redraw
+ endif
+
+ let has_tag = has_key(spec, 'tag')
+ if len(queue)
+ call s:spawn(name, spec, queue, { 'dir': spec.dir })
+ elseif !new
+ let [error, _] = s:git_validate(spec, 0)
+ if empty(error)
+ if pull
+ let cmd = s:git_version_requirement(2) ? ['git', '-c', 'credential.helper=', 'fetch'] : ['git', 'fetch']
+ if has_tag && !empty(globpath(spec.dir, '.git/shallow'))
+ call extend(cmd, ['--depth', '99999999'])
+ endif
+ if !empty(prog)
+ call add(cmd, prog)
+ endif
+ let queue = [cmd, split('git remote set-head origin -a')]
+ if !has_tag && !has_key(spec, 'commit')
+ call extend(queue, [function('s:checkout_command'), function('s:merge_command')])
+ endif
+ call s:spawn(name, spec, queue, { 'dir': spec.dir })
+ else
+ let s:jobs[name] = { 'running': 0, 'lines': ['Already installed'], 'error': 0 }
+ endif
+ else
+ let s:jobs[name] = { 'running': 0, 'lines': s:lines(error), 'error': 1 }
+ endif
+ else
+ let cmd = ['git', 'clone']
+ if !has_tag
+ call extend(cmd, s:clone_opt)
+ endif
+ if !empty(prog)
+ call add(cmd, prog)
+ endif
+ call s:spawn(name, spec, [extend(cmd, [spec.uri, s:trim(spec.dir)]), function('s:checkout_command'), function('s:merge_command')], { 'new': 1 })
+ endif
+
+ if !s:jobs[name].running
+ call s:reap(name)
+ endif
+ if len(s:jobs) >= s:update.threads
+ break
+ endif
+endwhile
+endfunction
+
+function! s:update_python()
+let py_exe = has('python') ? 'python' : 'python3'
+execute py_exe "<< EOF"
+import datetime
+import functools
+import os
+try:
+ import queue
+except ImportError:
+ import Queue as queue
+import random
+import re
+import shutil
+import signal
+import subprocess
+import tempfile
+import threading as thr
+import time
+import traceback
+import vim
+
+G_NVIM = vim.eval("has('nvim')") == '1'
+G_PULL = vim.eval('s:update.pull') == '1'
+G_RETRIES = int(vim.eval('get(g:, "plug_retries", 2)')) + 1
+G_TIMEOUT = int(vim.eval('get(g:, "plug_timeout", 60)'))
+G_CLONE_OPT = ' '.join(vim.eval('s:clone_opt'))
+G_PROGRESS = vim.eval('s:progress_opt(1)')
+G_LOG_PROB = 1.0 / int(vim.eval('s:update.threads'))
+G_STOP = thr.Event()
+G_IS_WIN = vim.eval('s:is_win') == '1'
+
+class PlugError(Exception):
+ def __init__(self, msg):
+ self.msg = msg
+class CmdTimedOut(PlugError):
+ pass
+class CmdFailed(PlugError):
+ pass
+class InvalidURI(PlugError):
+ pass
+class Action(object):
+ INSTALL, UPDATE, ERROR, DONE = ['+', '*', 'x', '-']
+
+class Buffer(object):
+ def __init__(self, lock, num_plugs, is_pull):
+ self.bar = ''
+ self.event = 'Updating' if is_pull else 'Installing'
+ self.lock = lock
+ self.maxy = int(vim.eval('winheight(".")'))
+ self.num_plugs = num_plugs
+
+ def __where(self, name):
+ """ Find first line with name in current buffer. Return line num. """
+ found, lnum = False, 0
+ matcher = re.compile('^[-+x*] {0}:'.format(name))
+ for line in vim.current.buffer:
+ if matcher.search(line) is not None:
+ found = True
+ break
+ lnum += 1
+
+ if not found:
+ lnum = -1
+ return lnum
+
+ def header(self):
+ curbuf = vim.current.buffer
+ curbuf[0] = self.event + ' plugins ({0}/{1})'.format(len(self.bar), self.num_plugs)
+
+ num_spaces = self.num_plugs - len(self.bar)
+ curbuf[1] = '[{0}{1}]'.format(self.bar, num_spaces * ' ')
+
+ with self.lock:
+ vim.command('normal! 2G')
+ vim.command('redraw')
+
+ def write(self, action, name, lines):
+ first, rest = lines[0], lines[1:]
+ msg = ['{0} {1}{2}{3}'.format(action, name, ': ' if first else '', first)]
+ msg.extend([' ' + line for line in rest])
+
+ try:
+ if action == Action.ERROR:
+ self.bar += 'x'
+ vim.command("call add(s:update.errors, '{0}')".format(name))
+ elif action == Action.DONE:
+ self.bar += '='
+
+ curbuf = vim.current.buffer
+ lnum = self.__where(name)
+ if lnum != -1: # Found matching line num
+ del curbuf[lnum]
+ if lnum > self.maxy and action in set([Action.INSTALL, Action.UPDATE]):
+ lnum = 3
+ else:
+ lnum = 3
+ curbuf.append(msg, lnum)
+
+ self.header()
+ except vim.error:
+ pass
+
+class Command(object):
+ CD = 'cd /d' if G_IS_WIN else 'cd'
+
+ def __init__(self, cmd, cmd_dir=None, timeout=60, cb=None, clean=None):
+ self.cmd = cmd
+ if cmd_dir:
+ self.cmd = '{0} {1} && {2}'.format(Command.CD, cmd_dir, self.cmd)
+ self.timeout = timeout
+ self.callback = cb if cb else (lambda msg: None)
+ self.clean = clean if clean else (lambda: None)
+ self.proc = None
+
+ @property
+ def alive(self):
+ """ Returns true only if command still running. """
+ return self.proc and self.proc.poll() is None
+
+ def execute(self, ntries=3):
+ """ Execute the command with ntries if CmdTimedOut.
+ Returns the output of the command if no Exception.
+ """
+ attempt, finished, limit = 0, False, self.timeout
+
+ while not finished:
+ try:
+ attempt += 1
+ result = self.try_command()
+ finished = True
+ return result
+ except CmdTimedOut:
+ if attempt != ntries:
+ self.notify_retry()
+ self.timeout += limit
+ else:
+ raise
+
+ def notify_retry(self):
+ """ Retry required for command, notify user. """
+ for count in range(3, 0, -1):
+ if G_STOP.is_set():
+ raise KeyboardInterrupt
+ msg = 'Timeout. Will retry in {0} second{1} ...'.format(
+ count, 's' if count != 1 else '')
+ self.callback([msg])
+ time.sleep(1)
+ self.callback(['Retrying ...'])
+
+ def try_command(self):
+ """ Execute a cmd & poll for callback. Returns list of output.
+ Raises CmdFailed -> return code for Popen isn't 0
+ Raises CmdTimedOut -> command exceeded timeout without new output
+ """
+ first_line = True
+
+ try:
+ tfile = tempfile.NamedTemporaryFile(mode='w+b')
+ preexec_fn = not G_IS_WIN and os.setsid or None
+ self.proc = subprocess.Popen(self.cmd, stdout=tfile,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.PIPE, shell=True,
+ preexec_fn=preexec_fn)
+ thrd = thr.Thread(target=(lambda proc: proc.wait()), args=(self.proc,))
+ thrd.start()
+
+ thread_not_started = True
+ while thread_not_started:
+ try:
+ thrd.join(0.1)
+ thread_not_started = False
+ except RuntimeError:
+ pass
+
+ while self.alive:
+ if G_STOP.is_set():
+ raise KeyboardInterrupt
+
+ if first_line or random.random() < G_LOG_PROB:
+ first_line = False
+ line = '' if G_IS_WIN else nonblock_read(tfile.name)
+ if line:
+ self.callback([line])
+
+ time_diff = time.time() - os.path.getmtime(tfile.name)
+ if time_diff > self.timeout:
+ raise CmdTimedOut(['Timeout!'])
+
+ thrd.join(0.5)
+
+ tfile.seek(0)
+ result = [line.decode('utf-8', 'replace').rstrip() for line in tfile]
+
+ if self.proc.returncode != 0:
+ raise CmdFailed([''] + result)
+
+ return result
+ except:
+ self.terminate()
+ raise
+
+ def terminate(self):
+ """ Terminate process and cleanup. """
+ if self.alive:
+ if G_IS_WIN:
+ os.kill(self.proc.pid, signal.SIGINT)
+ else:
+ os.killpg(self.proc.pid, signal.SIGTERM)
+ self.clean()
+
+class Plugin(object):
+ def __init__(self, name, args, buf_q, lock):
+ self.name = name
+ self.args = args
+ self.buf_q = buf_q
+ self.lock = lock
+ self.tag = args.get('tag', 0)
+
+ def manage(self):
+ try:
+ if os.path.exists(self.args['dir']):
+ self.update()
+ else:
+ self.install()
+ with self.lock:
+ thread_vim_command("let s:update.new['{0}'] = 1".format(self.name))
+ except PlugError as exc:
+ self.write(Action.ERROR, self.name, exc.msg)
+ except KeyboardInterrupt:
+ G_STOP.set()
+ self.write(Action.ERROR, self.name, ['Interrupted!'])
+ except:
+ # Any exception except those above print stack trace
+ msg = 'Trace:\n{0}'.format(traceback.format_exc().rstrip())
+ self.write(Action.ERROR, self.name, msg.split('\n'))
+ raise
+
+ def install(self):
+ target = self.args['dir']
+ if target[-1] == '\\':
+ target = target[0:-1]
+
+ def clean(target):
+ def _clean():
+ try:
+ shutil.rmtree(target)
+ except OSError:
+ pass
+ return _clean
+
+ self.write(Action.INSTALL, self.name, ['Installing ...'])
+ callback = functools.partial(self.write, Action.INSTALL, self.name)
+ cmd = 'git clone {0} {1} {2} {3} 2>&1'.format(
+ '' if self.tag else G_CLONE_OPT, G_PROGRESS, self.args['uri'],
+ esc(target))
+ com = Command(cmd, None, G_TIMEOUT, callback, clean(target))
+ result = com.execute(G_RETRIES)
+ self.write(Action.DONE, self.name, result[-1:])
+
+ def repo_uri(self):
+ cmd = 'git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url'
+ command = Command(cmd, self.args['dir'], G_TIMEOUT,)
+ result = command.execute(G_RETRIES)
+ return result[-1]
+
+ def update(self):
+ actual_uri = self.repo_uri()
+ expect_uri = self.args['uri']
+ regex = re.compile(r'^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$')
+ ma = regex.match(actual_uri)
+ mb = regex.match(expect_uri)
+ if ma is None or mb is None or ma.groups() != mb.groups():
+ msg = ['',
+ 'Invalid URI: {0}'.format(actual_uri),
+ 'Expected {0}'.format(expect_uri),
+ 'PlugClean required.']
+ raise InvalidURI(msg)
+
+ if G_PULL:
+ self.write(Action.UPDATE, self.name, ['Updating ...'])
+ callback = functools.partial(self.write, Action.UPDATE, self.name)
+ fetch_opt = '--depth 99999999' if self.tag and os.path.isfile(os.path.join(self.args['dir'], '.git/shallow')) else ''
+ cmd = 'git fetch {0} {1} 2>&1'.format(fetch_opt, G_PROGRESS)
+ com = Command(cmd, self.args['dir'], G_TIMEOUT, callback)
+ result = com.execute(G_RETRIES)
+ self.write(Action.DONE, self.name, result[-1:])
+ else:
+ self.write(Action.DONE, self.name, ['Already installed'])
+
+ def write(self, action, name, msg):
+ self.buf_q.put((action, name, msg))
+
+class PlugThread(thr.Thread):
+ def __init__(self, tname, args):
+ super(PlugThread, self).__init__()
+ self.tname = tname
+ self.args = args
+
+ def run(self):
+ thr.current_thread().name = self.tname
+ buf_q, work_q, lock = self.args
+
+ try:
+ while not G_STOP.is_set():
+ name, args = work_q.get_nowait()
+ plug = Plugin(name, args, buf_q, lock)
+ plug.manage()
+ work_q.task_done()
+ except queue.Empty:
+ pass
+
+class RefreshThread(thr.Thread):
+ def __init__(self, lock):
+ super(RefreshThread, self).__init__()
+ self.lock = lock
+ self.running = True
+
+ def run(self):
+ while self.running:
+ with self.lock:
+ thread_vim_command('noautocmd normal! a')
+ time.sleep(0.33)
+
+ def stop(self):
+ self.running = False
+
+if G_NVIM:
+ def thread_vim_command(cmd):
+ vim.session.threadsafe_call(lambda: vim.command(cmd))
+else:
+ def thread_vim_command(cmd):
+ vim.command(cmd)
+
+def esc(name):
+ return '"' + name.replace('"', '\"') + '"'
+
+def nonblock_read(fname):
+ """ Read a file with nonblock flag. Return the last line. """
+ fread = os.open(fname, os.O_RDONLY | os.O_NONBLOCK)
+ buf = os.read(fread, 100000).decode('utf-8', 'replace')
+ os.close(fread)
+
+ line = buf.rstrip('\r\n')
+ left = max(line.rfind('\r'), line.rfind('\n'))
+ if left != -1:
+ left += 1
+ line = line[left:]
+
+ return line
+
+def main():
+ thr.current_thread().name = 'main'
+ nthreads = int(vim.eval('s:update.threads'))
+ plugs = vim.eval('s:update.todo')
+ mac_gui = vim.eval('s:mac_gui') == '1'
+
+ lock = thr.Lock()
+ buf = Buffer(lock, len(plugs), G_PULL)
+ buf_q, work_q = queue.Queue(), queue.Queue()
+ for work in plugs.items():
+ work_q.put(work)
+
+ start_cnt = thr.active_count()
+ for num in range(nthreads):
+ tname = 'PlugT-{0:02}'.format(num)
+ thread = PlugThread(tname, (buf_q, work_q, lock))
+ thread.start()
+ if mac_gui:
+ rthread = RefreshThread(lock)
+ rthread.start()
+
+ while not buf_q.empty() or thr.active_count() != start_cnt:
+ try:
+ action, name, msg = buf_q.get(True, 0.25)
+ buf.write(action, name, ['OK'] if not msg else msg)
+ buf_q.task_done()
+ except queue.Empty:
+ pass
+ except KeyboardInterrupt:
+ G_STOP.set()
+
+ if mac_gui:
+ rthread.stop()
+ rthread.join()
+
+main()
+EOF
+endfunction
+
+function! s:update_ruby()
+ ruby << EOF
+ module PlugStream
+ SEP = ["\r", "\n", nil]
+ def get_line
+ buffer = ''
+ loop do
+ char = readchar rescue return
+ if SEP.include? char.chr
+ buffer << $/
+ break
+ else
+ buffer << char
+ end
+ end
+ buffer
+ end
+ end unless defined?(PlugStream)
+
+ def esc arg
+ %["#{arg.gsub('"', '\"')}"]
+ end
+
+ def killall pid
+ pids = [pid]
+ if /mswin|mingw|bccwin/ =~ RUBY_PLATFORM
+ pids.each { |pid| Process.kill 'INT', pid.to_i rescue nil }
+ else
+ unless `which pgrep 2> /dev/null`.empty?
+ children = pids
+ until children.empty?
+ children = children.map { |pid|
+ `pgrep -P #{pid}`.lines.map { |l| l.chomp }
+ }.flatten
+ pids += children
+ end
+ end
+ pids.each { |pid| Process.kill 'TERM', pid.to_i rescue nil }
+ end
+ end
+
+ def compare_git_uri a, b
+ regex = %r{^(?:\w+://)?(?:[^@/]*@)?([^:/]*(?::[0-9]*)?)[:/](.*?)(?:\.git)?/?$}
+ regex.match(a).to_a.drop(1) == regex.match(b).to_a.drop(1)
+ end
+
+ require 'thread'
+ require 'fileutils'
+ require 'timeout'
+ running = true
+ iswin = VIM::evaluate('s:is_win').to_i == 1
+ pull = VIM::evaluate('s:update.pull').to_i == 1
+ base = VIM::evaluate('g:plug_home')
+ all = VIM::evaluate('s:update.todo')
+ limit = VIM::evaluate('get(g:, "plug_timeout", 60)')
+ tries = VIM::evaluate('get(g:, "plug_retries", 2)') + 1
+ nthr = VIM::evaluate('s:update.threads').to_i
+ maxy = VIM::evaluate('winheight(".")').to_i
+ vim7 = VIM::evaluate('v:version').to_i <= 703 && RUBY_PLATFORM =~ /darwin/
+ cd = iswin ? 'cd /d' : 'cd'
+ tot = VIM::evaluate('len(s:update.todo)') || 0
+ bar = ''
+ skip = 'Already installed'
+ mtx = Mutex.new
+ take1 = proc { mtx.synchronize { running && all.shift } }
+ logh = proc {
+ cnt = bar.length
+ $curbuf[1] = "#{pull ? 'Updating' : 'Installing'} plugins (#{cnt}/#{tot})"
+ $curbuf[2] = '[' + bar.ljust(tot) + ']'
+ VIM::command('normal! 2G')
+ VIM::command('redraw')
+ }
+ where = proc { |name| (1..($curbuf.length)).find { |l| $curbuf[l] =~ /^[-+x*] #{name}:/ } }
+ log = proc { |name, result, type|
+ mtx.synchronize do
+ ing = ![true, false].include?(type)
+ bar += type ? '=' : 'x' unless ing
+ b = case type
+ when :install then '+' when :update then '*'
+ when true, nil then '-' else
+ VIM::command("call add(s:update.errors, '#{name}')")
+ 'x'
+ end
+ result =
+ if type || type.nil?
+ ["#{b} #{name}: #{result.lines.to_a.last || 'OK'}"]
+ elsif result =~ /^Interrupted|^Timeout/
+ ["#{b} #{name}: #{result}"]
+ else
+ ["#{b} #{name}"] + result.lines.map { |l| " " << l }
+ end
+ if lnum = where.call(name)
+ $curbuf.delete lnum
+ lnum = 4 if ing && lnum > maxy
+ end
+ result.each_with_index do |line, offset|
+ $curbuf.append((lnum || 4) - 1 + offset, line.gsub(/\e\[./, '').chomp)
+ end
+ logh.call
+ end
+ }
+ bt = proc { |cmd, name, type, cleanup|
+ tried = timeout = 0
+ begin
+ tried += 1
+ timeout += limit
+ fd = nil
+ data = ''
+ if iswin
+ Timeout::timeout(timeout) do
+ tmp = VIM::evaluate('tempname()')
+ system("(#{cmd}) > #{tmp}")
+ data = File.read(tmp).chomp
+ File.unlink tmp rescue nil
+ end
+ else
+ fd = IO.popen(cmd).extend(PlugStream)
+ first_line = true
+ log_prob = 1.0 / nthr
+ while line = Timeout::timeout(timeout) { fd.get_line }
+ data << line
+ log.call name, line.chomp, type if name && (first_line || rand < log_prob)
+ first_line = false
+ end
+ fd.close
+ end
+ [$? == 0, data.chomp]
+ rescue Timeout::Error, Interrupt => e
+ if fd && !fd.closed?
+ killall fd.pid
+ fd.close
+ end
+ cleanup.call if cleanup
+ if e.is_a?(Timeout::Error) && tried < tries
+ 3.downto(1) do |countdown|
+ s = countdown > 1 ? 's' : ''
+ log.call name, "Timeout. Will retry in #{countdown} second#{s} ...", type
+ sleep 1
+ end
+ log.call name, 'Retrying ...', type
+ retry
+ end
+ [false, e.is_a?(Interrupt) ? "Interrupted!" : "Timeout!"]
+ end
+ }
+ main = Thread.current
+ threads = []
+ watcher = Thread.new {
+ if vim7
+ while VIM::evaluate('getchar(1)')
+ sleep 0.1
+ end
+ else
+ require 'io/console' # >= Ruby 1.9
+ nil until IO.console.getch == 3.chr
+ end
+ mtx.synchronize do
+ running = false
+ threads.each { |t| t.raise Interrupt } unless vim7
+ end
+ threads.each { |t| t.join rescue nil }
+ main.kill
+ }
+ refresh = Thread.new {
+ while true
+ mtx.synchronize do
+ break unless running
+ VIM::command('noautocmd normal! a')
+ end
+ sleep 0.2
+ end
+ } if VIM::evaluate('s:mac_gui') == 1
+
+ clone_opt = VIM::evaluate('s:clone_opt').join(' ')
+ progress = VIM::evaluate('s:progress_opt(1)')
+ nthr.times do
+ mtx.synchronize do
+ threads << Thread.new {
+ while pair = take1.call
+ name = pair.first
+ dir, uri, tag = pair.last.values_at *%w[dir uri tag]
+ exists = File.directory? dir
+ ok, result =
+ if exists
+ chdir = "#{cd} #{iswin ? dir : esc(dir)}"
+ ret, data = bt.call "#{chdir} && git rev-parse --abbrev-ref HEAD 2>&1 && git config -f .git/config remote.origin.url", nil, nil, nil
+ current_uri = data.lines.to_a.last
+ if !ret
+ if data =~ /^Interrupted|^Timeout/
+ [false, data]
+ else
+ [false, [data.chomp, "PlugClean required."].join($/)]
+ end
+ elsif !compare_git_uri(current_uri, uri)
+ [false, ["Invalid URI: #{current_uri}",
+ "Expected: #{uri}",
+ "PlugClean required."].join($/)]
+ else
+ if pull
+ log.call name, 'Updating ...', :update
+ fetch_opt = (tag && File.exist?(File.join(dir, '.git/shallow'))) ? '--depth 99999999' : ''
+ bt.call "#{chdir} && git fetch #{fetch_opt} #{progress} 2>&1", name, :update, nil
+ else
+ [true, skip]
+ end
+ end
+ else
+ d = esc dir.sub(%r{[\\/]+$}, '')
+ log.call name, 'Installing ...', :install
+ bt.call "git clone #{clone_opt unless tag} #{progress} #{uri} #{d} 2>&1", name, :install, proc {
+ FileUtils.rm_rf dir
+ }
+ end
+ mtx.synchronize { VIM::command("let s:update.new['#{name}'] = 1") } if !exists && ok
+ log.call name, result, ok
+ end
+ } if running
+ end
+ end
+ threads.each { |t| t.join rescue nil }
+ logh.call
+ refresh.kill if refresh
+ watcher.kill
+EOF
+endfunction
+
+function! s:shellesc_cmd(arg, script)
+ let escaped = substitute('"'.a:arg.'"', '[&|<>()@^!"]', '^&', 'g')
+ return substitute(escaped, '%', (a:script ? '%' : '^') . '&', 'g')
+endfunction
+
+function! s:shellesc_ps1(arg)
+ return "'".substitute(escape(a:arg, '\"'), "'", "''", 'g')."'"
+endfunction
+
+function! s:shellesc_sh(arg)
+ return "'".substitute(a:arg, "'", "'\\\\''", 'g')."'"
+endfunction
+
+" Escape the shell argument based on the shell.
+" Vim and Neovim's shellescape() are insufficient.
+" 1. shellslash determines whether to use single/double quotes.
+" Double-quote escaping is fragile for cmd.exe.
+" 2. It does not work for powershell.
+" 3. It does not work for *sh shells if the command is executed
+" via cmd.exe (ie. cmd.exe /c sh -c command command_args)
+" 4. It does not support batchfile syntax.
+"
+" Accepts an optional dictionary with the following keys:
+" - shell: same as Vim/Neovim 'shell' option.
+" If unset, fallback to 'cmd.exe' on Windows or 'sh'.
+" - script: If truthy and shell is cmd.exe, escape for batchfile syntax.
+function! plug#shellescape(arg, ...)
+ if a:arg =~# '^[A-Za-z0-9_/:.-]\+$'
+ return a:arg
+ endif
+ let opts = a:0 > 0 && type(a:1) == s:TYPE.dict ? a:1 : {}
+ let shell = get(opts, 'shell', s:is_win ? 'cmd.exe' : 'sh')
+ let script = get(opts, 'script', 1)
+ if shell =~# 'cmd\(\.exe\)\?$'
+ return s:shellesc_cmd(a:arg, script)
+ elseif s:is_powershell(shell)
+ return s:shellesc_ps1(a:arg)
+ endif
+ return s:shellesc_sh(a:arg)
+endfunction
+
+function! s:glob_dir(path)
+ return map(filter(s:glob(a:path, '**'), 'isdirectory(v:val)'), 's:dirpath(v:val)')
+endfunction
+
+function! s:progress_bar(line, bar, total)
+ call setline(a:line, '[' . s:lpad(a:bar, a:total) . ']')
+endfunction
+
+function! s:compare_git_uri(a, b)
+ " See `git help clone'
+ " https:// [user@] github.com[:port] / junegunn/vim-plug [.git]
+ " [git@] github.com[:port] : junegunn/vim-plug [.git]
+ " file:// / junegunn/vim-plug [/]
+ " / junegunn/vim-plug [/]
+ let pat = '^\%(\w\+://\)\='.'\%([^@/]*@\)\='.'\([^:/]*\%(:[0-9]*\)\=\)'.'[:/]'.'\(.\{-}\)'.'\%(\.git\)\=/\?$'
+ let ma = matchlist(a:a, pat)
+ let mb = matchlist(a:b, pat)
+ return ma[1:2] ==# mb[1:2]
+endfunction
+
+function! s:format_message(bullet, name, message)
+ if a:bullet != 'x'
+ return [printf('%s %s: %s', a:bullet, a:name, s:lastline(a:message))]
+ else
+ let lines = map(s:lines(a:message), '" ".v:val')
+ return extend([printf('x %s:', a:name)], lines)
+ endif
+endfunction
+
+function! s:with_cd(cmd, dir, ...)
+ let script = a:0 > 0 ? a:1 : 1
+ return printf('cd%s %s && %s', s:is_win ? ' /d' : '', plug#shellescape(a:dir, {'script': script}), a:cmd)
+endfunction
+
+function! s:system(cmd, ...)
+ let batchfile = ''
+ try
+ let [sh, shellcmdflag, shrd] = s:chsh(1)
+ if type(a:cmd) == s:TYPE.list
+ " Neovim's system() supports list argument to bypass the shell
+ " but it cannot set the working directory for the command.
+ " Assume that the command does not rely on the shell.
+ if has('nvim') && a:0 == 0
+ return system(a:cmd)
+ endif
+ let cmd = join(map(copy(a:cmd), 'plug#shellescape(v:val, {"shell": &shell, "script": 0})'))
+ if s:is_powershell(&shell)
+ let cmd = '& ' . cmd
+ endif
+ else
+ let cmd = a:cmd
+ endif
+ if a:0 > 0
+ let cmd = s:with_cd(cmd, a:1, type(a:cmd) != s:TYPE.list)
+ endif
+ if s:is_win && type(a:cmd) != s:TYPE.list
+ let [batchfile, cmd] = s:batchfile(cmd)
+ endif
+ return system(cmd)
+ finally
+ let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
+ if s:is_win && filereadable(batchfile)
+ call delete(batchfile)
+ endif
+ endtry
+endfunction
+
+function! s:system_chomp(...)
+ let ret = call('s:system', a:000)
+ return v:shell_error ? '' : substitute(ret, '\n$', '', '')
+endfunction
+
+function! s:git_validate(spec, check_branch)
+ let err = ''
+ if isdirectory(a:spec.dir)
+ let result = [s:git_local_branch(a:spec.dir), s:git_origin_url(a:spec.dir)]
+ let remote = result[-1]
+ if empty(remote)
+ let err = join([remote, 'PlugClean required.'], "\n")
+ elseif !s:compare_git_uri(remote, a:spec.uri)
+ let err = join(['Invalid URI: '.remote,
+ \ 'Expected: '.a:spec.uri,
+ \ 'PlugClean required.'], "\n")
+ elseif a:check_branch && has_key(a:spec, 'commit')
+ let sha = s:git_revision(a:spec.dir)
+ if empty(sha)
+ let err = join(add(result, 'PlugClean required.'), "\n")
+ elseif !s:hash_match(sha, a:spec.commit)
+ let err = join([printf('Invalid HEAD (expected: %s, actual: %s)',
+ \ a:spec.commit[:6], sha[:6]),
+ \ 'PlugUpdate required.'], "\n")
+ endif
+ elseif a:check_branch
+ let current_branch = result[0]
+ " Check tag
+ let origin_branch = s:git_origin_branch(a:spec)
+ if has_key(a:spec, 'tag')
+ let tag = s:system_chomp('git describe --exact-match --tags HEAD 2>&1', a:spec.dir)
+ if a:spec.tag !=# tag && a:spec.tag !~ '\*'
+ let err = printf('Invalid tag: %s (expected: %s). Try PlugUpdate.',
+ \ (empty(tag) ? 'N/A' : tag), a:spec.tag)
+ endif
+ " Check branch
+ elseif origin_branch !=# current_branch
+ let err = printf('Invalid branch: %s (expected: %s). Try PlugUpdate.',
+ \ current_branch, origin_branch)
+ endif
+ if empty(err)
+ let ahead_behind = split(s:lastline(s:system([
+ \ 'git', 'rev-list', '--count', '--left-right',
+ \ printf('HEAD...origin/%s', origin_branch)
+ \ ], a:spec.dir)), '\t')
+ if v:shell_error || len(ahead_behind) != 2
+ let err = "Failed to compare with the origin. The default branch might have changed.\nPlugClean required."
+ else
+ let [ahead, behind] = ahead_behind
+ if ahead && behind
+ " Only mention PlugClean if diverged, otherwise it's likely to be
+ " pushable (and probably not that messed up).
+ let err = printf(
+ \ "Diverged from origin/%s (%d commit(s) ahead and %d commit(s) behind!\n"
+ \ .'Backup local changes and run PlugClean and PlugUpdate to reinstall it.', origin_branch, ahead, behind)
+ elseif ahead
+ let err = printf("Ahead of origin/%s by %d commit(s).\n"
+ \ .'Cannot update until local changes are pushed.',
+ \ origin_branch, ahead)
+ endif
+ endif
+ endif
+ endif
+ else
+ let err = 'Not found'
+ endif
+ return [err, err =~# 'PlugClean']
+endfunction
+
+function! s:rm_rf(dir)
+ if isdirectory(a:dir)
+ return s:system(s:is_win
+ \ ? 'rmdir /S /Q '.plug#shellescape(a:dir)
+ \ : ['rm', '-rf', a:dir])
+ endif
+endfunction
+
+function! s:clean(force)
+ call s:prepare()
+ call append(0, 'Searching for invalid plugins in '.g:plug_home)
+ call append(1, '')
+
+ " List of valid directories
+ let dirs = []
+ let errs = {}
+ let [cnt, total] = [0, len(g:plugs)]
+ for [name, spec] in items(g:plugs)
+ if !s:is_managed(name) || get(spec, 'frozen', 0)
+ call add(dirs, spec.dir)
+ else
+ let [err, clean] = s:git_validate(spec, 1)
+ if clean
+ let errs[spec.dir] = s:lines(err)[0]
+ else
+ call add(dirs, spec.dir)
+ endif
+ endif
+ let cnt += 1
+ call s:progress_bar(2, repeat('=', cnt), total)
+ normal! 2G
+ redraw
+ endfor
+
+ let allowed = {}
+ for dir in dirs
+ let allowed[s:dirpath(s:plug_fnamemodify(dir, ':h:h'))] = 1
+ let allowed[dir] = 1
+ for child in s:glob_dir(dir)
+ let allowed[child] = 1
+ endfor
+ endfor
+
+ let todo = []
+ let found = sort(s:glob_dir(g:plug_home))
+ while !empty(found)
+ let f = remove(found, 0)
+ if !has_key(allowed, f) && isdirectory(f)
+ call add(todo, f)
+ call append(line('$'), '- ' . f)
+ if has_key(errs, f)
+ call append(line('$'), ' ' . errs[f])
+ endif
+ let found = filter(found, 'stridx(v:val, f) != 0')
+ end
+ endwhile
+
+ 4
+ redraw
+ if empty(todo)
+ call append(line('$'), 'Already clean.')
+ else
+ let s:clean_count = 0
+ call append(3, ['Directories to delete:', ''])
+ redraw!
+ if a:force || s:ask_no_interrupt('Delete all directories?')
+ call s:delete([6, line('$')], 1)
+ else
+ call setline(4, 'Cancelled.')
+ nnoremap <silent> <buffer> d :set opfunc=<sid>delete_op<cr>g@
+ nmap <silent> <buffer> dd d_
+ xnoremap <silent> <buffer> d :<c-u>call <sid>delete_op(visualmode(), 1)<cr>
+ echo 'Delete the lines (d{motion}) to delete the corresponding directories'
+ endif
+ endif
+ 4
+ setlocal nomodifiable
+endfunction
+
+function! s:delete_op(type, ...)
+ call s:delete(a:0 ? [line("'<"), line("'>")] : [line("'["), line("']")], 0)
+endfunction
+
+function! s:delete(range, force)
+ let [l1, l2] = a:range
+ let force = a:force
+ let err_count = 0
+ while l1 <= l2
+ let line = getline(l1)
+ if line =~ '^- ' && isdirectory(line[2:])
+ execute l1
+ redraw!
+ let answer = force ? 1 : s:ask('Delete '.line[2:].'?', 1)
+ let force = force || answer > 1
+ if answer
+ let err = s:rm_rf(line[2:])
+ setlocal modifiable
+ if empty(err)
+ call setline(l1, '~'.line[1:])
+ let s:clean_count += 1
+ else
+ delete _
+ call append(l1 - 1, s:format_message('x', line[1:], err))
+ let l2 += len(s:lines(err))
+ let err_count += 1
+ endif
+ let msg = printf('Removed %d directories.', s:clean_count)
+ if err_count > 0
+ let msg .= printf(' Failed to remove %d directories.', err_count)
+ endif
+ call setline(4, msg)
+ setlocal nomodifiable
+ endif
+ endif
+ let l1 += 1
+ endwhile
+endfunction
+
+function! s:upgrade()
+ echo 'Downloading the latest version of vim-plug'
+ redraw
+ let tmp = s:plug_tempname()
+ let new = tmp . '/plug.vim'
+
+ try
+ let out = s:system(['git', 'clone', '--depth', '1', s:plug_src, tmp])
+ if v:shell_error
+ return s:err('Error upgrading vim-plug: '. out)
+ endif
+
+ if readfile(s:me) ==# readfile(new)
+ echo 'vim-plug is already up-to-date'
+ return 0
+ else
+ call rename(s:me, s:me . '.old')
+ call rename(new, s:me)
+ unlet g:loaded_plug
+ echo 'vim-plug has been upgraded'
+ return 1
+ endif
+ finally
+ silent! call s:rm_rf(tmp)
+ endtry
+endfunction
+
+function! s:upgrade_specs()
+ for spec in values(g:plugs)
+ let spec.frozen = get(spec, 'frozen', 0)
+ endfor
+endfunction
+
+function! s:status()
+ call s:prepare()
+ call append(0, 'Checking plugins')
+ call append(1, '')
+
+ let ecnt = 0
+ let unloaded = 0
+ let [cnt, total] = [0, len(g:plugs)]
+ for [name, spec] in items(g:plugs)
+ let is_dir = isdirectory(spec.dir)
+ if has_key(spec, 'uri')
+ if is_dir
+ let [err, _] = s:git_validate(spec, 1)
+ let [valid, msg] = [empty(err), empty(err) ? 'OK' : err]
+ else
+ let [valid, msg] = [0, 'Not found. Try PlugInstall.']
+ endif
+ else
+ if is_dir
+ let [valid, msg] = [1, 'OK']
+ else
+ let [valid, msg] = [0, 'Not found.']
+ endif
+ endif
+ let cnt += 1
+ let ecnt += !valid
+ " `s:loaded` entry can be missing if PlugUpgraded
+ if is_dir && get(s:loaded, name, -1) == 0
+ let unloaded = 1
+ let msg .= ' (not loaded)'
+ endif
+ call s:progress_bar(2, repeat('=', cnt), total)
+ call append(3, s:format_message(valid ? '-' : 'x', name, msg))
+ normal! 2G
+ redraw
+ endfor
+ call setline(1, 'Finished. '.ecnt.' error(s).')
+ normal! gg
+ setlocal nomodifiable
+ if unloaded
+ echo "Press 'L' on each line to load plugin, or 'U' to update"
+ nnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
+ xnoremap <silent> <buffer> L :call <SID>status_load(line('.'))<cr>
+ end
+endfunction
+
+function! s:extract_name(str, prefix, suffix)
+ return matchstr(a:str, '^'.a:prefix.' \zs[^:]\+\ze:.*'.a:suffix.'$')
+endfunction
+
+function! s:status_load(lnum)
+ let line = getline(a:lnum)
+ let name = s:extract_name(line, '-', '(not loaded)')
+ if !empty(name)
+ call plug#load(name)
+ setlocal modifiable
+ call setline(a:lnum, substitute(line, ' (not loaded)$', '', ''))
+ setlocal nomodifiable
+ endif
+endfunction
+
+function! s:status_update() range
+ let lines = getline(a:firstline, a:lastline)
+ let names = filter(map(lines, 's:extract_name(v:val, "[x-]", "")'), '!empty(v:val)')
+ if !empty(names)
+ echo
+ execute 'PlugUpdate' join(names)
+ endif
+endfunction
+
+function! s:is_preview_window_open()
+ silent! wincmd P
+ if &previewwindow
+ wincmd p
+ return 1
+ endif
+endfunction
+
+function! s:find_name(lnum)
+ for lnum in reverse(range(1, a:lnum))
+ let line = getline(lnum)
+ if empty(line)
+ return ''
+ endif
+ let name = s:extract_name(line, '-', '')
+ if !empty(name)
+ return name
+ endif
+ endfor
+ return ''
+endfunction
+
+function! s:preview_commit()
+ if b:plug_preview < 0
+ let b:plug_preview = !s:is_preview_window_open()
+ endif
+
+ let sha = matchstr(getline('.'), '^ \X*\zs[0-9a-f]\{7,9}')
+ if empty(sha)
+ let name = matchstr(getline('.'), '^- \zs[^:]*\ze:$')
+ if empty(name)
+ return
+ endif
+ let title = 'HEAD@{1}..'
+ let command = 'git diff --no-color HEAD@{1}'
+ else
+ let title = sha
+ let command = 'git show --no-color --pretty=medium '.sha
+ let name = s:find_name(line('.'))
+ endif
+
+ if empty(name) || !has_key(g:plugs, name) || !isdirectory(g:plugs[name].dir)
+ return
+ endif
+
+ if !s:is_preview_window_open()
+ execute get(g:, 'plug_pwindow', 'vertical rightbelow new')
+ execute 'e' title
+ else
+ execute 'pedit' title
+ wincmd P
+ endif
+ setlocal previewwindow filetype=git buftype=nofile bufhidden=wipe nobuflisted modifiable
+ let batchfile = ''
+ try
+ let [sh, shellcmdflag, shrd] = s:chsh(1)
+ let cmd = 'cd '.plug#shellescape(g:plugs[name].dir).' && '.command
+ if s:is_win
+ let [batchfile, cmd] = s:batchfile(cmd)
+ endif
+ execute 'silent %!' cmd
+ finally
+ let [&shell, &shellcmdflag, &shellredir] = [sh, shellcmdflag, shrd]
+ if s:is_win && filereadable(batchfile)
+ call delete(batchfile)
+ endif
+ endtry
+ setlocal nomodifiable
+ nnoremap <silent> <buffer> q :q<cr>
+ wincmd p
+endfunction
+
+function! s:section(flags)
+ call search('\(^[x-] \)\@<=[^:]\+:', a:flags)
+endfunction
+
+function! s:format_git_log(line)
+ let indent = ' '
+ let tokens = split(a:line, nr2char(1))
+ if len(tokens) != 5
+ return indent.substitute(a:line, '\s*$', '', '')
+ endif
+ let [graph, sha, refs, subject, date] = tokens
+ let tag = matchstr(refs, 'tag: [^,)]\+')
+ let tag = empty(tag) ? ' ' : ' ('.tag.') '
+ return printf('%s%s%s%s%s (%s)', indent, graph, sha, tag, subject, date)
+endfunction
+
+function! s:append_ul(lnum, text)
+ call append(a:lnum, ['', a:text, repeat('-', len(a:text))])
+endfunction
+
+function! s:diff()
+ call s:prepare()
+ call append(0, ['Collecting changes ...', ''])
+ let cnts = [0, 0]
+ let bar = ''
+ let total = filter(copy(g:plugs), 's:is_managed(v:key) && isdirectory(v:val.dir)')
+ call s:progress_bar(2, bar, len(total))
+ for origin in [1, 0]
+ let plugs = reverse(sort(items(filter(copy(total), (origin ? '' : '!').'(has_key(v:val, "commit") || has_key(v:val, "tag"))'))))
+ if empty(plugs)
+ continue
+ endif
+ call s:append_ul(2, origin ? 'Pending updates:' : 'Last update:')
+ for [k, v] in plugs
+ let branch = s:git_origin_branch(v)
+ if len(branch)
+ let range = origin ? '..origin/'.branch : 'HEAD@{1}..'
+ let cmd = ['git', 'log', '--graph', '--color=never']
+ if s:git_version_requirement(2, 10, 0)
+ call add(cmd, '--no-show-signature')
+ endif
+ call extend(cmd, ['--pretty=format:%x01%h%x01%d%x01%s%x01%cr', range])
+ if has_key(v, 'rtp')
+ call extend(cmd, ['--', v.rtp])
+ endif
+ let diff = s:system_chomp(cmd, v.dir)
+ if !empty(diff)
+ let ref = has_key(v, 'tag') ? (' (tag: '.v.tag.')') : has_key(v, 'commit') ? (' '.v.commit) : ''
+ call append(5, extend(['', '- '.k.':'.ref], map(s:lines(diff), 's:format_git_log(v:val)')))
+ let cnts[origin] += 1
+ endif
+ endif
+ let bar .= '='
+ call s:progress_bar(2, bar, len(total))
+ normal! 2G
+ redraw
+ endfor
+ if !cnts[origin]
+ call append(5, ['', 'N/A'])
+ endif
+ endfor
+ call setline(1, printf('%d plugin(s) updated.', cnts[0])
+ \ . (cnts[1] ? printf(' %d plugin(s) have pending updates.', cnts[1]) : ''))
+
+ if cnts[0] || cnts[1]
+ nnoremap <silent> <buffer> <plug>(plug-preview) :silent! call <SID>preview_commit()<cr>
+ if empty(maparg("\<cr>", 'n'))
+ nmap <buffer> <cr> <plug>(plug-preview)
+ endif
+ if empty(maparg('o', 'n'))
+ nmap <buffer> o <plug>(plug-preview)
+ endif
+ endif
+ if cnts[0]
+ nnoremap <silent> <buffer> X :call <SID>revert()<cr>
+ echo "Press 'X' on each block to revert the update"
+ endif
+ normal! gg
+ setlocal nomodifiable
+endfunction
+
+function! s:revert()
+ if search('^Pending updates', 'bnW')
+ return
+ endif
+
+ let name = s:find_name(line('.'))
+ if empty(name) || !has_key(g:plugs, name) ||
+ \ input(printf('Revert the update of %s? (y/N) ', name)) !~? '^y'
+ return
+ endif
+
+ call s:system('git reset --hard HEAD@{1} && git checkout '.plug#shellescape(g:plugs[name].branch).' --', g:plugs[name].dir)
+ setlocal modifiable
+ normal! "_dap
+ setlocal nomodifiable
+ echo 'Reverted'
+endfunction
+
+function! s:snapshot(force, ...) abort
+ call s:prepare()
+ setf vim
+ call append(0, ['" Generated by vim-plug',
+ \ '" '.strftime("%c"),
+ \ '" :source this file in vim to restore the snapshot',
+ \ '" or execute: vim -S snapshot.vim',
+ \ '', '', 'PlugUpdate!'])
+ 1
+ let anchor = line('$') - 3
+ let names = sort(keys(filter(copy(g:plugs),
+ \'has_key(v:val, "uri") && isdirectory(v:val.dir)')))
+ for name in reverse(names)
+ let sha = has_key(g:plugs[name], 'commit') ? g:plugs[name].commit : s:git_revision(g:plugs[name].dir)
+ if !empty(sha)
+ call append(anchor, printf("silent! let g:plugs['%s'].commit = '%s'", name, sha))
+ redraw
+ endif
+ endfor
+
+ if a:0 > 0
+ let fn = s:plug_expand(a:1)
+ if filereadable(fn) && !(a:force || s:ask(a:1.' already exists. Overwrite?'))
+ return
+ endif
+ call writefile(getline(1, '$'), fn)
+ echo 'Saved as '.a:1
+ silent execute 'e' s:esc(fn)
+ setf vim
+ endif
+endfunction
+
+function! s:split_rtp()
+ return split(&rtp, '\\\@<!,')
+endfunction
+
+let s:first_rtp = s:escrtp(get(s:split_rtp(), 0, ''))
+let s:last_rtp = s:escrtp(get(s:split_rtp(), -1, ''))
+
+if exists('g:plugs')
+ let g:plugs_order = get(g:, 'plugs_order', keys(g:plugs))
+ call s:upgrade_specs()
+ call s:define_commands()
+endif
+
+let &cpo = s:cpo_save
+unlet s:cpo_save
diff --git a/vim/bundle/supertab b/vim/bundle/supertab
deleted file mode 160000
index f0093ae..0000000
--- a/vim/bundle/supertab
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit f0093ae12a9115498f887199809a6114659fc858
diff --git a/vim/bundles.vim b/vim/bundles.vim
deleted file mode 100644
index 285bde8..0000000
--- a/vim/bundles.vim
+++ /dev/null
@@ -1,26 +0,0 @@
-filetype off
-set rtp+=~/.vim/bundle/Vundle.vim
-call vundle#begin()
-
-Plugin 'gmarik/Vundle.vim'
-
-" Vim improvements
-Plugin 'Lokaltog/powerline'
-Plugin 'ervandew/supertab'
-Plugin 'altercation/vim-colors-solarized'
-
-" tpope
-Plugin 'tpope/vim-endwise'
-Plugin 'tpope/vim-rails'
-Plugin 'tpope/vim-surround'
-Plugin 'tpope/vim-fugitive'
-
-" Languages / Syntax
-Plugin 'sheerun/vim-polyglot'
-
-" Go
-Plugin 'fatih/vim-go'
-Plugin 'Shougo/deoplete.nvim'
-Plugin 'roxma/nvim-yarp'
-
-call vundle#end()
diff --git a/vim/ftplugin/ruby.vim b/vim/ftplugin/ruby.vim
index 783f52b..0334146 100644
--- a/vim/ftplugin/ruby.vim
+++ b/vim/ftplugin/ruby.vim
@@ -1,30 +1,27 @@
"""""""""""""""""""""""""""""
" Custom Ruby configuration "
"""""""""""""""""""""""""""""
" Run syntax check on the current file
noremap <F4> :w<CR>:!ruby -c '%'<CR>
" Easy commenting / uncommenting
noremap z :s/^/#<CR><Down>
noremap Z :s/^\s*\(#\)//<CR><Down>
" ERB helpers
iabbr _rv <%= %><Esc>2<Left>i
iabbr _rc <% %><Esc>2<Left>i
" Test::Unit macros
iabbr _ae assert_equal
iabbr _ane assert_not_equal
iabbr _aid assert_in_delta expect, actual, delta, ""
iabbr _ai assert_instance_of
iabbr _ak assert_kind_of
iabbr _am assert_match
iabbr _an assert_nil
iabbr _ann assert_not_nil
iabbr _as assert_same
iabbr _ans assert_not_same
iabbr _art assert_redirected_to
-
-" Bind <leader>d to go-to-definition.
-nmap <leader>d <Plug>(ale_go_to_definition)
diff --git a/vim/plugged/coc.nvim b/vim/plugged/coc.nvim
new file mode 160000
index 0000000..196d8f0
--- /dev/null
+++ b/vim/plugged/coc.nvim
@@ -0,0 +1 @@
+Subproject commit 196d8f0314bc6199f8243f00411ca7d87adc3c30
diff --git a/vim/plugged/deoplete.nvim b/vim/plugged/deoplete.nvim
new file mode 160000
index 0000000..43d7457
--- /dev/null
+++ b/vim/plugged/deoplete.nvim
@@ -0,0 +1 @@
+Subproject commit 43d7457059d65335ee0ceaa5505befbdd78ad705
diff --git a/vim/plugged/nvim-yarp b/vim/plugged/nvim-yarp
new file mode 160000
index 0000000..bb5f5e0
--- /dev/null
+++ b/vim/plugged/nvim-yarp
@@ -0,0 +1 @@
+Subproject commit bb5f5e038bfe119d3b777845a76b0b919b35ebc8
diff --git a/vim/plugged/powerline b/vim/plugged/powerline
new file mode 160000
index 0000000..a34abe3
--- /dev/null
+++ b/vim/plugged/powerline
@@ -0,0 +1 @@
+Subproject commit a34abe325a9ca94e020dc2f717731d92466d6037
diff --git a/vim/bundle/vim-colors-solarized b/vim/plugged/vim-colors-solarized
similarity index 100%
rename from vim/bundle/vim-colors-solarized
rename to vim/plugged/vim-colors-solarized
diff --git a/vim/plugged/vim-endwise b/vim/plugged/vim-endwise
new file mode 160000
index 0000000..3719ffd
--- /dev/null
+++ b/vim/plugged/vim-endwise
@@ -0,0 +1 @@
+Subproject commit 3719ffddb5e42bf67b55b2183d7a6fb8d3e5a2b8
diff --git a/vim/plugged/vim-fugitive b/vim/plugged/vim-fugitive
new file mode 160000
index 0000000..c0b03f1
--- /dev/null
+++ b/vim/plugged/vim-fugitive
@@ -0,0 +1 @@
+Subproject commit c0b03f1cac242d96837326d300f42a660306fc1a
diff --git a/vim/plugged/vim-go b/vim/plugged/vim-go
new file mode 160000
index 0000000..14eedf6
--- /dev/null
+++ b/vim/plugged/vim-go
@@ -0,0 +1 @@
+Subproject commit 14eedf6135cf4253b0ed48a0b53d6834a40da1c4
diff --git a/vim/plugged/vim-polyglot b/vim/plugged/vim-polyglot
new file mode 160000
index 0000000..bc8a81d
--- /dev/null
+++ b/vim/plugged/vim-polyglot
@@ -0,0 +1 @@
+Subproject commit bc8a81d3592dab86334f27d1d43c080ebf680d42
diff --git a/vim/plugged/vim-rails b/vim/plugged/vim-rails
new file mode 160000
index 0000000..3a15546
--- /dev/null
+++ b/vim/plugged/vim-rails
@@ -0,0 +1 @@
+Subproject commit 3a155462d1c346e291595400ca238037d02a357f
diff --git a/vim/plugged/vim-surround b/vim/plugged/vim-surround
new file mode 160000
index 0000000..3d188ed
--- /dev/null
+++ b/vim/plugged/vim-surround
@@ -0,0 +1 @@
+Subproject commit 3d188ed2113431cf8dac77be61b842acb64433d9
diff --git a/vimrc b/vimrc
index 0d80091..8448503 100644
--- a/vimrc
+++ b/vimrc
@@ -1,139 +1,206 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
-set rtp+=~/.vim/bundle/Vundle.vim
-source ~/.vim/bundles.vim
+call plug#begin()
+
+" Vim improvements
+Plug 'Lokaltog/powerline'
+Plug 'altercation/vim-colors-solarized'
+
+" tpope
+Plug 'tpope/vim-endwise'
+Plug 'tpope/vim-rails'
+Plug 'tpope/vim-surround'
+Plug 'tpope/vim-fugitive'
+
+" Languages / Syntax
+Plug 'sheerun/vim-polyglot'
+Plug 'neoclide/coc.nvim', {'branch': 'release'}
+
+" Go
+Plug 'fatih/vim-go'
+Plug 'Shougo/deoplete.nvim'
+Plug 'roxma/nvim-yarp'
+
+call plug#end()
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
-" Command for running `par` to format blocks of text
-map <leader>f {!}par w80qrg<cr>
-
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
+
+""""""""""""""""""""""""""
+""" CoC Config """""""""""
+""""""""""""""""""""""""""
+
+" https://github.com/neoclide/coc.nvim?tab=readme-ov-file
+
+function! CheckBackspace() abort
+ let col = col('.') - 1
+ return !col || getline('.')[col - 1] =~# '\s'
+endfunction
+
+" Use <c-space> to trigger completion
+if has('nvim')
+ inoremap <silent><expr> <c-space> coc#refresh()
+else
+ inoremap <silent><expr> <c-@> coc#refresh()
+endif
+
+" Use tab for trigger completion with characters ahead and navigate
+" NOTE: There's always complete item selected by default, you may want to enable
+" no select by `"suggest.noselect": true` in your configuration file
+" NOTE: Use command ':verbose imap <tab>' to make sure tab is not mapped by
+" other plugin before putting this into your config
+inoremap <silent><expr> <TAB>
+ \ coc#pum#visible() ? coc#pum#next(1) :
+ \ CheckBackspace() ? "\<Tab>" :
+ \ coc#refresh()
+inoremap <expr><S-TAB> coc#pum#visible() ? coc#pum#prev(1) : "\<C-h>"
+
+" Make <CR> to accept selected completion item or notify coc.nvim to format
+" <C-g>u breaks current undo, please make your own choice
+inoremap <silent><expr> <CR> coc#pum#visible() ? coc#pum#confirm()
+ \: "\<C-g>u\<CR>\<c-r>=coc#on_enter()\<CR>"
+
+nmap <silent> gd <Plug>(coc-definition)
+nmap <silent> gy <Plug>(coc-type-definition)
+nmap <silent> gi <Plug>(coc-implementation)
+nmap <silent> gr <Plug>(coc-references)
+
+" Formatting selected code
+xmap <leader>f <Plug>(coc-format-selected)
+nmap <leader>f <Plug>(coc-format-selected)
+
+" Remap keys for applying code actions at the cursor position
+nmap <leader>ac <Plug>(coc-codeaction-cursor)
+" Remap keys for apply code actions affect whole buffer
+nmap <leader>as <Plug>(coc-codeaction-source)
+" Apply the most preferred quickfix action to fix diagnostic on the current line
+nmap <leader>qf <Plug>(coc-fix-current)
|
jasonroelofs/dev
|
795159eee8034400d309299e3186050368cfa216
|
Clean up the cruft and pare back plugins / config
|
diff --git a/Rakefile b/Rakefile
index 6851bb9..efe8f45 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,34 +1,26 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
%w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc pryrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
end
puts "Setting up Python for MacVim + deoplete. Python3 required"
sh "python3 -m pip install pynvim"
puts "Install Vundle for vim plugin management"
sh "git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim"
- [
- # Enable Bundles in Mail
- "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
- "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
- ].each do |option|
- sh option
- end
-
puts "", "Ready! Jump into vim and run :BundleInstall to get all plugins", ""
end
diff --git a/alias b/alias
index 604bf06..2f5d14b 100644
--- a/alias
+++ b/alias
@@ -1,14 +1,11 @@
alias pg="ps aux | grep "
alias ng="netstat -an | grep "
alias mvi='mvim'
alias mivm='mvim'
alias it="git"
alias gitup="git stash && git pullr && git stash pop"
alias ls="ls -G"
-alias cdb="cv"
-
-alias cda="cdargs -a \`pwd\`"
diff --git a/gitconfig b/gitconfig
index 4078592..861219e 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,59 +1,59 @@
[user]
name = Jason Roelofs
email = [email protected]
signingkey = 1157F583
[github]
user = jasonroelofs
[color]
diff = auto
status = auto
branch = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
[alias]
st = status
ci = commit
co = checkout
dif = diff
cp = cherry-pick
unpushed = rev-list HEAD --pretty ^origin/master
lg = log --graph --pretty=format:'%Cred%h%Creset - %Cblue[%an]%Creset%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
pullr = pull --rebase
initial-commit = commit --allow-empty -m 'Initial Commit'
shove = push --force-with-lease
[merge]
tool = mvim
[mergetool "mvim"]
cmd = mvim -d -g $LOCAL $MERGED $REMOTE
keepbackup = false
[repack]
usedeltabaseoffset = true
[core]
- editor = /usr/local/bin/vim
+ editor = vim
pager = "less -FRX"
excludesfile = /Users/jroelofs/.gitignore
[push]
default = simple
[branch]
autosetupmerge = true
autosetuprebase = always
[credential]
helper = osxkeychain
[filter "lfs"]
required = true
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
[credentials]
helper = osxkeychain
diff --git a/profile b/profile
index 3111df7..42796de 100644
--- a/profile
+++ b/profile
@@ -1,45 +1,37 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
if [ -f `brew --prefix`/etc/profile.d/bash_completion.sh ]; then
. `brew --prefix`/etc/profile.d/bash_completion.sh
-
- for COMPLETION in `brew --prefix`/etc/bash_completion.d/*; do
- [[ -r "$COMPLETION" ]] && source "$COMPLETION"
- done
-fi
-
-if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
- . `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
-# Always start Vagrant with vmware
-export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
-
# No homebrew, you cannot send analytics
export HOMEBREW_NO_ANALYTICS=1
-# Never ever ever ever EVER run Spring on a Rails project
-export DISABLE_SPRING=1
-
# Enable kernel history in Erlang/Elixir (OTP 20 and later)
export ERL_AFLAGS="-kernel shell_history enabled"
# Shut up macOS, I know
export BASH_SILENCE_DEPRECATION_WARNING=1
+# Make mvim available on the command line
+export PATH="/Applications/MacVim.app/Contents/bin:$PATH"
+
+# ASDF
+export PATH="~/.asdf/shims:$PATH"
+
# Client-specific environment variables that we don't check into `dev`
if [ -f ~/.client-env ]; then
. ~/.client-env
fi
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
diff --git a/prompt b/prompt
index 79a573e..10add86 100644
--- a/prompt
+++ b/prompt
@@ -1,31 +1,30 @@
#!/bin/sh
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
parse_git_dirty () {
if [[ $((git status 2> /dev/null) | tail -n1) = "" ]]; then
echo ""
elif [[ $((git status 2> /dev/null) | tail -n1) != "nothing to commit, working directory clean" ]]; then
echo " â"
else
echo ""
fi
}
LIGHT_CYAN="\[\033[1;36m\]"
YELLOW="\[\033[1;33m\]"
LIGHT_RED="\[\033[1;31m\]"
WHITE="\[\033[1;37m\]"
RESET="\[\033[0m\]"
# Set up things so bash history remembers across terminals
# http://lpetr.org/blog/archives/preserve-bash-history
export HISTSIZE=50000
export HISTFILESIZE=50000
export HISTCONTROL=ignoredups:erasedups
shopt -s histappend
export PS1="$LIGHT_CYAN\u@\h:$YELLOW\w $LIGHT_RED\$(parse_git_branch)$(parse_git_dirty)$YELLOW\n] $RESET"
-export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"
diff --git a/vim/bundle/supertab b/vim/bundle/supertab
index 40fe711..f0093ae 160000
--- a/vim/bundle/supertab
+++ b/vim/bundle/supertab
@@ -1 +1 @@
-Subproject commit 40fe711e088e2ab346738233dd5adbb1be355172
+Subproject commit f0093ae12a9115498f887199809a6114659fc858
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 1cb03dd..285bde8 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,32 +1,26 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
-Plugin 'rking/ag.vim'
-Plugin 'kien/ctrlp.vim'
-Plugin 'FelikZ/ctrlp-py-matcher'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-fugitive'
" Languages / Syntax
Plugin 'sheerun/vim-polyglot'
-Plugin 'dense-analysis/ale'
" Go
Plugin 'fatih/vim-go'
Plugin 'Shougo/deoplete.nvim'
Plugin 'roxma/nvim-yarp'
-Plugin 'roxma/vim-hug-neovim-rpc'
-Plugin 'zchee/deoplete-go'
call vundle#end()
diff --git a/vimrc b/vimrc
index fb71a1c..0d80091 100644
--- a/vimrc
+++ b/vimrc
@@ -1,189 +1,139 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
-au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
+au BufRead,BufNewFile {Gemfile,Rakefile,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
-au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
-au BufRead,BufNewFile *.red set ft=rebol
-" TEMP! Until I figure out a name for my new language
-" and put together its own syntax highlighting
-au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
-""" Ag """
-set grepprg=ag\ --nogroup\ --nocolor
-
-""" Ctrl-P """
-let g:ctrlp_working_path_mode = 0
-let g:ctrlp_show_hidden = 0
-let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
-let g:ctrlp_use_caching = 1
-let g:ctrlp_max_files = 200000
-let g:ctrlp_match_window = 'top,order:ttb'
-let g:ctrlp_map = '<D-p>'
-let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
-
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
-
-""" Deoplete """
-let g:python3_host_prog = "/usr/local/bin/python3"
-let g:deoplete#enable_at_startup = 1
-call deoplete#custom#option('auto_complete_delay', 200)
-
-autocmd FileType text,markdown call deoplete#custom#buffer_option('auto_complete', v:false)
-
-""" Ale """
-let g:ale_linters = {}
-let g:ale_fixers = {}
-let g:ale_linters.javascript = ['eslint']
-let g:ale_fixers.javascript = ['eslint']
-let g:ale_fix_on_save = 1
-
-" Sorbet "
-if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
- call ale#linter#Define('ruby', {
- \ 'name': 'sorbet-lsp',
- \ 'lsp': 'stdio',
- \ 'executable': 'true',
- \ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
- \ 'language': 'ruby',
- \ 'project_root': $HOME . '/stripe/pay-server',
- \ })
-
- let g:ale_linters.ruby = ['sorbet-lsp']
-end
-
-""" Go """
-let g:go_fmt_command = "goimports"
-let g:deoplete#sources#go#gocode_binary = $HOME.'/go/bin/gocode'
|
jasonroelofs/dev
|
8ee17d847a6022c695b63ca632f936641be3f0ef
|
Fix up a few things
|
diff --git a/alias b/alias
index 7a7b935..604bf06 100644
--- a/alias
+++ b/alias
@@ -1,15 +1,14 @@
alias pg="ps aux | grep "
alias ng="netstat -an | grep "
alias mvi='mvim'
alias mivm='mvim'
alias it="git"
-alias cuc='bundle exec cucumber'
alias gitup="git stash && git pullr && git stash pop"
alias ls="ls -G"
alias cdb="cv"
alias cda="cdargs -a \`pwd\`"
diff --git a/profile b/profile
index 3afe34b..3111df7 100644
--- a/profile
+++ b/profile
@@ -1,38 +1,45 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
-if [ -f `brew --prefix`/etc/bash_completion ]; then
- . `brew --prefix`/etc/bash_completion
+if [ -f `brew --prefix`/etc/profile.d/bash_completion.sh ]; then
+ . `brew --prefix`/etc/profile.d/bash_completion.sh
+
+ for COMPLETION in `brew --prefix`/etc/bash_completion.d/*; do
+ [[ -r "$COMPLETION" ]] && source "$COMPLETION"
+ done
fi
if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
. `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
# Always start Vagrant with vmware
export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
# No homebrew, you cannot send analytics
export HOMEBREW_NO_ANALYTICS=1
# Never ever ever ever EVER run Spring on a Rails project
export DISABLE_SPRING=1
# Enable kernel history in Erlang/Elixir (OTP 20 and later)
export ERL_AFLAGS="-kernel shell_history enabled"
+# Shut up macOS, I know
+export BASH_SILENCE_DEPRECATION_WARNING=1
+
# Client-specific environment variables that we don't check into `dev`
if [ -f ~/.client-env ]; then
. ~/.client-env
fi
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
|
jasonroelofs/dev
|
38a5768cc713f666d8175fff60b2a3acc51cf2aa
|
Put a small delay on the autocomplete window
|
diff --git a/vimrc b/vimrc
index 856bc69..fb71a1c 100644
--- a/vimrc
+++ b/vimrc
@@ -1,188 +1,189 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 0
let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
let g:ctrlp_use_caching = 1
let g:ctrlp_max_files = 200000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
+call deoplete#custom#option('auto_complete_delay', 200)
autocmd FileType text,markdown call deoplete#custom#buffer_option('auto_complete', v:false)
""" Ale """
let g:ale_linters = {}
let g:ale_fixers = {}
let g:ale_linters.javascript = ['eslint']
let g:ale_fixers.javascript = ['eslint']
let g:ale_fix_on_save = 1
" Sorbet "
if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
call ale#linter#Define('ruby', {
\ 'name': 'sorbet-lsp',
\ 'lsp': 'stdio',
\ 'executable': 'true',
\ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
\ 'language': 'ruby',
\ 'project_root': $HOME . '/stripe/pay-server',
\ })
let g:ale_linters.ruby = ['sorbet-lsp']
end
""" Go """
let g:go_fmt_command = "goimports"
let g:deoplete#sources#go#gocode_binary = $HOME.'/go/bin/gocode'
|
jasonroelofs/dev
|
91c4dd6824eabaec977db72039f5d9d8be4e9dff
|
Hook up Git (fugitive) and faster loading of files into CtrlP
|
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 3976476..1cb03dd 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,31 +1,32 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'rking/ag.vim'
Plugin 'kien/ctrlp.vim'
Plugin 'FelikZ/ctrlp-py-matcher'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
+Plugin 'tpope/vim-fugitive'
" Languages / Syntax
Plugin 'sheerun/vim-polyglot'
Plugin 'dense-analysis/ale'
" Go
Plugin 'fatih/vim-go'
Plugin 'Shougo/deoplete.nvim'
Plugin 'roxma/nvim-yarp'
Plugin 'roxma/vim-hug-neovim-rpc'
Plugin 'zchee/deoplete-go'
call vundle#end()
diff --git a/vimrc b/vimrc
index 2a82aaf..856bc69 100644
--- a/vimrc
+++ b/vimrc
@@ -1,186 +1,188 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 0
let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
let g:ctrlp_use_caching = 1
-let g:ctrlp_max_files = 150000
+let g:ctrlp_max_files = 200000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
+let g:ctrlp_user_command = ['.git/', 'git --git-dir=%s/.git ls-files -oc --exclude-standard']
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
autocmd FileType text,markdown call deoplete#custom#buffer_option('auto_complete', v:false)
""" Ale """
let g:ale_linters = {}
let g:ale_fixers = {}
let g:ale_linters.javascript = ['eslint']
let g:ale_fixers.javascript = ['eslint']
let g:ale_fix_on_save = 1
" Sorbet "
if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
call ale#linter#Define('ruby', {
\ 'name': 'sorbet-lsp',
\ 'lsp': 'stdio',
\ 'executable': 'true',
\ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
\ 'language': 'ruby',
\ 'project_root': $HOME . '/stripe/pay-server',
\ })
let g:ale_linters.ruby = ['sorbet-lsp']
end
""" Go """
let g:go_fmt_command = "goimports"
+let g:deoplete#sources#go#gocode_binary = $HOME.'/go/bin/gocode'
|
jasonroelofs/dev
|
2cb71e98213c29eca304a66209f250d68ab053d6
|
Disable autocomplete for non-code file types
|
diff --git a/vimrc b/vimrc
index c203086..2a82aaf 100644
--- a/vimrc
+++ b/vimrc
@@ -1,184 +1,186 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 0
let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
let g:ctrlp_use_caching = 1
let g:ctrlp_max_files = 150000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
+autocmd FileType text,markdown call deoplete#custom#buffer_option('auto_complete', v:false)
+
""" Ale """
let g:ale_linters = {}
let g:ale_fixers = {}
let g:ale_linters.javascript = ['eslint']
let g:ale_fixers.javascript = ['eslint']
let g:ale_fix_on_save = 1
" Sorbet "
if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
call ale#linter#Define('ruby', {
\ 'name': 'sorbet-lsp',
\ 'lsp': 'stdio',
\ 'executable': 'true',
\ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
\ 'language': 'ruby',
\ 'project_root': $HOME . '/stripe/pay-server',
\ })
let g:ale_linters.ruby = ['sorbet-lsp']
end
""" Go """
let g:go_fmt_command = "goimports"
|
jasonroelofs/dev
|
158f65c5f3be7b6a5cb0e807883a4c92a5d048f2
|
Tweaks to ruby and go options
|
diff --git a/vim/ftplugin/go.vim b/vim/ftplugin/go.vim
index 25863df..f5516f9 100644
--- a/vim/ftplugin/go.vim
+++ b/vim/ftplugin/go.vim
@@ -1,19 +1,20 @@
" Easy commenting / uncommenting
map z :s/^/\/\/<CR><Down>
map Z :s/^\s*\(\/\/\)//<CR><Down>
-map <leader>t :GoTest<CR>
+nmap <leader>t :GoTest<CR>
+nmap <leader>d :GoDef<CR>
" Test generation macros
iabbr _test func Test_(t *testing.T) {<ESC>16<LEFT>s
" Testify macros
iabbr _ae assert.Equal(t,
iabbr _ane assert.NotEqual(t,
iabbr _an assert.Nil(t,
iabbr _ann assert.NotNil(t,
iabbr _at assert.True(t,
iabbr _af assert.False(t,
iabbr _ac assert.Contains(t,
iabbr _anc assert.NotContains(t,
diff --git a/vim/ftplugin/ruby.vim b/vim/ftplugin/ruby.vim
index 8221222..783f52b 100644
--- a/vim/ftplugin/ruby.vim
+++ b/vim/ftplugin/ruby.vim
@@ -1,28 +1,30 @@
"""""""""""""""""""""""""""""
" Custom Ruby configuration "
"""""""""""""""""""""""""""""
" Run syntax check on the current file
noremap <F4> :w<CR>:!ruby -c '%'<CR>
" Easy commenting / uncommenting
noremap z :s/^/#<CR><Down>
noremap Z :s/^\s*\(#\)//<CR><Down>
" ERB helpers
iabbr _rv <%= %><Esc>2<Left>i
iabbr _rc <% %><Esc>2<Left>i
" Test::Unit macros
iabbr _ae assert_equal
iabbr _ane assert_not_equal
iabbr _aid assert_in_delta expect, actual, delta, ""
iabbr _ai assert_instance_of
iabbr _ak assert_kind_of
iabbr _am assert_match
iabbr _an assert_nil
iabbr _ann assert_not_nil
iabbr _as assert_same
iabbr _ans assert_not_same
iabbr _art assert_redirected_to
+" Bind <leader>d to go-to-definition.
+nmap <leader>d <Plug>(ale_go_to_definition)
diff --git a/vimrc b/vimrc
index 57bef27..c203086 100644
--- a/vimrc
+++ b/vimrc
@@ -1,184 +1,184 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 0
let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
let g:ctrlp_use_caching = 1
let g:ctrlp_max_files = 150000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
""" Ale """
let g:ale_linters = {}
let g:ale_fixers = {}
let g:ale_linters.javascript = ['eslint']
let g:ale_fixers.javascript = ['eslint']
let g:ale_fix_on_save = 1
" Sorbet "
if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
call ale#linter#Define('ruby', {
\ 'name': 'sorbet-lsp',
\ 'lsp': 'stdio',
\ 'executable': 'true',
\ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
\ 'language': 'ruby',
\ 'project_root': $HOME . '/stripe/pay-server',
\ })
let g:ale_linters.ruby = ['sorbet-lsp']
end
-" Bind <leader>d to go-to-definition.
-nmap <leader>d <Plug>(ale_go_to_definition)
+""" Go """
+let g:go_fmt_command = "goimports"
|
jasonroelofs/dev
|
e3ad2edae862c72174a6bdaf4bc13950162d7636
|
Fix linter def to not clobber other options
|
diff --git a/vimrc b/vimrc
index f9d40e6..57bef27 100644
--- a/vimrc
+++ b/vimrc
@@ -1,181 +1,184 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 0
let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
let g:ctrlp_use_caching = 1
let g:ctrlp_max_files = 150000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
""" Ale """
-let g:ale_fixers = { 'javascript': ['eslint'] }
+let g:ale_linters = {}
+let g:ale_fixers = {}
+let g:ale_linters.javascript = ['eslint']
+let g:ale_fixers.javascript = ['eslint']
let g:ale_fix_on_save = 1
" Sorbet "
if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
call ale#linter#Define('ruby', {
\ 'name': 'sorbet-lsp',
\ 'lsp': 'stdio',
\ 'executable': 'true',
\ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
\ 'language': 'ruby',
\ 'project_root': $HOME . '/stripe/pay-server',
\ })
- let g:ale_linters = {'ruby': ['sorbet-lsp']}
+ let g:ale_linters.ruby = ['sorbet-lsp']
end
" Bind <leader>d to go-to-definition.
nmap <leader>d <Plug>(ale_go_to_definition)
|
jasonroelofs/dev
|
87f8048bc3b368982c69ff4ddb2262d6450d5a61
|
Allow Enter to "run last command" in Pry
|
diff --git a/pryrc b/pryrc
index 27b0c1e..d81e158 100644
--- a/pryrc
+++ b/pryrc
@@ -1,4 +1,8 @@
Pry.commands.alias_command 'c', 'continue'
Pry.commands.alias_command 's', 'step'
Pry.commands.alias_command 'n', 'next'
Pry.commands.alias_command 'f', 'finish'
+
+Pry.config.commands.command(/^$/, 'repeat last command') do
+ __pry__.input = StringIO.new(Pry.history.to_a.last)
+end
|
jasonroelofs/dev
|
80143d40978a450816653be4861cdefe94b090f6
|
Switch CTRLP to use py-matcher (faster) and hook up Sorbet LSP
|
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 08b665a..3976476 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,29 +1,31 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'rking/ag.vim'
Plugin 'kien/ctrlp.vim'
+Plugin 'FelikZ/ctrlp-py-matcher'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
" Languages / Syntax
Plugin 'sheerun/vim-polyglot'
+Plugin 'dense-analysis/ale'
" Go
Plugin 'fatih/vim-go'
Plugin 'Shougo/deoplete.nvim'
Plugin 'roxma/nvim-yarp'
Plugin 'roxma/vim-hug-neovim-rpc'
Plugin 'zchee/deoplete-go'
call vundle#end()
diff --git a/vimrc b/vimrc
index c96f5e7..f9d40e6 100644
--- a/vimrc
+++ b/vimrc
@@ -1,158 +1,181 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
" TEMP! Until I figure out a name for my new language
" and put together its own syntax highlighting
au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
-let g:ctrlp_show_hidden = 1
-let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
-let g:ctrlp_use_caching = 0
+let g:ctrlp_show_hidden = 0
+let g:ctrlp_match_func = { 'match': 'pymatcher#PyMatch' }
+let g:ctrlp_use_caching = 1
+let g:ctrlp_max_files = 150000
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
+let g:python3_host_prog = "/usr/local/bin/python3"
let g:deoplete#enable_at_startup = 1
+
+""" Ale """
+let g:ale_fixers = { 'javascript': ['eslint'] }
+let g:ale_fix_on_save = 1
+
+" Sorbet "
+if fnamemodify(getcwd(), ':p') == $HOME.'/stripe/pay-server/'
+ call ale#linter#Define('ruby', {
+ \ 'name': 'sorbet-lsp',
+ \ 'lsp': 'stdio',
+ \ 'executable': 'true',
+ \ 'command': 'pay exec scripts/bin/typecheck --lsp -v',
+ \ 'language': 'ruby',
+ \ 'project_root': $HOME . '/stripe/pay-server',
+ \ })
+
+ let g:ale_linters = {'ruby': ['sorbet-lsp']}
+end
+
+" Bind <leader>d to go-to-definition.
+nmap <leader>d <Plug>(ale_go_to_definition)
|
jasonroelofs/dev
|
cd99ed7f0c5436006b5392a2c8b66a3bf579e9a2
|
Add steps for ensuring vim/MacVim are installed correctly
|
diff --git a/Rakefile b/Rakefile
index cc9113d..6851bb9 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,26 +1,34 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
%w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc pryrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
end
+ puts "Setting up Python for MacVim + deoplete. Python3 required"
+ sh "python3 -m pip install pynvim"
+
+ puts "Install Vundle for vim plugin management"
+ sh "git clone https://github.com/VundleVim/Vundle.vim.git ~/.vim/bundle/Vundle.vim"
+
[
# Enable Bundles in Mail
"defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
"defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
].each do |option|
sh option
end
+
+ puts "", "Ready! Jump into vim and run :BundleInstall to get all plugins", ""
end
|
jasonroelofs/dev
|
365a1267196bcf1ae38d8b4b4076747ef08b31fc
|
Only need to run this once
|
diff --git a/Rakefile b/Rakefile
index 9b59684..cc9113d 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,26 +1,26 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
%w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc pryrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
+ end
- [
- # Enable Bundles in Mail
- "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
- "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
- ].each do |option|
- sh option
- end
+ [
+ # Enable Bundles in Mail
+ "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
+ "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
+ ].each do |option|
+ sh option
end
end
|
jasonroelofs/dev
|
4a49e5455ffd9c67044dfa58f78744e2481795df
|
Store my custom pry configs
|
diff --git a/Rakefile b/Rakefile
index 31cf778..9b59684 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,26 +1,26 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
- %w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc).each do |name|
+ %w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc pryrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
[
# Enable Bundles in Mail
"defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
"defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
].each do |option|
sh option
end
end
end
diff --git a/pryrc b/pryrc
new file mode 100644
index 0000000..27b0c1e
--- /dev/null
+++ b/pryrc
@@ -0,0 +1,4 @@
+Pry.commands.alias_command 'c', 'continue'
+Pry.commands.alias_command 's', 'step'
+Pry.commands.alias_command 'n', 'next'
+Pry.commands.alias_command 'f', 'finish'
|
jasonroelofs/dev
|
3fbe52e42186c037dfdf1fec0d1c11b015d30cfb
|
Ignore any dotenv local files
|
diff --git a/gitignore b/gitignore
index 456bf2f..8444c5c 100644
--- a/gitignore
+++ b/gitignore
@@ -1,10 +1,11 @@
.DS_Store
.rvmrc
*.rbc
.*.swp
.powrc
.powenv
.foreman
.ruby-version
.sass-cache
TODO
+.envrc
|
jasonroelofs/dev
|
eef791f7eb573f9cb16898ab44d6c435ff25a8d4
|
Some minor changes
|
diff --git a/gemrc b/gemrc
index 6153a6e..be43970 100644
--- a/gemrc
+++ b/gemrc
@@ -1 +1 @@
-gem: --no-ri --no-rdoc
+gem: --no-ri --no-rdoc --no-document
diff --git a/gitignore b/gitignore
index 15078f9..456bf2f 100644
--- a/gitignore
+++ b/gitignore
@@ -1,11 +1,10 @@
.DS_Store
.rvmrc
*.rbc
.*.swp
-proto
.powrc
.powenv
.foreman
.ruby-version
.sass-cache
TODO
diff --git a/profile b/profile
index db1d605..3afe34b 100644
--- a/profile
+++ b/profile
@@ -1,33 +1,38 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
. `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
# Always start Vagrant with vmware
export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
# No homebrew, you cannot send analytics
export HOMEBREW_NO_ANALYTICS=1
# Never ever ever ever EVER run Spring on a Rails project
export DISABLE_SPRING=1
# Enable kernel history in Erlang/Elixir (OTP 20 and later)
export ERL_AFLAGS="-kernel shell_history enabled"
+# Client-specific environment variables that we don't check into `dev`
+if [ -f ~/.client-env ]; then
+ . ~/.client-env
+fi
+
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
diff --git a/vimrc b/vimrc
index cf7514e..c96f5e7 100644
--- a/vimrc
+++ b/vimrc
@@ -1,155 +1,158 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Close all other splits than mine
:map <leader>o :only<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
" Keep scratch buffer from showing up in autocomplete calls
set completeopt-=preview
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
au BufRead,BufNewFile *.red set ft=rebol
+" TEMP! Until I figure out a name for my new language
+" and put together its own syntax highlighting
+au BufRead,BufNewFile *.lang set ft=ruby
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 1
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
let g:ctrlp_use_caching = 0
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Deoplete """
let g:deoplete#enable_at_startup = 1
|
jasonroelofs/dev
|
ee206db4e03ce40baf5ca17e9ffbb01dc5d8c008
|
Better bash history storage and usage
|
diff --git a/prompt b/prompt
index 5956550..79a573e 100644
--- a/prompt
+++ b/prompt
@@ -1,23 +1,31 @@
#!/bin/sh
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
parse_git_dirty () {
if [[ $((git status 2> /dev/null) | tail -n1) = "" ]]; then
echo ""
elif [[ $((git status 2> /dev/null) | tail -n1) != "nothing to commit, working directory clean" ]]; then
echo " â"
else
echo ""
fi
}
LIGHT_CYAN="\[\033[1;36m\]"
YELLOW="\[\033[1;33m\]"
LIGHT_RED="\[\033[1;31m\]"
WHITE="\[\033[1;37m\]"
RESET="\[\033[0m\]"
+# Set up things so bash history remembers across terminals
+# http://lpetr.org/blog/archives/preserve-bash-history
+export HISTSIZE=50000
+export HISTFILESIZE=50000
+export HISTCONTROL=ignoredups:erasedups
+shopt -s histappend
+
export PS1="$LIGHT_CYAN\u@\h:$YELLOW\w $LIGHT_RED\$(parse_git_branch)$(parse_git_dirty)$YELLOW\n] $RESET"
+export PROMPT_COMMAND="${PROMPT_COMMAND:+$PROMPT_COMMAND$'\n'}history -a; history -c; history -r"
|
jasonroelofs/dev
|
3e3d2f6ad8c6f70b71e3e246449dc889185a865d
|
Use REBOL syntax highlighting for Red
|
diff --git a/vimrc b/vimrc
index e117517..056d215 100644
--- a/vimrc
+++ b/vimrc
@@ -1,153 +1,154 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
+au BufRead,BufNewFile *.red set ft=rebol
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 1
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
let g:ctrlp_use_caching = 0
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Sweeter Vest """
let g:clear_each_run=1
let g:sweeter_vest_skip_mappings=1
nnoremap <F5> :SweeterVestRunFile<cr>
nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
a2da1728ca9eac532d3022068f94e8ca65ddda37
|
Keep Erlang/IEX history!
|
diff --git a/profile b/profile
index beebf05..db1d605 100644
--- a/profile
+++ b/profile
@@ -1,30 +1,33 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
. `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
# Always start Vagrant with vmware
export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
# No homebrew, you cannot send analytics
export HOMEBREW_NO_ANALYTICS=1
# Never ever ever ever EVER run Spring on a Rails project
export DISABLE_SPRING=1
+# Enable kernel history in Erlang/Elixir (OTP 20 and later)
+export ERL_AFLAGS="-kernel shell_history enabled"
+
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
|
jasonroelofs/dev
|
4e29130155d73c22ebf1ca66e7b682a36813a410
|
`git shove`, the safe version of `git push --force`
|
diff --git a/gitconfig b/gitconfig
index e44eb77..841dc00 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,48 +1,49 @@
[user]
name = Jason Roelofs
email = [email protected]
[color]
diff = auto
status = auto
branch = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
[alias]
st = status
ci = commit
co = checkout
dif = diff
cp = cherry-pick
unpushed = rev-list HEAD --pretty ^origin/master
lg = log --graph --pretty=format:'%Cred%h%Creset - %Cblue[%an]%Creset%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
pullr = pull --rebase
initial-commit = commit --allow-empty -m 'Initial Commit'
+ shove = push --force-with-lease
[merge]
tool = mvim
[mergetool "mvim"]
cmd = mvim -d -g $LOCAL $MERGED $REMOTE
keepbackup = false
[repack]
usedeltabaseoffset = true
[core]
editor = /usr/local/bin/vim
pager = "less -FRX"
excludesfile = /Users/jroelofs/.gitignore
[push]
default = simple
[branch]
autosetupmerge = true
autosetuprebase = always
[credential]
helper = osxkeychain
|
jasonroelofs/dev
|
6afcade19b7b2014f0b7dc4d03084a7b5fdda86d
|
Move to using vim-polyglot and update vim plugins
|
diff --git a/vim/bundle/powerline b/vim/bundle/powerline
index d816de0..cdd0cdb 160000
--- a/vim/bundle/powerline
+++ b/vim/bundle/powerline
@@ -1 +1 @@
-Subproject commit d816de054a7ce02c61543718f94ec968d3a9694b
+Subproject commit cdd0cdbfee94238d38c1bef5f0548a4622518a05
diff --git a/vim/bundle/vim-coffee-script b/vim/bundle/vim-coffee-script
deleted file mode 160000
index 32fe889..0000000
--- a/vim/bundle/vim-coffee-script
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 32fe889b8cafd3a4921ef8e6485156453ff58c42
diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails
index 7ea50ed..80e03f7 160000
--- a/vim/bundle/vim-rails
+++ b/vim/bundle/vim-rails
@@ -1 +1 @@
-Subproject commit 7ea50ede5420058d3d5142d1a5d635ce876486cf
+Subproject commit 80e03f766f5f049d6bd8998bd7b25b77ddaa9a1e
diff --git a/vim/bundle/vim-ruby b/vim/bundle/vim-ruby
deleted file mode 160000
index 97bc933..0000000
--- a/vim/bundle/vim-ruby
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 97bc93301057b4ea27ae93c6d5c9749f77ca702b
diff --git a/vim/bundles.vim b/vim/bundles.vim
index a5fafe1..573df61 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,33 +1,24 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'rking/ag.vim'
Plugin 'kien/ctrlp.vim'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
Plugin 'emilford/vim-sweeter-vest'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
" Languages / Syntax
-Plugin 'scrooloose/Syntastic'
-Plugin 'fatih/vim-go'
-Plugin 'vim-ruby/vim-ruby'
-Plugin 'kchmck/vim-coffee-script'
-Plugin 'othree/html5.vim'
-Plugin 'wting/rust.vim'
-Plugin 'cespare/vim-toml'
-Plugin 'slim-template/vim-slim'
-Plugin 'elixir-lang/vim-elixir'
-Plugin 'markcornick/vim-terraform'
+Plugin 'sheerun/vim-polyglot'
call vundle#end()
|
jasonroelofs/dev
|
e934fb40496b0da3ba1323b5c471e4a94b8a7ec4
|
Spring is bad
|
diff --git a/profile b/profile
index 97f40a7..beebf05 100644
--- a/profile
+++ b/profile
@@ -1,27 +1,30 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
. `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
# Always start Vagrant with vmware
export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
# No homebrew, you cannot send analytics
export HOMEBREW_NO_ANALYTICS=1
+# Never ever ever ever EVER run Spring on a Rails project
+export DISABLE_SPRING=1
+
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
|
jasonroelofs/dev
|
21f3a5ab643b53c656e94c493149651cf43f0f5d
|
Bundle update
|
diff --git a/vim/bundle/powerline b/vim/bundle/powerline
index 3bcd0ec..d816de0 160000
--- a/vim/bundle/powerline
+++ b/vim/bundle/powerline
@@ -1 +1 @@
-Subproject commit 3bcd0ec54754601fed4da05ff6433a8aa9e1bcc2
+Subproject commit d816de054a7ce02c61543718f94ec968d3a9694b
diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails
index b131dc9..7ea50ed 160000
--- a/vim/bundle/vim-rails
+++ b/vim/bundle/vim-rails
@@ -1 +1 @@
-Subproject commit b131dc94bb4f9f1a620ed2e7f1a8a2f497df5661
+Subproject commit 7ea50ede5420058d3d5142d1a5d635ce876486cf
diff --git a/vim/bundle/vim-ruby b/vim/bundle/vim-ruby
index 666adb5..97bc933 160000
--- a/vim/bundle/vim-ruby
+++ b/vim/bundle/vim-ruby
@@ -1 +1 @@
-Subproject commit 666adb5bcdfb2d21572a58fcdf7545a26bac32a0
+Subproject commit 97bc93301057b4ea27ae93c6d5c9749f77ca702b
diff --git a/vim/bundle/vim-surround b/vim/bundle/vim-surround
index 2d05440..e49d6c2 160000
--- a/vim/bundle/vim-surround
+++ b/vim/bundle/vim-surround
@@ -1 +1 @@
-Subproject commit 2d05440ad23f97a7874ebd9b5de3a0e65d25d85c
+Subproject commit e49d6c2459e0f5569ff2d533b4df995dd7f98313
|
jasonroelofs/dev
|
13d429cf3636ca06ed1732ff497b01292f567970
|
Fix matching text in prompt
|
diff --git a/prompt b/prompt
index 1afcebc..5956550 100644
--- a/prompt
+++ b/prompt
@@ -1,23 +1,23 @@
#!/bin/sh
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'
}
parse_git_dirty () {
if [[ $((git status 2> /dev/null) | tail -n1) = "" ]]; then
echo ""
- elif [[ $((git status 2> /dev/null) | tail -n1) != "nothing to commit (working directory clean)" ]]; then
+ elif [[ $((git status 2> /dev/null) | tail -n1) != "nothing to commit, working directory clean" ]]; then
echo " â"
else
echo ""
fi
}
LIGHT_CYAN="\[\033[1;36m\]"
YELLOW="\[\033[1;33m\]"
LIGHT_RED="\[\033[1;31m\]"
WHITE="\[\033[1;37m\]"
RESET="\[\033[0m\]"
export PS1="$LIGHT_CYAN\u@\h:$YELLOW\w $LIGHT_RED\$(parse_git_branch)$(parse_git_dirty)$YELLOW\n] $RESET"
|
jasonroelofs/dev
|
30076cb19016a4b46340f3a38d6af3f5c620bf6c
|
Some dev-land settings updates
|
diff --git a/gitignore b/gitignore
index 87af1d6..99c1223 100644
--- a/gitignore
+++ b/gitignore
@@ -1,9 +1,10 @@
.DS_Store
.rvmrc
*.rbc
.*.swp
proto
.powrc
.powenv
.foreman
.ruby-version
+.sass-cache
diff --git a/profile b/profile
index 0ce0254..97f40a7 100644
--- a/profile
+++ b/profile
@@ -1,21 +1,27 @@
if [ -f ~/.prompt ]; then
. ~/.prompt
fi
if [ -f ~/.alias ]; then
. ~/.alias
fi
if [ -f `brew --prefix`/etc/bash_completion ]; then
. `brew --prefix`/etc/bash_completion
fi
if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
. `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
fi
export EDITOR=vim
+# Always start Vagrant with vmware
+export VAGRANT_DEFAULT_PROVIDER=vmware_fusion
+
+# No homebrew, you cannot send analytics
+export HOMEBREW_NO_ANALYTICS=1
+
if [ -f ~/.bashrc ]; then
. ~/.bashrc
fi
diff --git a/vim/ftplugin/elixir.vim b/vim/ftplugin/elixir.vim
new file mode 100644
index 0000000..f2815c2
--- /dev/null
+++ b/vim/ftplugin/elixir.vim
@@ -0,0 +1,11 @@
+"""""""""""""""""""""""""""""
+" Custom Ruby configuration "
+"""""""""""""""""""""""""""""
+
+" Easy commenting / uncommenting
+noremap z :s/^/#<CR><Down>
+noremap Z :s/^\s*\(#\)//<CR><Down>
+
+" ERB helpers
+iabbr _rv <%= %><Esc>2<Left>i
+iabbr _rc <% %><Esc>2<Left>i
diff --git a/vimrc b/vimrc
index f45bb93..e117517 100644
--- a/vimrc
+++ b/vimrc
@@ -1,154 +1,153 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
-" Custom File types handling
-au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
-au BufNewFile,BufRead *.json set ft=javascript
-
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
+au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
+au BufNewFile,BufRead *.json set ft=javascript
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
+au BufRead,BufNewFile *.tpl,*.incl set ft=smarty
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 1
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
let g:ctrlp_use_caching = 0
let g:ctrlp_match_window = 'top,order:ttb'
let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Sweeter Vest """
let g:clear_each_run=1
let g:sweeter_vest_skip_mappings=1
nnoremap <F5> :SweeterVestRunFile<cr>
nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
c9fe6e9fab875e01d39518ea27d9b6ec41ed94fa
|
Vim bundle update
|
diff --git a/vim/bundle/powerline b/vim/bundle/powerline
index 2fa7c3c..aa33599 160000
--- a/vim/bundle/powerline
+++ b/vim/bundle/powerline
@@ -1 +1 @@
-Subproject commit 2fa7c3cfc8023a927e44975514b7da4d5ac6e57e
+Subproject commit aa33599e3fb363ab7f2744ce95b7c6465eef7f08
diff --git a/vim/bundle/supertab b/vim/bundle/supertab
index c8bfece..9f7da6d 160000
--- a/vim/bundle/supertab
+++ b/vim/bundle/supertab
@@ -1 +1 @@
-Subproject commit c8bfeceb1fc92ad58f2ae6967cbfcd6fbcb0d6e7
+Subproject commit 9f7da6d4988daf863ebc414f221bb12c2614f59e
diff --git a/vim/bundle/syntastic b/vim/bundle/syntastic
index a7fde99..e1217a8 160000
--- a/vim/bundle/syntastic
+++ b/vim/bundle/syntastic
@@ -1 +1 @@
-Subproject commit a7fde99ea9a4eb26e6dfedb3ea54bbeefb71b325
+Subproject commit e1217a888a6d1f3266ca610b04d1752cea837438
diff --git a/vim/bundle/vim-endwise b/vim/bundle/vim-endwise
index bba43b8..f06abe3 160000
--- a/vim/bundle/vim-endwise
+++ b/vim/bundle/vim-endwise
@@ -1 +1 @@
-Subproject commit bba43b831ae0485cf9b86d16340a6a314b927391
+Subproject commit f06abe3d6eca6f6ebfc31ea3163a51575f450df6
diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails
index 6092275..b07208e 160000
--- a/vim/bundle/vim-rails
+++ b/vim/bundle/vim-rails
@@ -1 +1 @@
-Subproject commit 609227534f11a7cf7b3ba1cf51c79b72e5c9ba1b
+Subproject commit b07208e63e45a9780292bd2af9e45dae358ce24f
diff --git a/vim/bundle/vim-ruby b/vim/bundle/vim-ruby
index ef2deea..3db2f83 160000
--- a/vim/bundle/vim-ruby
+++ b/vim/bundle/vim-ruby
@@ -1 +1 @@
-Subproject commit ef2deeae81f540a17a3da5907146b3579c8ee0d6
+Subproject commit 3db2f8362011c984d1acfcae42b5cedf9b64219f
diff --git a/vim/bundle/vim-surround b/vim/bundle/vim-surround
index 772ab95..2d05440 160000
--- a/vim/bundle/vim-surround
+++ b/vim/bundle/vim-surround
@@ -1 +1 @@
-Subproject commit 772ab9587b7d1e2c3bae75395c9123803059ba8a
+Subproject commit 2d05440ad23f97a7874ebd9b5de3a0e65d25d85c
diff --git a/vim/bundles.vim b/vim/bundles.vim
index b93cc0b..a6640ad 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,32 +1,31 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'rking/ag.vim'
Plugin 'kien/ctrlp.vim'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
Plugin 'emilford/vim-sweeter-vest'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
" Languages / Syntax
Plugin 'scrooloose/Syntastic'
Plugin 'fatih/vim-go'
Plugin 'vim-ruby/vim-ruby'
Plugin 'kchmck/vim-coffee-script'
-Plugin 'beyondmarc/glsl.vim'
Plugin 'othree/html5.vim'
Plugin 'wting/rust.vim'
Plugin 'cespare/vim-toml'
Plugin 'slim-template/vim-slim'
call vundle#end()
|
jasonroelofs/dev
|
721f7c1aef67b33a7e512d68b8f59fed0f8dd741
|
Make sure ctrl-p is fully mapped to Command-p
|
diff --git a/gvimrc b/gvimrc
index b0558d3..7706f50 100644
--- a/gvimrc
+++ b/gvimrc
@@ -1,51 +1,52 @@
"""""""""""""""""""""""""""
""" Gvim Global Configs """
"""""""""""""""""""""""""""
command -nargs=0 Zoom :macaction performZoom:
" Setup the font (Bitstream on Linux, Lucida on Windows)
:set guifont=Monaco:h16.00,Bitstream\ Vera\ Sans\ Mono\ 11,\ Lucida_Sans_Typewriter:h8:cANSI
" Set all gui options
" Options can be set or unset with
" :set guioptions+=(options)
" :set guioptions-=(options)
" Options
" r - right scrollbar
" l - left scrollbar
" b - bottom scrollbar
" m - menu bar
" t - tools bar
" e - Macvim native tabs
"Disable all options, scrollbars give funky business in full screen
:set guioptions=e
:cabbr toff set guioptions-=T
:cabbr ton set guioptions+=T
:cabbr moff set guioptions-=m
:cabbr mon set guioptions+=m
" Maximize both dimensions when going fullscreen
:set fuopt=maxhorz,maxvert
:highlight Normal guifg=white guibg=black
"""""""""""""""""""""""""""""
""" Plugin Initialization """
"""""""""""""""""""""""""""""
""" CtrlP """
" I want Command+p!
if has("gui_macvim")
macmenu &File.Print key=<nop>
+ let g:ctrlp_map = '<D-p>'
nmap <D-p> :CtrlP<CR>
nmap <D-P> :CtrlPBuffer<CR>
endif
""" SweeterVest """
" Ensure dispatch is always turned on if we're in MacVim
let g:use_dispatch=1
diff --git a/vimrc b/vimrc
index ed44fb5..f45bb93 100644
--- a/vimrc
+++ b/vimrc
@@ -1,153 +1,154 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
" Custom File types handling
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" Ag """
set grepprg=ag\ --nogroup\ --nocolor
""" Ctrl-P """
let g:ctrlp_working_path_mode = 0
let g:ctrlp_show_hidden = 1
let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
let g:ctrlp_use_caching = 0
let g:ctrlp_match_window = 'top,order:ttb'
+let g:ctrlp_map = '<D-p>'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Sweeter Vest """
let g:clear_each_run=1
let g:sweeter_vest_skip_mappings=1
nnoremap <F5> :SweeterVestRunFile<cr>
nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
e8a053c680d033cb5b576f418ed8c5e2ceb0ccdd
|
System username changed to jroelofs
|
diff --git a/gitconfig b/gitconfig
index 80402f2..e44eb77 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,48 +1,48 @@
[user]
name = Jason Roelofs
email = [email protected]
[color]
diff = auto
status = auto
branch = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
[alias]
st = status
ci = commit
co = checkout
dif = diff
cp = cherry-pick
unpushed = rev-list HEAD --pretty ^origin/master
lg = log --graph --pretty=format:'%Cred%h%Creset - %Cblue[%an]%Creset%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
pullr = pull --rebase
initial-commit = commit --allow-empty -m 'Initial Commit'
[merge]
tool = mvim
[mergetool "mvim"]
cmd = mvim -d -g $LOCAL $MERGED $REMOTE
keepbackup = false
[repack]
usedeltabaseoffset = true
[core]
editor = /usr/local/bin/vim
pager = "less -FRX"
- excludesfile = /Users/roelofs/.gitignore
+ excludesfile = /Users/jroelofs/.gitignore
[push]
default = simple
[branch]
autosetupmerge = true
autosetuprebase = always
[credential]
helper = osxkeychain
|
jasonroelofs/dev
|
01e2c311f8604ccb100355e2241a2a146ef3e68b
|
Start documenting various defaults I like using
|
diff --git a/Rakefile b/Rakefile
index 9927e77..31cf778 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,18 +1,26 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
%w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
+
+ [
+ # Enable Bundles in Mail
+ "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist EnableBundles -bool true",
+ "defaults write ~/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail.plist BundleCompatibilityVersion -int 4"
+ ].each do |option|
+ sh option
+ end
end
end
|
jasonroelofs/dev
|
1eb5a55482825e45152b0830f1dc8267f8b1e8e9
|
Vim Bundle updates
|
diff --git a/vim/bundle/powerline b/vim/bundle/powerline
index 364fc4d..2fa7c3c 160000
--- a/vim/bundle/powerline
+++ b/vim/bundle/powerline
@@ -1 +1 @@
-Subproject commit 364fc4dcd95352c57177b578643056e40709d9aa
+Subproject commit 2fa7c3cfc8023a927e44975514b7da4d5ac6e57e
diff --git a/vim/bundle/syntastic b/vim/bundle/syntastic
index 710a854..a7fde99 160000
--- a/vim/bundle/syntastic
+++ b/vim/bundle/syntastic
@@ -1 +1 @@
-Subproject commit 710a854f6a6832004b225c25d5c076bb537fd589
+Subproject commit a7fde99ea9a4eb26e6dfedb3ea54bbeefb71b325
diff --git a/vim/bundle/vim-coffee-script b/vim/bundle/vim-coffee-script
index 827e4a3..32fe889 160000
--- a/vim/bundle/vim-coffee-script
+++ b/vim/bundle/vim-coffee-script
@@ -1 +1 @@
-Subproject commit 827e4a38b07479433b619091469a7495a392df8a
+Subproject commit 32fe889b8cafd3a4921ef8e6485156453ff58c42
diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails
index 981f8d7..6092275 160000
--- a/vim/bundle/vim-rails
+++ b/vim/bundle/vim-rails
@@ -1 +1 @@
-Subproject commit 981f8d790cbecd5bbbb907aa30a94f63b6aee041
+Subproject commit 609227534f11a7cf7b3ba1cf51c79b72e5c9ba1b
diff --git a/vim/bundle/vim-ruby b/vim/bundle/vim-ruby
index c298d2f..ef2deea 160000
--- a/vim/bundle/vim-ruby
+++ b/vim/bundle/vim-ruby
@@ -1 +1 @@
-Subproject commit c298d2f352559f0c690d5e75f7ed6ce0c61ff474
+Subproject commit ef2deeae81f540a17a3da5907146b3579c8ee0d6
|
jasonroelofs/dev
|
7f61124872aba1d31c086816eae7b8aca789c92b
|
Alias cdargs' new 'cv' to my expected 'cdb'
|
diff --git a/alias b/alias
index a953075..7a7b935 100644
--- a/alias
+++ b/alias
@@ -1,14 +1,15 @@
alias pg="ps aux | grep "
alias ng="netstat -an | grep "
alias mvi='mvim'
alias mivm='mvim'
alias it="git"
alias cuc='bundle exec cucumber'
alias gitup="git stash && git pullr && git stash pop"
alias ls="ls -G"
+alias cdb="cv"
alias cda="cdargs -a \`pwd\`"
|
jasonroelofs/dev
|
36b0a62a12c15901f91de7fc9fc5d43748333277
|
Combine common bashrc requirements into and link a .profile
|
diff --git a/Rakefile b/Rakefile
index 935a656..9927e77 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,18 +1,18 @@
require 'fileutils'
include FileUtils
desc "Install everything"
task :install do
sh "mkdir -p ~/._backup"
- %w(vim vimrc gvimrc gitconfig gitignore alias prompt gemrc).each do |name|
+ %w(vim vimrc gvimrc gitconfig gitignore profile prompt alias gemrc).each do |name|
path = File.join(ENV["HOME"], ".#{name}")
if (File.file?(path) || File.directory?(path)) && !File.symlink?(path)
sh %Q(mv ~/.#{name} ~/._backup/#{name})
end
if !File.symlink?(path)
sh %Q(ln -s `pwd`/#{name} ~/.#{name})
end
end
end
diff --git a/profile b/profile
new file mode 100644
index 0000000..0ce0254
--- /dev/null
+++ b/profile
@@ -0,0 +1,21 @@
+if [ -f ~/.prompt ]; then
+ . ~/.prompt
+fi
+
+if [ -f ~/.alias ]; then
+ . ~/.alias
+fi
+
+if [ -f `brew --prefix`/etc/bash_completion ]; then
+ . `brew --prefix`/etc/bash_completion
+fi
+
+if [ -f `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh ]; then
+ . `brew --prefix`/Cellar/cdargs/1.35/contrib/cdargs-bash.sh
+fi
+
+export EDITOR=vim
+
+if [ -f ~/.bashrc ]; then
+ . ~/.bashrc
+fi
|
jasonroelofs/dev
|
c8388cb0f8015f2c5fb0da8142b4c207ede6b5bf
|
Upgrade vim plugins
|
diff --git a/vim/bundle/powerline b/vim/bundle/powerline
index ca67970..364fc4d 160000
--- a/vim/bundle/powerline
+++ b/vim/bundle/powerline
@@ -1 +1 @@
-Subproject commit ca6797055a728bb043d0ac46a849949d8efd72ff
+Subproject commit 364fc4dcd95352c57177b578643056e40709d9aa
diff --git a/vim/bundle/syntastic b/vim/bundle/syntastic
index 5214f00..710a854 160000
--- a/vim/bundle/syntastic
+++ b/vim/bundle/syntastic
@@ -1 +1 @@
-Subproject commit 5214f00a17a389ee2c285610f5b367341a77ce21
+Subproject commit 710a854f6a6832004b225c25d5c076bb537fd589
diff --git a/vim/bundle/vim-rails b/vim/bundle/vim-rails
index 6d21bd0..981f8d7 160000
--- a/vim/bundle/vim-rails
+++ b/vim/bundle/vim-rails
@@ -1 +1 @@
-Subproject commit 6d21bd0d90ab4b27581cbe834397f503ea115565
+Subproject commit 981f8d790cbecd5bbbb907aa30a94f63b6aee041
diff --git a/vim/bundle/vim-ruby b/vim/bundle/vim-ruby
index 01657cc..c298d2f 160000
--- a/vim/bundle/vim-ruby
+++ b/vim/bundle/vim-ruby
@@ -1 +1 @@
-Subproject commit 01657cc9d9fc93590104af0f5aaa6897caa4af11
+Subproject commit c298d2f352559f0c690d5e75f7ed6ce0c61ff474
diff --git a/vim/bundle/vim-surround b/vim/bundle/vim-surround
index ec579a5..772ab95 160000
--- a/vim/bundle/vim-surround
+++ b/vim/bundle/vim-surround
@@ -1 +1 @@
-Subproject commit ec579a50478758ee6cebe265cf536f9a2f6c4e34
+Subproject commit 772ab9587b7d1e2c3bae75395c9123803059ba8a
|
jasonroelofs/dev
|
b7af7aa7b392ee630f679dafdf5a6be69081f850
|
Switch from Command-T to CtrlP with Ag support
|
diff --git a/.gitmodules b/.gitmodules
index eaafbc2..0f52753 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -1,36 +1,33 @@
[submodule "vim/bundle/pathogen"]
path = vim/bundle/pathogen
url = git://github.com/tpope/vim-pathogen
[submodule "vim/bundle/nerdtree"]
path = vim/bundle/nerdtree
url = git://github.com/scrooloose/nerdtree
[submodule "vim/bundle/solarized"]
path = vim/bundle/solarized
url = git://github.com/altercation/vim-colors-solarized.git
[submodule "vim/bundle/powerline"]
path = vim/bundle/powerline
url = git://github.com/skwp/vim-powerline
[submodule "vim/bundle/endwise"]
path = vim/bundle/endwise
url = git://github.com/tpope/vim-endwise.git
[submodule "vim/bundle/supertab"]
path = vim/bundle/supertab
url = git://github.com/ervandew/supertab.git
[submodule "vim/bundle/syntastic"]
path = vim/bundle/syntastic
url = git://github.com/ervandew/supertab.git
[submodule "vim/bundle/ruby"]
path = vim/bundle/ruby
url = git://github.com/vim-ruby/vim-ruby.git
[submodule "vim/bundle/rails"]
path = vim/bundle/rails
url = git://github.com/tpope/vim-rails.git
-[submodule "vim/bundle/commandT"]
- path = vim/bundle/commandT
- url = git://github.com/wincent/Command-T
[submodule "vim/bundle/vim-coffee-script"]
path = vim/bundle/vim-coffee-script
url = git://github.com/kchmck/vim-coffee-script.git
[submodule "vim/bundle/golang"]
path = vim/bundle/golang
url = git://github.com/jnwhiteh/vim-golang.git
diff --git a/gvimrc b/gvimrc
index 17024c7..b0558d3 100644
--- a/gvimrc
+++ b/gvimrc
@@ -1,48 +1,51 @@
"""""""""""""""""""""""""""
""" Gvim Global Configs """
"""""""""""""""""""""""""""
command -nargs=0 Zoom :macaction performZoom:
" Setup the font (Bitstream on Linux, Lucida on Windows)
:set guifont=Monaco:h16.00,Bitstream\ Vera\ Sans\ Mono\ 11,\ Lucida_Sans_Typewriter:h8:cANSI
" Set all gui options
" Options can be set or unset with
" :set guioptions+=(options)
" :set guioptions-=(options)
" Options
" r - right scrollbar
" l - left scrollbar
" b - bottom scrollbar
" m - menu bar
" t - tools bar
" e - Macvim native tabs
"Disable all options, scrollbars give funky business in full screen
:set guioptions=e
:cabbr toff set guioptions-=T
:cabbr ton set guioptions+=T
:cabbr moff set guioptions-=m
:cabbr mon set guioptions+=m
" Maximize both dimensions when going fullscreen
:set fuopt=maxhorz,maxvert
:highlight Normal guifg=white guibg=black
-if has("gui_macvim")
- macmenu &File.Print key=<nop>
- nmap <D-p> :CommandT<CR>
- nmap <D-P> :CommandTBuffer<CR>
-endif
-
"""""""""""""""""""""""""""""
""" Plugin Initialization """
"""""""""""""""""""""""""""""
+""" CtrlP """
+
+" I want Command+p!
+if has("gui_macvim")
+ macmenu &File.Print key=<nop>
+ nmap <D-p> :CtrlP<CR>
+ nmap <D-P> :CtrlPBuffer<CR>
+endif
+
""" SweeterVest """
" Ensure dispatch is always turned on if we're in MacVim
let g:use_dispatch=1
diff --git a/vim/bundle/Command-T b/vim/bundle/Command-T
deleted file mode 160000
index 13760a7..0000000
--- a/vim/bundle/Command-T
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 13760a725779b65fa0f2ebef51806f3c05a52550
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 86c0352..b93cc0b 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,31 +1,32 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
-Plugin 'wincent/Command-T'
+Plugin 'rking/ag.vim'
+Plugin 'kien/ctrlp.vim'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
Plugin 'emilford/vim-sweeter-vest'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
" Languages / Syntax
Plugin 'scrooloose/Syntastic'
Plugin 'fatih/vim-go'
Plugin 'vim-ruby/vim-ruby'
Plugin 'kchmck/vim-coffee-script'
Plugin 'beyondmarc/glsl.vim'
Plugin 'othree/html5.vim'
Plugin 'wting/rust.vim'
Plugin 'cespare/vim-toml'
Plugin 'slim-template/vim-slim'
call vundle#end()
diff --git a/vimrc b/vimrc
index a2385f5..82e15a0 100644
--- a/vimrc
+++ b/vimrc
@@ -1,147 +1,152 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
" Custom File types handling
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
-""" CommandT """
-" Keybindings configured in gvimrc
-let g:CommandTMaxHeight=20
-let g:CommandTMatchWindowAtTop=1
+""" Ag """
+set grepprg=ag\ --nogroup\ --nocolor
+
+""" Ctrl-P """
+let g:ctrlp_working_path_mode = 0
+let g:ctrlp_show_hidden = 1
+let g:ctrlp_user_command = 'ag %s -l --nocolor -g ""'
+let g:ctrlp_use_caching = 0
+let g:ctrlp_match_window = 'top,order:ttb'
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Sweeter Vest """
let g:clear_each_run=1
let g:sweeter_vest_skip_mappings=1
nnoremap <F5> :SweeterVestRunFile<cr>
nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
0f2d3cd6e271b1562a701656d20892c70bf8ee8e
|
Don't syntasic sass/scss files
|
diff --git a/vimrc b/vimrc
index 008b3c8..a2385f5 100644
--- a/vimrc
+++ b/vimrc
@@ -1,147 +1,147 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
" Custom File types handling
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" CommandT """
" Keybindings configured in gvimrc
let g:CommandTMaxHeight=20
let g:CommandTMatchWindowAtTop=1
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Syntastic """
set statusline+=%#warningmsg#
set statusline+=%{SyntasticStatuslineFlag()}
set statusline+=%*
-let g:syntastic_auto_loc_list = 1
+let g:syntastic_auto_loc_list = 0
let g:syntastic_check_on_wq = 0
" Disable automatic checking on :w for some filetypes that are
" just annoyingly slow to run.
-let g:syntastic_mode_map = { "passive_filetypes": ["slim"] }
+let g:syntastic_mode_map = { "passive_filetypes": ["slim", "sass", "scss"] }
""" Sweeter Vest """
let g:clear_each_run=1
let g:sweeter_vest_skip_mappings=1
nnoremap <F5> :SweeterVestRunFile<cr>
nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
27b537e642c4ff2ac61d20922a63d28b4da8f636
|
Set up Synastic to ignore slim files, and some other options
|
diff --git a/vimrc b/vimrc
index 944ef86..008b3c8 100644
--- a/vimrc
+++ b/vimrc
@@ -1,131 +1,147 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
" Custom File types handling
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" CommandT """
" Keybindings configured in gvimrc
let g:CommandTMaxHeight=20
let g:CommandTMatchWindowAtTop=1
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
-""" Omnisharp """
-let g:Omnisharp_stop_server=0
+""" Syntastic """
+set statusline+=%#warningmsg#
+set statusline+=%{SyntasticStatuslineFlag()}
+set statusline+=%*
+
+let g:syntastic_auto_loc_list = 1
+let g:syntastic_check_on_wq = 0
+
+" Disable automatic checking on :w for some filetypes that are
+" just annoyingly slow to run.
+let g:syntastic_mode_map = { "passive_filetypes": ["slim"] }
+
+""" Sweeter Vest """
+let g:clear_each_run=1
+let g:sweeter_vest_skip_mappings=1
+
+nnoremap <F5> :SweeterVestRunFile<cr>
+nnoremap <F6> :SweeterVestRunTest<cr>
|
jasonroelofs/dev
|
0a31bb4bc6d1d87b3e842ca1deb49e815fe359fb
|
Re-install SweeterVest and dispatch to Terminal
|
diff --git a/gvimrc b/gvimrc
index 85c6aa7..17024c7 100644
--- a/gvimrc
+++ b/gvimrc
@@ -1,39 +1,48 @@
"""""""""""""""""""""""""""
""" Gvim Global Configs """
"""""""""""""""""""""""""""
command -nargs=0 Zoom :macaction performZoom:
" Setup the font (Bitstream on Linux, Lucida on Windows)
:set guifont=Monaco:h16.00,Bitstream\ Vera\ Sans\ Mono\ 11,\ Lucida_Sans_Typewriter:h8:cANSI
" Set all gui options
" Options can be set or unset with
" :set guioptions+=(options)
" :set guioptions-=(options)
" Options
" r - right scrollbar
" l - left scrollbar
" b - bottom scrollbar
" m - menu bar
" t - tools bar
" e - Macvim native tabs
"Disable all options, scrollbars give funky business in full screen
:set guioptions=e
:cabbr toff set guioptions-=T
:cabbr ton set guioptions+=T
:cabbr moff set guioptions-=m
:cabbr mon set guioptions+=m
" Maximize both dimensions when going fullscreen
:set fuopt=maxhorz,maxvert
:highlight Normal guifg=white guibg=black
if has("gui_macvim")
macmenu &File.Print key=<nop>
nmap <D-p> :CommandT<CR>
nmap <D-P> :CommandTBuffer<CR>
endif
+
+"""""""""""""""""""""""""""""
+""" Plugin Initialization """
+"""""""""""""""""""""""""""""
+
+""" SweeterVest """
+
+" Ensure dispatch is always turned on if we're in MacVim
+let g:use_dispatch=1
diff --git a/vim/bundles.vim b/vim/bundles.vim
index fc8de61..86c0352 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,30 +1,31 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'wincent/Command-T'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
+Plugin 'emilford/vim-sweeter-vest'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
" Languages / Syntax
Plugin 'scrooloose/Syntastic'
Plugin 'fatih/vim-go'
Plugin 'vim-ruby/vim-ruby'
Plugin 'kchmck/vim-coffee-script'
Plugin 'beyondmarc/glsl.vim'
Plugin 'othree/html5.vim'
Plugin 'wting/rust.vim'
Plugin 'cespare/vim-toml'
Plugin 'slim-template/vim-slim'
call vundle#end()
|
jasonroelofs/dev
|
377e1c46c77fa0763b06b6b9da02202b5ef03ba2
|
Always ignore local .ruby-version files by default
|
diff --git a/gitignore b/gitignore
index 59891a3..87af1d6 100644
--- a/gitignore
+++ b/gitignore
@@ -1,8 +1,9 @@
.DS_Store
.rvmrc
*.rbc
.*.swp
proto
.powrc
.powenv
.foreman
+.ruby-version
|
jasonroelofs/dev
|
b8cf69a6085d723aa7659511bd0103ffacc05a81
|
Fix whitelist to use proper names of filetypes
|
diff --git a/vimrc b/vimrc
index 06a0ffe..139ea02 100644
--- a/vimrc
+++ b/vimrc
@@ -1,141 +1,141 @@
"""""""""""""""""""""""""""
""" Vim Global Configs """
"""""""""""""""""""""""""""
set nocompatible
set encoding=utf-8
set title
set hidden
filetype off
source ~/.vim/bundles.vim
filetype plugin indent on
let mapleader=","
" Share system clipboard
set clipboard=unnamed
" Look and Feel
syntax on
colorscheme koehler
set background=dark
set ruler
" Turn off error / visual bell
set noerrorbells
set visualbell t_vb=
set history=200
set undolevels=1000
set fileformats=unix,dos,mac
" Search settings
set nohlsearch
set incsearch
set ignorecase
set smartcase
" Tabbing and indenting
set autoindent smartindent
set smarttab
set expandtab
set tabstop=2
set shiftwidth=2
set shiftround
set copyindent
set preserveindent
" Command Tab completion
set wildmenu
set wildmode=list:longest
set backspace=2
set showmatch
" Highlight extraneous whitespace
highlight ExtraWhitespace ctermbg=red guibg=red
au ColorScheme * highlight ExtraWhitespace guibg=red
au BufEnter * match ExtraWhitespace /\s\+$/
au InsertEnter * match ExtraWhitespace /\s\+\%#\@<!$/
au InsertLeave * match ExtraWhiteSpace /\s\+$/
" Custom File types handling
au BufRead,BufNewFile {Gemfile,Rakefile,Vagrantfile,config.ru,*.rake} set ft=ruby
au BufNewFile,BufRead *.json set ft=javascript
"""""""""""""""""""""""""""
""" Global key mappings """
"""""""""""""""""""""""""""
noremap ; :
noremap j gj
noremap k gk
" Typo fixits
:cabbr W w
:cabbr Q q
" Clear out all extra whitespace in a file
:map <leader>s :%s/\s\+$//<CR>
" Format entire buffer with indents
:map <leader>i mzggvG='z
:map \ft :retab<CR>
" Ctrl-h/j/k/l for easy window movement
map <C-h> <C-w>h
map <C-j> <C-w>j
map <C-k> <C-w>k
map <C-l> <C-w>l
" Buffer management
noremap :bn
noremap :bp
noremap :bd
" Make ',e' (in normal mode) give a prompt for opening files
" in the same dir as the current buffer's file.
if has("unix")
map <leader>e :e <C-R>=expand("%:p:h") . "/" <CR>
else
map <leader>e :e <C-R>=expand("%:p:h") . "\\" <CR>
endif
" Command for running `par` to format blocks of text
map <leader>f {!}par w80qrg<cr>
""""""""""""""""""""""""""""
""" File Type Assoc """
""""""""""""""""""""""""""""
au BufNewFile,BufRead *.md set filetype=markdown
au BufNewFile,BufRead *.vp,*.fp,*.gp,*.vs,*.fs,*.gs,*.tcs,*.tes,*.cs,*.vert,*.frag,*.geom,*.tess,*.shd,*.gls,*.glsl set filetype=glsl330
""""""""""""""""""""""""""""
""" Plugin Configuration """
""""""""""""""""""""""""""""
""" CommandT """
" Keybindings configured in gvimrc
let g:CommandTMaxHeight=20
let g:CommandTMatchWindowAtTop=1
""" Powerline """
let g:Powerline_symbols='fancy'
let g:Powerline_themer='skwp'
let g:Powerline_colorscheme='skwp'
""" Omnisharp """
let g:Omnisharp_stop_server=0
""" Sweeter Vest """
let g:clear_each_run = 1
" Run the current file with F5
noremap <F5> :SweeterVestRunFile<CR>
noremap <F6> :SweeterVestRunContext<CR>
""" YouCompleteMe """
-let g:ycm_filetype_whitelist = { 'cpp': 1, 'c': 1, 'rb': 1, 'go': 1, 'rs': 1, 'js': 1, 'coffee': 1 }
+let g:ycm_filetype_whitelist = { 'cpp': 1, 'c': 1, 'ruby': 1, 'go': 1, 'rust': 1, 'javascript': 1, 'coffee': 1 }
|
jasonroelofs/dev
|
9e1f555c5ddbefbc5adc8741efdf1ed4dea1a545
|
Use homebrew installed vim
|
diff --git a/gitconfig b/gitconfig
index d3efa3f..80402f2 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,48 +1,48 @@
[user]
name = Jason Roelofs
email = [email protected]
[color]
diff = auto
status = auto
branch = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
[alias]
st = status
ci = commit
co = checkout
dif = diff
cp = cherry-pick
unpushed = rev-list HEAD --pretty ^origin/master
lg = log --graph --pretty=format:'%Cred%h%Creset - %Cblue[%an]%Creset%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
pullr = pull --rebase
initial-commit = commit --allow-empty -m 'Initial Commit'
[merge]
tool = mvim
[mergetool "mvim"]
cmd = mvim -d -g $LOCAL $MERGED $REMOTE
keepbackup = false
[repack]
usedeltabaseoffset = true
[core]
- editor = /usr/bin/vim
+ editor = /usr/local/bin/vim
pager = "less -FRX"
excludesfile = /Users/roelofs/.gitignore
[push]
default = simple
[branch]
autosetupmerge = true
autosetuprebase = always
[credential]
helper = osxkeychain
|
jasonroelofs/dev
|
fb1cab8affd94e723582df4d26f16630439d807b
|
Switch golang vim bundles to the new hotness
|
diff --git a/vim/bundle/vim-golang b/vim/bundle/vim-golang
deleted file mode 160000
index e6d0c6a..0000000
--- a/vim/bundle/vim-golang
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit e6d0c6a72a66af2674b96233c4747661e0f47a8c
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 841088e..754f90b 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,32 +1,32 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'wincent/Command-T'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
" Misc
Plugin 'emilford/vim-sweeter-vest'
" Languages / Syntax
Plugin 'Syntastic'
-Plugin 'jnwhiteh/vim-golang'
+Plugin 'fatih/vim-go'
Plugin 'vim-ruby/vim-ruby'
Plugin 'kchmck/vim-coffee-script'
Plugin 'beyondmarc/glsl.vim'
Plugin 'othree/html5.vim'
Plugin 'wting/rust.vim'
Plugin 'cespare/vim-toml'
call vundle#end()
|
jasonroelofs/dev
|
dc5a5e7b8fb98e157847cb20c3b6985389842358
|
Remove some unused plugins
|
diff --git a/vim/bundle/bats.vim b/vim/bundle/bats.vim
deleted file mode 160000
index 3e64c95..0000000
--- a/vim/bundle/bats.vim
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 3e64c95d7a55feb33492717d101c9eb92a8d0a9a
diff --git a/vim/bundle/splitjoin.vim b/vim/bundle/splitjoin.vim
deleted file mode 160000
index 720e0a1..0000000
--- a/vim/bundle/splitjoin.vim
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 720e0a1a6ad4708f719ecb9058b80e5d7e330951
diff --git a/vim/bundle/vim-fugitive b/vim/bundle/vim-fugitive
deleted file mode 160000
index 0374322..0000000
--- a/vim/bundle/vim-fugitive
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 0374322ba5d85ae44dd9dc44ef31ca015a59097e
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 86df103..841088e 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,35 +1,32 @@
filetype off
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
Plugin 'gmarik/Vundle.vim'
" Vim improvements
Plugin 'wincent/Command-T'
Plugin 'Lokaltog/powerline'
Plugin 'ervandew/supertab'
Plugin 'altercation/vim-colors-solarized'
-Plugin 'AndrewRadev/splitjoin.vim'
" tpope
Plugin 'tpope/vim-endwise'
Plugin 'tpope/vim-rails'
-Plugin 'tpope/vim-fugitive'
Plugin 'tpope/vim-surround'
Plugin 'tpope/vim-dispatch'
+" Misc
Plugin 'emilford/vim-sweeter-vest'
" Languages / Syntax
Plugin 'Syntastic'
Plugin 'jnwhiteh/vim-golang'
Plugin 'vim-ruby/vim-ruby'
Plugin 'kchmck/vim-coffee-script'
Plugin 'beyondmarc/glsl.vim'
-Plugin 'rosstimson/bats.vim'
Plugin 'othree/html5.vim'
Plugin 'wting/rust.vim'
-Plugin 'nosami/Omnisharp'
Plugin 'cespare/vim-toml'
call vundle#end()
|
jasonroelofs/dev
|
434d22ecbe99a0930df0a00e8f10d487266fa81c
|
Initial Rust configs
|
diff --git a/vim/ftplugin/rust.vim b/vim/ftplugin/rust.vim
new file mode 100644
index 0000000..e36a332
--- /dev/null
+++ b/vim/ftplugin/rust.vim
@@ -0,0 +1 @@
+setlocal tabstop=4 shiftwidth=4 softtabstop=4 expandtab
|
jasonroelofs/dev
|
0bed25fdd9416cf5841267eab6533ad3505863b0
|
Use othree/html5
|
diff --git a/vim/bundles.vim b/vim/bundles.vim
index c16c836..ee94735 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,24 +1,25 @@
filetype off
Bundle "gmarik/vundle"
" Vim improvements
Bundle "wincent/Command-T"
Bundle "Lokaltog/powerline"
Bundle "ervandew/supertab"
Bundle "altercation/vim-colors-solarized"
Bundle "AndrewRadev/splitjoin.vim"
" tpope
Bundle "tpope/vim-endwise"
Bundle "tpope/vim-rails"
Bundle "tpope/vim-fugitive"
Bundle "tpope/vim-surround"
" Languages / Syntax
Bundle "Syntastic"
Bundle "jnwhiteh/vim-golang"
Bundle "vim-ruby/vim-ruby"
Bundle "kchmck/vim-coffee-script"
Bundle "beyondmarc/glsl.vim"
Bundle "rosstimson/bats.vim"
+Bundle "othree/html5.vim"
|
jasonroelofs/dev
|
f9393fcd5860d24625f97103194b3da3de9607c0
|
Add git alias for easily making empty initial commit
|
diff --git a/gitconfig b/gitconfig
index c377410..af283d7 100644
--- a/gitconfig
+++ b/gitconfig
@@ -1,46 +1,47 @@
[user]
name = Jason Roelofs
email = [email protected]
[color]
diff = auto
status = auto
branch = auto
[color "branch"]
current = yellow reverse
local = yellow
remote = green
[color "diff"]
meta = yellow bold
frag = magenta bold
old = red bold
new = green bold
[color "status"]
added = yellow
changed = green
untracked = cyan
[alias]
st = status
ci = commit
co = checkout
dif = diff
cp = cherry-pick
unpushed = rev-list HEAD --pretty ^origin/master
lg = log --graph --pretty=format:'%Cred%h%Creset - %Cblue[%an]%Creset%C(yellow)%d%Creset %s %Cgreen(%cr)%Creset' --abbrev-commit --date=relative
pullr = pull --rebase
+ initial-commit = commit --allow-empty -m 'Initial Commit'
[merge]
ff = only
tool = mvim
[mergetool "mvim"]
cmd = mvim -d -g $LOCAL $MERGED $REMOTE
keepbackup = false
[repack]
usedeltabaseoffset = true
[core]
editor = /usr/bin/vim
pager = "less -FRSX"
excludesfile = /Users/roelofs/.gitignore
[push]
default = tracking
[branch]
autosetupmerge = true
autosetuprebase = always
|
jasonroelofs/dev
|
f1060680c52aac65b3b1888288c07afdba987d36
|
Add bats.vim for highlighting bats files
|
diff --git a/vim/bundle/bats.vim b/vim/bundle/bats.vim
new file mode 160000
index 0000000..3e64c95
--- /dev/null
+++ b/vim/bundle/bats.vim
@@ -0,0 +1 @@
+Subproject commit 3e64c95d7a55feb33492717d101c9eb92a8d0a9a
diff --git a/vim/bundles.vim b/vim/bundles.vim
index 27ba73f..c16c836 100644
--- a/vim/bundles.vim
+++ b/vim/bundles.vim
@@ -1,23 +1,24 @@
filetype off
Bundle "gmarik/vundle"
" Vim improvements
Bundle "wincent/Command-T"
Bundle "Lokaltog/powerline"
Bundle "ervandew/supertab"
Bundle "altercation/vim-colors-solarized"
Bundle "AndrewRadev/splitjoin.vim"
" tpope
Bundle "tpope/vim-endwise"
Bundle "tpope/vim-rails"
Bundle "tpope/vim-fugitive"
Bundle "tpope/vim-surround"
" Languages / Syntax
Bundle "Syntastic"
Bundle "jnwhiteh/vim-golang"
Bundle "vim-ruby/vim-ruby"
Bundle "kchmck/vim-coffee-script"
Bundle "beyondmarc/glsl.vim"
+Bundle "rosstimson/bats.vim"
|
aliawais-tkxel/Test-App
|
e66419fb81b92b8a3413f3eda39c6e08b74e98ea
|
First Readme
|
diff --git a/README.rtf b/README.rtf
new file mode 100644
index 0000000..308dd4d
--- /dev/null
+++ b/README.rtf
@@ -0,0 +1,7 @@
+{\rtf1\ansi\ansicpg1252\cocoartf1038\cocoasubrtf290
+{\fonttbl\f0\fswiss\fcharset0 Helvetica;}
+{\colortbl;\red255\green255\blue255;}
+\paperw11900\paperh16840\margl1440\margr1440\vieww9000\viewh8400\viewkind0
+\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\ql\qnatural\pardirnatural
+
+\f0\fs24 \cf0 My Readme.}
\ No newline at end of file
|
kurtchen/hk_macau
|
63f2206765d9a1b9b833f378d9b96988c2c2cae2
|
bug fix, set size when load GMap, opera can't use div size for GMap
|
diff --git a/js/main.js b/js/main.js
index bccd8ea..ff311fb 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,355 +1,355 @@
$(document).ready(function(){
// Load Google Map
loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
// Get the spots and update the slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
curGroup = this.id.substr(this.id.lastIndexOf("_")+1);
$.getJSON("json/group"+curGroup+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
curGroup = 1;
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
var spotHtml = '<div class="Panel" id="panel_';
spotHtml += (entryIdx+1);
spotHtml += '"><div class="inside"><img src="';
spotHtml += entry['image_url'];
spotHtml += '" alt="';
spotHtml += entry['description'];
spotHtml += '" /><span>';
spotHtml += entry['name'];
spotHtml += '</span></div></div>';
//alert(spotHtml);
$('.ScrollContainer').append(spotHtml);
// Set Lat & Lng info
$("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
$("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
$("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
//console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
//console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
//console.debug("==>"+$(".ScrollContainer").css("left"));
if($("#slider").data("currentlyMoving")==true)
{
$("#slider").data("currentlyMoving", false);
//console.debug("Calling moveMap after animation");
moveMap();
}
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
- map = new GMap2(document.getElementById("hk_map"));
+ map = new GMap2(document.getElementById("hk_map"), {size:new GSize(800,430)});
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
//console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
zoom = parseInt(zoom);
map.setZoom(zoom);
//map.panTo(new GLatLng(lat,lng));
map.setCenter(new GLatLng(lat,lng));
// Show Marker and the Info window
showMarkerAndInfo(lat,lng, zoom);
}
return true;
}
/*
Show Maker on the map and show the info window.
*/
function showMarkerAndInfo(lat, lng, zoom){
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
map.closeInfoWindow();
var marker = markermanager.getMarker(lat,lng, zoom);
markermanager.removeMarker(marker);
markermanager.addMarker(marker,zoom);
//console.debug(markermanager.getMarkerCount(zoom));
markermanager.refresh();
var $curPanelImg = $("#panel_"+curPanel+" img");
// Set the click event for the marker
//GEvent.addListener(marker, "click", function(){
// marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//});
marker.bindInfoWindowHtml("<div style=\"font-size:11px;height:120px;width:180px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
//console.debug($curPanelImg.attr("src"));
//marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//GEvent.trigger(marker, "click");
setTimeout(function(){GEvent.trigger(marker, "click");},1000);
return true;
}
/*
Get the photos when the img in infowindow is clicked.
*/
function getPhotos(group, spot){
//console.debug("Enter getPhotos");
// Show waiting notice
//$("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
//console.debug("Get the photos");
//console.debug('json/photos_'+group+'_'+spot+'.json');
// Get the photos
$.getJSON('json/photos_'+group+'_'+spot+'.json', showLightBox);
}
/*
Show light box for the photos.
*/
function showLightBox(data){
//console.debug("Enter showLightBox");
//$("#notice").empty().css("display","none");
// Remove the previous photos
$("#gallery").empty();
// Add the photos
$.each(data, function(entryIdx, entry){
var galleryHtml = "<a href=\"";
galleryHtml+=entry['photo_big'];
galleryHtml+="\" title=\"";
galleryHtml+= entry['title'];
galleryHtml+="\"><img src=\"";
galleryHtml+=entry['photo_small'];
galleryHtml+="\" width=\"72\" height=\"72\" alt=\"\" /></a>";
//console.debug(""+galleryHtml);
$("#gallery").append(galleryHtml);
});
// Trigger the light box
$('#gallery a').lightBox({txtImage:'å¾ç',txtOf:'/'});
$("#gallery a:eq(0)").trigger("click");
}
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
var curGroup = 0;
// The map
var map;
var markermanager;
|
kurtchen/hk_macau
|
d301fa2d96305bd692c9c22736cf2d01880ef677
|
bug fix:add width for info window;move gallery to bottom;remove notice area.
|
diff --git a/index.html b/index.html
index d5f826f..6df9cf2 100644
--- a/index.html
+++ b/index.html
@@ -1,156 +1,139 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HongKong & Macau in 5 Days</title>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
<script src="js/markermanager.js" type="text/javascript"></script>
<script src="js/main.js" type="text/javascript"></script>
<script src="js/jquery.lightbox-0.5.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="css/main.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.lightbox-0.5.css" media="screen" />
</head>
<body>
- <div id="notice"></div>
- <center>
- <div id="gallery">
-<!-- <ul>
- <li>
- <a href="photos/image1.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery').lightBox();">
- <img src="photos/thumb_image1.jpg" width="72" height="72" alt="" />
- </a>
- </li>
- <li>
- <a href="photos/image2.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
- <img src="photos/thumb_image2.jpg" width="72" height="72" alt="" />
- </a>
- </li>
- <li>
- <a href="photos/image3.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
- <img src="photos/thumb_image3.jpg" width="72" height="72" alt="" />
- </a>
- </li>
- <li>
- <a href="photos/image4.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
- <img src="photos/thumb_image4.jpg" width="72" height="72" alt="" />
- </a>
- </li>
- <li>
- <a href="photos/image5.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
- <img src="photos/thumb_image5.jpg" width="72" height="72" alt="" />
- </a>
- </li>
- </ul>-->
- </div>
+<!-- <div id="notice"></div>-->
+ <center>
<div class="TabsArea">
<div id="tab_menu" class="TabMenu">
<img src="img/loading.gif" width="220" height="19"/>
<!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
<span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
<span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
<span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
<span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
</div>
<!--############################Begine Slider###########################################-->
<div id="slider">
<img class="ScrollButtons left" src="img/leftarrow.png">
<div class="ScrollPanes">
<div class="ScrollContainer">
<!-- <img src="img/loading.gif" width="220" height="19"/> -->
<!--
<div class="Panel" id="panel_1">
<div class="inside">
<img src="img/slider/1.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_2">
<div class="inside">
<img src="img/slider/2.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_3">
<div class="inside">
<img src="img/slider/3.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_4">
<div class="inside">
<img src="img/slider/4.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_5">
<div class="inside">
<img src="img/slider/5.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
-->
</div>
<div id="left_shadow"></div>
<div id="right_shadow"></div>
</div>
<img class="ScrollButtons right" src="img/rightarrow.png">
</div>
<!--############################End Slider###########################################-->
</div>
<hr/>
<!--############################Begine Map###########################################-->
- <div id="hk_map">
-
- </div>
+ <div id="hk_map">
+
+ </div>
<!--############################End Map###########################################-->
<!--
<div>
<img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
<img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
<img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
<img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
<img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
</div>
-->
<!--############################Begine About###########################################-->
-<div id="about">
- <div id="about_album">
- <b>About this Album</b>
- <ul>
- <li>
- Powerd By: <a href="http://jquery.com/">jQuery</a>, <a href="http://code.google.com/apis/maps/">Google Map</a>, <a href="http://leandrovieira.com/projects/jquery/lightbox/">LightBox jQuery plugin</a>, <a href="http://css-tricks.com/moving-boxes/">Moving Boxes</a>.
- </li>
- <li>
- Most of the photos were taken during traveling in Hong Kong and Macau from 2009-09-18 to 2009-09-22. Some of the photos are from Internet.
- </li>
- <li>
- The source code can be fetched from <a href="http://github.com/kurtchen/hk_macau">github.com</a>
- </li>
- </ul>
- </div>
- <div id="about_me">
- <b>About Me</b>
- <ul>
- <li>
- Software Engineer in NanJing. <br/>Interested in Mobile & Web.
- </li>
- <li>
- Email: <br/><img src="img/gmail.png"/><img src="img/hotmail.png"/>
- </li>
- <li>
- Blog: <a href="http://chenguangming83.spaces.live.com/">http://chenguangming83.spaces.live.com/</a>
- </li>
- <li>
- Twitter: <a href="http://twitter.com/kurtchen">http://twitter.com/kurtchen</a>
- </li>
- </ul>
- </div>
-</div>
+ <div id="about">
+ <div id="about_album">
+ <b>About this Album</b>
+ <ul>
+ <li>
+ Powerd By: <a href="http://jquery.com/">jQuery</a>, <a href="http://code.google.com/apis/maps/">Google Map</a>, <a href="http://leandrovieira.com/projects/jquery/lightbox/">LightBox jQuery plugin</a>, <a href="http://css-tricks.com/moving-boxes/">Moving Boxes</a>.
+ </li>
+ <li>
+ Most of the photos were taken during traveling in Hong Kong and Macau from 2009-09-18 to 2009-09-22. Some of the photos are from Internet.
+ </li>
+ <li>
+ The source code can be fetched from <a href="http://github.com/kurtchen/hk_macau">github.com</a>
+ </li>
+ </ul>
+ </div>
+ <div id="about_me">
+ <b>About Me</b>
+ <ul>
+ <li>
+ Software Engineer in NanJing. <br/>Interested in Mobile & Web.
+ </li>
+ <li>
+ Email: <br/><img src="img/gmail.png"/><img src="img/hotmail.png"/>
+ </li>
+ <li>
+ Blog: <a href="http://chenguangming83.spaces.live.com/">http://chenguangming83.spaces.live.com/</a>
+ </li>
+ <li>
+ Twitter: <a href="http://twitter.com/kurtchen">http://twitter.com/kurtchen</a>
+ </li>
+ </ul>
+ </div>
+ </div>
<!--############################End About###########################################-->
</center>
+ <div id="gallery">
+<!-- <a href="photos/image1.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery').lightBox();">
+ <img src="photos/thumb_image1.jpg" width="72" height="72" alt="" />
+ </a>
+ <a href="photos/image2.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image2.jpg" width="72" height="72" alt="" />
+ </a>
+ <a href="photos/image3.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image3.jpg" width="72" height="72" alt="" />
+ </a>
+-->
+ </div>
</body>
</html>
diff --git a/js/main.js b/js/main.js
index 134d85b..bccd8ea 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,355 +1,355 @@
$(document).ready(function(){
// Load Google Map
loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
// Get the spots and update the slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
curGroup = this.id.substr(this.id.lastIndexOf("_")+1);
$.getJSON("json/group"+curGroup+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
curGroup = 1;
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
var spotHtml = '<div class="Panel" id="panel_';
spotHtml += (entryIdx+1);
spotHtml += '"><div class="inside"><img src="';
spotHtml += entry['image_url'];
spotHtml += '" alt="';
spotHtml += entry['description'];
spotHtml += '" /><span>';
spotHtml += entry['name'];
spotHtml += '</span></div></div>';
//alert(spotHtml);
$('.ScrollContainer').append(spotHtml);
// Set Lat & Lng info
$("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
$("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
$("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
//console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
//console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
//console.debug("==>"+$(".ScrollContainer").css("left"));
if($("#slider").data("currentlyMoving")==true)
{
$("#slider").data("currentlyMoving", false);
//console.debug("Calling moveMap after animation");
moveMap();
}
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
map = new GMap2(document.getElementById("hk_map"));
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
//console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
zoom = parseInt(zoom);
map.setZoom(zoom);
//map.panTo(new GLatLng(lat,lng));
map.setCenter(new GLatLng(lat,lng));
// Show Marker and the Info window
showMarkerAndInfo(lat,lng, zoom);
}
return true;
}
/*
Show Maker on the map and show the info window.
*/
function showMarkerAndInfo(lat, lng, zoom){
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
map.closeInfoWindow();
var marker = markermanager.getMarker(lat,lng, zoom);
markermanager.removeMarker(marker);
markermanager.addMarker(marker,zoom);
//console.debug(markermanager.getMarkerCount(zoom));
markermanager.refresh();
var $curPanelImg = $("#panel_"+curPanel+" img");
// Set the click event for the marker
//GEvent.addListener(marker, "click", function(){
// marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//});
- marker.bindInfoWindowHtml("<div style=\"font-size:11px;height:120px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
+ marker.bindInfoWindowHtml("<div style=\"font-size:11px;height:120px;width:180px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
//console.debug($curPanelImg.attr("src"));
//marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//GEvent.trigger(marker, "click");
setTimeout(function(){GEvent.trigger(marker, "click");},1000);
return true;
}
/*
Get the photos when the img in infowindow is clicked.
*/
function getPhotos(group, spot){
//console.debug("Enter getPhotos");
// Show waiting notice
//$("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
//console.debug("Get the photos");
//console.debug('json/photos_'+group+'_'+spot+'.json');
// Get the photos
$.getJSON('json/photos_'+group+'_'+spot+'.json', showLightBox);
}
/*
Show light box for the photos.
*/
function showLightBox(data){
//console.debug("Enter showLightBox");
//$("#notice").empty().css("display","none");
// Remove the previous photos
$("#gallery").empty();
// Add the photos
$.each(data, function(entryIdx, entry){
var galleryHtml = "<a href=\"";
galleryHtml+=entry['photo_big'];
galleryHtml+="\" title=\"";
galleryHtml+= entry['title'];
galleryHtml+="\"><img src=\"";
galleryHtml+=entry['photo_small'];
galleryHtml+="\" width=\"72\" height=\"72\" alt=\"\" /></a>";
//console.debug(""+galleryHtml);
$("#gallery").append(galleryHtml);
});
// Trigger the light box
$('#gallery a').lightBox({txtImage:'å¾ç',txtOf:'/'});
$("#gallery a:eq(0)").trigger("click");
}
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
var curGroup = 0;
// The map
var map;
var markermanager;
|
kurtchen/hk_macau
|
4e266f5e1a402ee1df6101ed945912fce08a07ed
|
Set the size of the info window to adapt to the image.
|
diff --git a/js/main.js b/js/main.js
index 3346bc0..134d85b 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,355 +1,355 @@
$(document).ready(function(){
// Load Google Map
loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
// Get the spots and update the slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
curGroup = this.id.substr(this.id.lastIndexOf("_")+1);
$.getJSON("json/group"+curGroup+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
curGroup = 1;
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
var spotHtml = '<div class="Panel" id="panel_';
spotHtml += (entryIdx+1);
spotHtml += '"><div class="inside"><img src="';
spotHtml += entry['image_url'];
spotHtml += '" alt="';
spotHtml += entry['description'];
spotHtml += '" /><span>';
spotHtml += entry['name'];
spotHtml += '</span></div></div>';
//alert(spotHtml);
$('.ScrollContainer').append(spotHtml);
// Set Lat & Lng info
$("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
$("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
$("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
//console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
//console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
//console.debug("==>"+$(".ScrollContainer").css("left"));
if($("#slider").data("currentlyMoving")==true)
{
$("#slider").data("currentlyMoving", false);
//console.debug("Calling moveMap after animation");
moveMap();
}
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
map = new GMap2(document.getElementById("hk_map"));
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
//console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
zoom = parseInt(zoom);
map.setZoom(zoom);
//map.panTo(new GLatLng(lat,lng));
map.setCenter(new GLatLng(lat,lng));
// Show Marker and the Info window
showMarkerAndInfo(lat,lng, zoom);
}
return true;
}
/*
Show Maker on the map and show the info window.
*/
function showMarkerAndInfo(lat, lng, zoom){
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
map.closeInfoWindow();
var marker = markermanager.getMarker(lat,lng, zoom);
markermanager.removeMarker(marker);
markermanager.addMarker(marker,zoom);
//console.debug(markermanager.getMarkerCount(zoom));
markermanager.refresh();
var $curPanelImg = $("#panel_"+curPanel+" img");
// Set the click event for the marker
//GEvent.addListener(marker, "click", function(){
// marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//});
- marker.bindInfoWindowHtml("<div style=\"font-size:11px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
+ marker.bindInfoWindowHtml("<div style=\"font-size:11px;height:120px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
//console.debug($curPanelImg.attr("src"));
//marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//GEvent.trigger(marker, "click");
setTimeout(function(){GEvent.trigger(marker, "click");},1000);
return true;
}
/*
Get the photos when the img in infowindow is clicked.
*/
function getPhotos(group, spot){
//console.debug("Enter getPhotos");
// Show waiting notice
//$("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
//console.debug("Get the photos");
//console.debug('json/photos_'+group+'_'+spot+'.json');
// Get the photos
$.getJSON('json/photos_'+group+'_'+spot+'.json', showLightBox);
}
/*
Show light box for the photos.
*/
function showLightBox(data){
//console.debug("Enter showLightBox");
//$("#notice").empty().css("display","none");
// Remove the previous photos
$("#gallery").empty();
// Add the photos
$.each(data, function(entryIdx, entry){
var galleryHtml = "<a href=\"";
galleryHtml+=entry['photo_big'];
galleryHtml+="\" title=\"";
galleryHtml+= entry['title'];
galleryHtml+="\"><img src=\"";
galleryHtml+=entry['photo_small'];
galleryHtml+="\" width=\"72\" height=\"72\" alt=\"\" /></a>";
//console.debug(""+galleryHtml);
$("#gallery").append(galleryHtml);
});
// Trigger the light box
$('#gallery a').lightBox({txtImage:'å¾ç',txtOf:'/'});
$("#gallery a:eq(0)").trigger("click");
}
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
var curGroup = 0;
// The map
var map;
-var markermanager;
\ No newline at end of file
+var markermanager;
|
kurtchen/hk_macau
|
0d5804599c7dfb671c7c88468cdf559a0b0e2fb4
|
bug fix: remove notice area, can't work in IE and Opera.
|
diff --git a/js/main.js b/js/main.js
index 6c18f57..3346bc0 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,355 +1,355 @@
$(document).ready(function(){
// Load Google Map
loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
// Get the spots and update the slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
curGroup = this.id.substr(this.id.lastIndexOf("_")+1);
$.getJSON("json/group"+curGroup+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
curGroup = 1;
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
var spotHtml = '<div class="Panel" id="panel_';
spotHtml += (entryIdx+1);
spotHtml += '"><div class="inside"><img src="';
spotHtml += entry['image_url'];
spotHtml += '" alt="';
spotHtml += entry['description'];
spotHtml += '" /><span>';
spotHtml += entry['name'];
spotHtml += '</span></div></div>';
//alert(spotHtml);
$('.ScrollContainer').append(spotHtml);
// Set Lat & Lng info
$("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
$("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
$("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
//console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
//console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
//console.debug("==>"+$(".ScrollContainer").css("left"));
if($("#slider").data("currentlyMoving")==true)
{
$("#slider").data("currentlyMoving", false);
//console.debug("Calling moveMap after animation");
moveMap();
}
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
map = new GMap2(document.getElementById("hk_map"));
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
//console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
zoom = parseInt(zoom);
map.setZoom(zoom);
//map.panTo(new GLatLng(lat,lng));
map.setCenter(new GLatLng(lat,lng));
// Show Marker and the Info window
showMarkerAndInfo(lat,lng, zoom);
}
return true;
}
/*
Show Maker on the map and show the info window.
*/
function showMarkerAndInfo(lat, lng, zoom){
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
map.closeInfoWindow();
var marker = markermanager.getMarker(lat,lng, zoom);
markermanager.removeMarker(marker);
markermanager.addMarker(marker,zoom);
//console.debug(markermanager.getMarkerCount(zoom));
markermanager.refresh();
var $curPanelImg = $("#panel_"+curPanel+" img");
// Set the click event for the marker
//GEvent.addListener(marker, "click", function(){
// marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//});
marker.bindInfoWindowHtml("<div style=\"font-size:11px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
//console.debug($curPanelImg.attr("src"));
//marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//GEvent.trigger(marker, "click");
setTimeout(function(){GEvent.trigger(marker, "click");},1000);
return true;
}
/*
Get the photos when the img in infowindow is clicked.
*/
function getPhotos(group, spot){
//console.debug("Enter getPhotos");
// Show waiting notice
- $("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
+ //$("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
//console.debug("Get the photos");
//console.debug('json/photos_'+group+'_'+spot+'.json');
// Get the photos
$.getJSON('json/photos_'+group+'_'+spot+'.json', showLightBox);
}
/*
Show light box for the photos.
*/
function showLightBox(data){
//console.debug("Enter showLightBox");
- $("#notice").empty().css("display","none");
+ //$("#notice").empty().css("display","none");
// Remove the previous photos
$("#gallery").empty();
// Add the photos
$.each(data, function(entryIdx, entry){
var galleryHtml = "<a href=\"";
galleryHtml+=entry['photo_big'];
galleryHtml+="\" title=\"";
galleryHtml+= entry['title'];
galleryHtml+="\"><img src=\"";
galleryHtml+=entry['photo_small'];
galleryHtml+="\" width=\"72\" height=\"72\" alt=\"\" /></a>";
//console.debug(""+galleryHtml);
$("#gallery").append(galleryHtml);
});
// Trigger the light box
$('#gallery a').lightBox({txtImage:'å¾ç',txtOf:'/'});
$("#gallery a:eq(0)").trigger("click");
}
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
var curGroup = 0;
// The map
var map;
var markermanager;
\ No newline at end of file
diff --git a/json/group1.json b/json/group1.json
index 97b9a27..99ff731 100644
--- a/json/group1.json
+++ b/json/group1.json
@@ -1,119 +1,119 @@
[
{
"id": "1",
"name": "ä¸å鍿±½è½¦ç«",
"image_url": "photo/dayone/zhm_bus_station.jpg",
"description": "ä¹åæºåºå¤§å·´",
"latitude": "32.00882197319293",
"longitude": "118.7757682800293",
"zoom": "15"
},
{
"id": "2",
"name": "ç¦å£æºåº",
"image_url": "photo/dayone/lk_airport.jpg",
"description": "å飿º",
- "latitude": "31.78472759839612",
- "longitude": "118.86876583099365",
+ "latitude": "31.732761976442234",
+ "longitude": "118.87096289545298",
"zoom": "15"
},
{
"id": "3",
"name": "广å·",
"image_url": "photo/dayone/guangzhou.jpg",
"description": "广å·",
"latitude": "23.385591961067536",
"longitude": "113.30517768859863",
"zoom": "15"
},
{
"id": "4",
"name": "éç´«è广åº",
"image_url": "photo/dayone/jzj_square.jpg",
"description": "éç´«è广åº",
"latitude": "22.2843412100226",
"longitude": "114.17347848415375",
"zoom": "17"
},
{
"id": "5",
"name": "ä¼å±ä¸å¿",
"image_url": "photo/dayone/meeting_center.jpg",
"description": "ä¼å±ä¸å¿",
"latitude": "22.28282725263975",
"longitude": "114.17293131351471",
"zoom": "17"
},
{
"id": "6",
"name": "ç«æ³ä¼å¤§æ¥¼",
"image_url": "photo/dayone/law.jpg",
"description": "ç«æ³ä¼å¤§æ¥¼",
"latitude": "22.28107997652926",
"longitude": "114.16016399860382",
"zoom": "17"
},
{
"id": "7",
"name": "ä¸å½é¶è¡",
"image_url": "photo/dayone/cob.jpg",
"description": "ä¸å½é¶è¡",
"latitude": "22.280380067189995",
"longitude": "114.16034370660782",
"zoom": "17"
},
{
"id": "8",
- "name": "礼宾åºç¹åº",
+ "name": "礼宾åº",
"image_url": "photo/dayone/libinfu.jpg",
- "description": "礼宾åºç¹åº",
+ "description": "礼宾åº",
"latitude": "22.27875934169057",
"longitude": "114.15763199329376",
"zoom": "18"
},
{
"id": "9",
"name": "æ¿åºæ»é¨",
"image_url": "photo/dayone/gov.jpg",
"description": "æ¿åºæ»é¨",
"latitude": "22.27888592276567",
"longitude": "114.15872633457184",
"zoom": "17"
},
{
"id": "10",
"name": "æµ·æ´å
Œ",
"image_url": "photo/dayone/sea_park.jpg",
"description": "æµ·æ´å
Œ",
"latitude": "22.24527090215842",
"longitude": "114.17679369449615",
"zoom": "17"
},
{
"id": "11",
"name": "æµ
æ°´æ¹¾",
"image_url": "photo/dayone/repulse_bay.jpg",
"description": "æµ
æ°´æ¹¾",
"latitude": "22.237589598654903",
"longitude": "114.19914722442627",
"zoom": "17"
},
{
"id": "12",
"name": "太平山",
"image_url": "photo/dayone/taiping.jpg",
"description": "太平山",
- "latitude": "22.27039232678379",
- "longitude": "114.15189743041992",
- "zoom": "17"
+ "latitude": "22.26328332170731",
+ "longitude": "114.15876388549805",
+ "zoom": "14"
},
{
"id": "13",
"name": "宾é¦",
"image_url": "photo/dayone/hotel.jpg",
"description": "宾é¦",
- "latitude": "22.457657550575618",
- "longitude": "114.00574922561646",
- "zoom": "15"
+ "latitude": "22.45793021785494",
+ "longitude": "114.00272905826569",
+ "zoom": "17"
}
]
diff --git a/json/group2.json b/json/group2.json
index 264fe55..882433e 100644
--- a/json/group2.json
+++ b/json/group2.json
@@ -1,92 +1,92 @@
[
{
"id": "14",
"name": "é»å¤§ä»åº",
"image_url": "photo/daytwo/hdx.jpg",
"description": "é»å¤§ä»åº",
"latitude": "22.343268556904317",
"longitude": "114.19339656829834",
"zoom": "15"
},
{
"id": "15",
"name": "ç å®å±ç¤ºä¸å¿",
"image_url": "photo/daytwo/jewelry.jpg",
"description": "ç å®å±ç¤ºä¸å¿",
"latitude": "22.32662115005807",
"longitude": "114.2052572965622",
"zoom": "17"
},
{
"id": "16",
"name": "ç¾è´§åº",
"image_url": "photo/daytwo/store.jpg",
"description": "ç¾è´§åº",
"latitude": "22.407854560288325",
"longitude": "114.15138244628906",
"zoom": "10"
},
{
"id": "17",
"name": "åé¤",
"image_url": "photo/daytwo/lunch.jpg",
"description": "åé¤",
"latitude": "22.407854560288325",
"longitude": "114.15138244628906",
"zoom": "10"
},
{
"id": "18",
"name": "DFS",
"image_url": "photo/daytwo/dfs.jpg",
"description": "DFS",
"latitude": "22.29681708367642",
"longitude": "114.16930228471756",
"zoom": "18"
},
{
"id": "19",
"name": "æå
大é",
"image_url": "photo/daytwo/start.jpg",
"description": "æå
大é",
- "latitude": "22.293960661077",
- "longitude": "114.17190670967102",
+ "latitude": "22.29351891544449",
+ "longitude": "114.17499125003815",
"zoom": "18"
},
{
"id": "20",
"name": "å°æ²åæåä¸å¿",
"image_url": "photo/daytwo/jsz.jpg",
"description": "å°æ²åæåä¸å¿",
"latitude": "22.29335015831739",
"longitude": "114.16998624801636",
"zoom": "17"
},
{
"id": "21",
"name": "大鿥¼",
"image_url": "photo/daytwo/tower.jpg",
"description": "大鿥¼",
"latitude": "22.2933997927877",
"longitude": "114.16951149702072",
"zoom": "18"
},
{
"id": "22",
"name": "æµ·é²å¤§é¤",
"image_url": "photo/daytwo/sea_food.jpg",
"description": "æµ·é²å¤§é¤",
"latitude": "22.407854560288325",
"longitude": "114.15138244628906",
"zoom": "10"
},
{
"id": "23",
"name": "ç»´å¤å©äºæ¸¯",
"image_url": "photo/daytwo/victoria.jpg",
"description": "ç»´å¤å©äºæ¸¯",
"latitude": "22.29529085297506",
"longitude": "114.16202545166016",
"zoom": "13"
}
]
diff --git a/json/group5.json b/json/group5.json
index 44d2fb5..445c2ab 100644
--- a/json/group5.json
+++ b/json/group5.json
@@ -1,38 +1,38 @@
[
{
"id": "43",
"name": "æ±åå
³",
"image_url": "photo/dayfive/gbg.jpg",
"description": "æ±åå
³",
"latitude": "22.22443556792428",
"longitude": "113.56189727783203",
"zoom": "12"
},
{
"id": "44",
"name": "æ
侣路",
"image_url": "photo/dayfive/lover.jpg",
"description": "æ
侣路",
"latitude": "22.26129750157242",
"longitude": "113.5856294631958",
"zoom": "14"
},
{
"id": "45",
"name": "æ¸å¥³å",
"image_url": "photo/dayfive/fisher.jpg",
"description": "æ¸å¥³å",
"latitude": "22.261793959247537",
"longitude": "113.58962059020996",
"zoom": "15"
},
{
"id": "49",
"name": "å京æºåº",
"image_url": "photo/dayfive/nkg.jpg",
"description": "å京æºåº",
- "latitude": "31.78472759839612",
- "longitude": "118.86876583099365",
+ "latitude": "31.732761976442234",
+ "longitude": "118.87096289545298",
"zoom": "15"
}
]
diff --git a/json/photos_1_2.json b/json/photos_1_2.json
index e2693c5..aa72079 100644
--- a/json/photos_1_2.json
+++ b/json/photos_1_2.json
@@ -1,12 +1,17 @@
[
{
"photo_big": "photo/dayone/lk_airport.jpg",
"title": "å¾çæ¥èªç½ç»",
"photo_small": "photo/dayone/lk_airport.jpg"
},
{
"photo_big": "photo/dayone/lk_airport/lk_airport_inside.jpg",
- "title": "ç¡ææ£æµæ¥å°æºåºï¼ç¨å°ææºæäºä¸å¼ ",
+ "title": "ç¡ææ£æµæ¥å°æºåºï¼ç¨ææºæäºä¸å¼ ",
"photo_small": "photo/dayone/lk_airport/lk_airport_inside.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/lk_airport/plane.jpg",
+ "title": "èµ·é£å¯",
+ "photo_small": "photo/dayone/lk_airport/plane.jpg"
}
]
diff --git a/json/photos_1_3.json b/json/photos_1_3.json
index ed5d02a..e7a25d7 100644
--- a/json/photos_1_3.json
+++ b/json/photos_1_3.json
@@ -1,17 +1,22 @@
[
{
"photo_big": "photo/dayone/guangzhou.jpg",
"title": "广å·ç½äºæºåºï¼å¾çæ¥èªç½ç»",
"photo_small": "photo/dayone/guangzhou.jpg"
},
+ {
+ "photo_big": "photo/dayone/guangzhou/plane.jpg",
+ "title": "éè½å¯",
+ "photo_small": "photo/dayone/guangzhou/plane.jpg"
+ },
{
"photo_big": "photo/dayone/guangzhou/tower.jpg",
"title": "è¿ä¸ªä¸è¥¿æ³ææ²¡ææå°",
"photo_small": "photo/dayone/guangzhou/tower.jpg"
},
{
"photo_big": "photo/dayone/guangzhou/gz_airport.jpg",
"title": "åªæ¯å¨è¿æºåºçç ´è½¦ä¸æäºä¸å¼ ",
"photo_small": "photo/dayone/guangzhou/gz_airport.jpg"
}
]
diff --git a/photo/dayone/guangzhou/plane.jpg b/photo/dayone/guangzhou/plane.jpg
new file mode 100644
index 0000000..c9cda1f
Binary files /dev/null and b/photo/dayone/guangzhou/plane.jpg differ
diff --git a/photo/dayone/lk_airport/plane.jpg b/photo/dayone/lk_airport/plane.jpg
new file mode 100644
index 0000000..6335add
Binary files /dev/null and b/photo/dayone/lk_airport/plane.jpg differ
|
kurtchen/hk_macau
|
5c2203415ba939ed39265e03c9f8324d9ab03099
|
finished the photo album.
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..f05287e
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+*.[oa]
+*~
diff --git a/css/jquery.lightbox-0.5.css b/css/jquery.lightbox-0.5.css
new file mode 100644
index 0000000..dfdc488
--- /dev/null
+++ b/css/jquery.lightbox-0.5.css
@@ -0,0 +1,102 @@
+/**
+ * jQuery lightBox plugin
+ * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
+ * and adapted to me for use like a plugin from jQuery.
+ * @name jquery-lightbox-0.5.css
+ * @author Leandro Vieira Pinho - http://leandrovieira.com
+ * @version 0.5
+ * @date April 11, 2008
+ * @category jQuery plugin
+ * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
+ * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
+ * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
+ */
+#jquery-overlay {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 90;
+ width: 100%;
+ height: 500px;
+}
+#jquery-lightbox {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 100%;
+ z-index: 100;
+ text-align: center;
+ line-height: 0;
+}
+#jquery-lightbox a img { border: none; }
+#lightbox-container-image-box {
+ position: relative;
+ background-color: #fff;
+ width: 250px;
+ height: 250px;
+ margin: 0 auto;
+}
+#lightbox-container-image { padding: 10px; }
+#lightbox-loading {
+ position: absolute;
+ top: 40%;
+ left: 0%;
+ height: 25%;
+ width: 100%;
+ text-align: center;
+ line-height: 0;
+}
+#lightbox-nav {
+ position: absolute;
+ top: 0;
+ left: 0;
+ height: 100%;
+ width: 100%;
+ z-index: 10;
+}
+#lightbox-container-image-box > #lightbox-nav { left: 0; }
+#lightbox-nav a { outline: none;}
+#lightbox-nav-btnPrev, #lightbox-nav-btnNext {
+ width: 49%;
+ height: 100%;
+ zoom: 1;
+ display: block;
+}
+#lightbox-nav-btnPrev {
+ left: 0;
+ float: left;
+}
+#lightbox-nav-btnNext {
+ right: 0;
+ float: right;
+}
+#lightbox-container-image-data-box {
+ font: 10px Verdana, Helvetica, sans-serif;
+ background-color: #fff;
+ margin: 0 auto;
+ line-height: 1.4em;
+ overflow: auto;
+ width: 100%;
+ padding: 0 10px 0;
+}
+#lightbox-container-image-data {
+ padding: 0 10px;
+ color: #666;
+}
+#lightbox-container-image-data #lightbox-image-details {
+ width: 70%;
+ float: left;
+ text-align: left;
+}
+#lightbox-image-details-caption { font-weight: bold; font-size: 12px;}
+#lightbox-image-details-currentNumber {
+ display: block;
+ clear: left;
+ padding-bottom: 1.0em;
+ font-size: 11px;
+}
+#lightbox-secNav-btnClose {
+ width: 66px;
+ float: right;
+ padding-bottom: 0.7em;
+}
\ No newline at end of file
diff --git a/css/main.css b/css/main.css
index 1908b48..198079b 100644
--- a/css/main.css
+++ b/css/main.css
@@ -1,178 +1,238 @@
body
{
margin:0;
padding:0;
}
/* ---------------Tabs-------------------- */
.TabsArea
{
overflow:hidden;
margin:auto;
}
.TabsArea .TabMenu
{
position: relative;
top: 5px;
left: 2px;
z-index: 10;
}
.TabsArea .TabMenu span
{
display: inline-block;
height: 85px;
width: 130px;
margin: 0px;
padding:0px;
font-family: "é»ä½","å®ä½",Verdana,Serif;
font-size: large;
font-weight: bold;
text-align: center;
vertical-align: middle;
cursor: pointer;
}
.TabsArea .TabMenu .CameraIcon
{
height: 56px;
width: 56px;
margin-top: 2px;
margin-left: 3px;
margin-right: 3px;
}
/* ---------------Slider-------------------- */
#slider {
width: 800px;
margin-top: 10px;
position: relative;
border: 10px solid #ccc;
}
.ScrollPanes {
overflow: hidden;
height: 150px;
width: 800px;
margin: 0 auto;
position: relative;
}
.ScrollContainer {
position: relative;
}
.ScrollContainer img{
margin-top: 65px;
}
.ScrollContainer div{
float: left;
position: relative;
}
.ScrollContainer div.Panel {
padding: 10px;
width: 130px;
/*height: 318px;*/
}
.ScrollContainer .Panel .inside {
padding: 5px;
border: 1px solid #999;
}
.ScrollContainer .Panel .inside img {
display: block;
border: 1px solid #666;
margin: 0 0 3px 0;
width: 100px;
}
.ScrollContainer .Panel .inside span {
font-weight: normal;
color: #111;
font-size: 12px;
}
.ScrollContainer .Panel .inside p {
font-size: 11px;
color: #ccc;
}
a {
color: #999;
text-decoration: none;
border-bottom: 1px dotted #ccc;
}
a:hover {
border-bottom: 1px solid #999;
}
.ScrollButtons {
position: absolute;
top: 46px;
cursor: pointer;
}
.ScrollButtons.left {
left: -45px;
}
.ScrollButtons.right {
right: -45px;
}
#left_shadow {
position: absolute;
top: 0;
left: 0;
width: 12px;
bottom: 0;
background: url(../img/leftshadow.png) repeat-y;
}
#right_shadow {
position: absolute;
top: 0;
right: 0;
width: 12px;
bottom: 0;
background: url(../img/rightshadow.png) repeat-y;
}
/* ---------------Map-------------------- */
#hk_map {
position: relative;
width: 800px;
height: 430px;
border: 10px solid #ccc;
}
/*.TabsArea .ContentFrame
{
height:206px;
left: 10px;
position: relative;
overflow:hidden;
}
.TabsArea .ContentFrame .AllTabs
{
position: relative;
left:0px;
width: 1190px;
height: 206px;
overflow:hidden;
}
.TabsArea .ContentFrame .AllTabs .TabContent
{
height: 200px;
margin-right:20px;
text-align: justify;
float:left;
overflow:hidden;
}*/
+
+/*------------------Gallery-----------------------*/
+#gallery {
+ /*position: absolute;*/
+ display: none;
+ background-color: #444;
+ padding: 10px;
+ width: 100%;
+ /*height: 500px;
+ z-index: 90;*/
+}
+#gallery ul { list-style: none; }
+#gallery ul li { display: inline; }
+#gallery ul img {
+ border: 5px solid #3e3e3e;
+ border-width: 5px 5px 20px;
+}
+#gallery ul a:hover img {
+ border: 5px solid #fff;
+ border-width: 5px 5px 20px;
+ color: #fff;
+}
+#gallery ul a:hover { color: #fff; }
+
+/*------------------Notice Area-----------------------*/
+#notice {
+ position: absolute;
+ left: 100%;
+ top: 0;
+ width: 200px;
+ background-color: #f00;
+ display: none;
+}
+/*------------------About Area-----------------------*/
+#about {
+ border-top-color: #ccc;
+ border-top-style: dotted;
+ border-top-width: 1px;
+ margin-top: 20px;
+ background-color: #eee;
+ width: 860px;
+ height: 150px;
+ text-align: left;
+ font-family: Verdana, Arial;
+ font-size: 10px;
+ color: #aaa;
+}
+#about_album {
+ margin-top: 20px;
+ margin-left: 20px;
+ float: left;
+ width: 45%;
+}
+#about_me {
+ margin-top: 20px;
+ margin-right: 20px;
+ float: right;
+ width: 45%;
+ position: relative;
+}
/*------------------Others-----------------------*/
.hide {
display: none;
}
.selector
{
background: url(../img/selector.png);
}
.hovering
{
background: url(../img/selector.png);
opacity: 0.5;
filter: alpha(opacity=50);
}
\ No newline at end of file
diff --git a/images/lightbox-blank.gif b/images/lightbox-blank.gif
new file mode 100644
index 0000000..1d11fa9
Binary files /dev/null and b/images/lightbox-blank.gif differ
diff --git a/images/lightbox-btn-close.gif b/images/lightbox-btn-close.gif
new file mode 100644
index 0000000..33bcf51
Binary files /dev/null and b/images/lightbox-btn-close.gif differ
diff --git a/images/lightbox-btn-next.gif b/images/lightbox-btn-next.gif
new file mode 100644
index 0000000..a0d4fcf
Binary files /dev/null and b/images/lightbox-btn-next.gif differ
diff --git a/images/lightbox-btn-prev.gif b/images/lightbox-btn-prev.gif
new file mode 100644
index 0000000..040ee59
Binary files /dev/null and b/images/lightbox-btn-prev.gif differ
diff --git a/images/lightbox-ico-loading.gif b/images/lightbox-ico-loading.gif
new file mode 100644
index 0000000..4f1429c
Binary files /dev/null and b/images/lightbox-ico-loading.gif differ
diff --git a/img/Contact.png b/img/Contact.png
deleted file mode 100644
index 9a93e12..0000000
Binary files a/img/Contact.png and /dev/null differ
diff --git a/img/Drive.png b/img/Drive.png
deleted file mode 100644
index 8007fcb..0000000
Binary files a/img/Drive.png and /dev/null differ
diff --git a/img/Thumbs.db b/img/Thumbs.db
deleted file mode 100644
index f81ec69..0000000
Binary files a/img/Thumbs.db and /dev/null differ
diff --git a/img/gmail.png b/img/gmail.png
new file mode 100755
index 0000000..d25a065
Binary files /dev/null and b/img/gmail.png differ
diff --git a/img/hongkong/hongkong1.jpg b/img/hongkong/hongkong1.jpg
deleted file mode 100644
index 0a31f7e..0000000
Binary files a/img/hongkong/hongkong1.jpg and /dev/null differ
diff --git a/img/hongkong/hongkong2.jpg b/img/hongkong/hongkong2.jpg
deleted file mode 100644
index 23adf09..0000000
Binary files a/img/hongkong/hongkong2.jpg and /dev/null differ
diff --git a/img/hongkong/hongkong3.jpg b/img/hongkong/hongkong3.jpg
deleted file mode 100644
index bcbd324..0000000
Binary files a/img/hongkong/hongkong3.jpg and /dev/null differ
diff --git a/img/hongkong/hongkong4.jpg b/img/hongkong/hongkong4.jpg
deleted file mode 100644
index b49df10..0000000
Binary files a/img/hongkong/hongkong4.jpg and /dev/null differ
diff --git a/img/hongkong/hongkong5.jpg b/img/hongkong/hongkong5.jpg
deleted file mode 100644
index 2141d3c..0000000
Binary files a/img/hongkong/hongkong5.jpg and /dev/null differ
diff --git a/img/hotmail.png b/img/hotmail.png
new file mode 100755
index 0000000..3f9d6aa
Binary files /dev/null and b/img/hotmail.png differ
diff --git a/img/iPod.png b/img/iPod.png
deleted file mode 100644
index 8f7fe10..0000000
Binary files a/img/iPod.png and /dev/null differ
diff --git a/img/macau/macau.jpg b/img/macau/macau.jpg
deleted file mode 100644
index 12cf762..0000000
Binary files a/img/macau/macau.jpg and /dev/null differ
diff --git a/img/slider/1.jpg b/img/slider/1.jpg
deleted file mode 100644
index d025210..0000000
Binary files a/img/slider/1.jpg and /dev/null differ
diff --git a/img/slider/2.jpg b/img/slider/2.jpg
deleted file mode 100644
index 63292eb..0000000
Binary files a/img/slider/2.jpg and /dev/null differ
diff --git a/img/slider/3.jpg b/img/slider/3.jpg
deleted file mode 100644
index 3908aab..0000000
Binary files a/img/slider/3.jpg and /dev/null differ
diff --git a/img/slider/4.jpg b/img/slider/4.jpg
deleted file mode 100644
index 29c6f64..0000000
Binary files a/img/slider/4.jpg and /dev/null differ
diff --git a/img/slider/5.jpg b/img/slider/5.jpg
deleted file mode 100644
index 63892a2..0000000
Binary files a/img/slider/5.jpg and /dev/null differ
diff --git a/img/under_construction.jpg b/img/under_construction.jpg
deleted file mode 100644
index 060e1c4..0000000
Binary files a/img/under_construction.jpg and /dev/null differ
diff --git a/index.html b/index.html
index 5100765..d5f826f 100644
--- a/index.html
+++ b/index.html
@@ -1,43 +1,156 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HongKong & Macau in 5 Days</title>
- <script src="js/jquery.js" type="text/javascript"></script>
- <link rel="stylesheet" type="text/css" href="css/main.css" />
- <script src="js/main.js" type="text/javascript"></script>
+ <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
+ <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
+ <script src="js/markermanager.js" type="text/javascript"></script>
+ <script src="js/main.js" type="text/javascript"></script>
+ <script src="js/jquery.lightbox-0.5.js" type="text/javascript"></script>
+ <link rel="stylesheet" type="text/css" href="css/main.css" />
+ <link rel="stylesheet" type="text/css" href="css/jquery.lightbox-0.5.css" media="screen" />
</head>
<body>
- <center>
- <div class="TabsArea">
- <div class="TabMenu">
- <span><img src="img/contact.png" /></span>
- <span><img src="img/ipod.png" /></span>
- <span><img src="img/drive.png" /></span>
- <span><img src="img/ipod.png" /></span>
- <span><img src="img/drive.png" /></span>
- </div>
- <div class="ContentFrame">
- <div class="AllTabs">
- <div class="TabContent">
- <img src="photo/sample.jpg" height="100" width="100"/>
- </div>
- <div class="TabContent">
- <img src="photo/sample.jpg" height="100" width="100"/>
- </div>
- <div class="TabContent">
- <img src="photo/sample.jpg" height="200" width="200"/>
- </div>
- <div class="TabContent">
- <img src="photo/sample.jpg" height="100" width="100"/>
- </div>
- <div class="TabContent">
- <img src="photo/sample.jpg" height="100" width="100"/>
- </div>
+ <div id="notice"></div>
+ <center>
+ <div id="gallery">
+<!-- <ul>
+ <li>
+ <a href="photos/image1.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery').lightBox();">
+ <img src="photos/thumb_image1.jpg" width="72" height="72" alt="" />
+ </a>
+ </li>
+ <li>
+ <a href="photos/image2.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image2.jpg" width="72" height="72" alt="" />
+ </a>
+ </li>
+ <li>
+ <a href="photos/image3.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image3.jpg" width="72" height="72" alt="" />
+ </a>
+ </li>
+ <li>
+ <a href="photos/image4.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image4.jpg" width="72" height="72" alt="" />
+ </a>
+ </li>
+ <li>
+ <a href="photos/image5.jpg" title="Utilize a flexibilidade dos seletores da jQuery e crie um grupo de imagens como desejar. $('#gallery a').lightBox();">
+ <img src="photos/thumb_image5.jpg" width="72" height="72" alt="" />
+ </a>
+ </li>
+ </ul>-->
+ </div>
+ <div class="TabsArea">
+ <div id="tab_menu" class="TabMenu">
+ <img src="img/loading.gif" width="220" height="19"/>
+ <!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
+ <span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
+ <span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
+ <span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
+ <span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
+ </div>
+<!--############################Begine Slider###########################################-->
+ <div id="slider">
+ <img class="ScrollButtons left" src="img/leftarrow.png">
+ <div class="ScrollPanes">
+ <div class="ScrollContainer">
+<!-- <img src="img/loading.gif" width="220" height="19"/> -->
+<!--
+ <div class="Panel" id="panel_1">
+ <div class="inside">
+ <img src="img/slider/1.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_2">
+ <div class="inside">
+ <img src="img/slider/2.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_3">
+ <div class="inside">
+ <img src="img/slider/3.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_4">
+ <div class="inside">
+ <img src="img/slider/4.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_5">
+ <div class="inside">
+ <img src="img/slider/5.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+-->
+ </div>
+ <div id="left_shadow"></div>
+ <div id="right_shadow"></div>
+ </div>
+ <img class="ScrollButtons right" src="img/rightarrow.png">
+ </div>
+<!--############################End Slider###########################################-->
</div>
- </div>
+ <hr/>
+<!--############################Begine Map###########################################-->
+ <div id="hk_map">
+
</div>
- </center>
+<!--############################End Map###########################################-->
+
+<!--
+ <div>
+ <img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
+ </div>
+-->
+<!--############################Begine About###########################################-->
+<div id="about">
+ <div id="about_album">
+ <b>About this Album</b>
+ <ul>
+ <li>
+ Powerd By: <a href="http://jquery.com/">jQuery</a>, <a href="http://code.google.com/apis/maps/">Google Map</a>, <a href="http://leandrovieira.com/projects/jquery/lightbox/">LightBox jQuery plugin</a>, <a href="http://css-tricks.com/moving-boxes/">Moving Boxes</a>.
+ </li>
+ <li>
+ Most of the photos were taken during traveling in Hong Kong and Macau from 2009-09-18 to 2009-09-22. Some of the photos are from Internet.
+ </li>
+ <li>
+ The source code can be fetched from <a href="http://github.com/kurtchen/hk_macau">github.com</a>
+ </li>
+ </ul>
+ </div>
+ <div id="about_me">
+ <b>About Me</b>
+ <ul>
+ <li>
+ Software Engineer in NanJing. <br/>Interested in Mobile & Web.
+ </li>
+ <li>
+ Email: <br/><img src="img/gmail.png"/><img src="img/hotmail.png"/>
+ </li>
+ <li>
+ Blog: <a href="http://chenguangming83.spaces.live.com/">http://chenguangming83.spaces.live.com/</a>
+ </li>
+ <li>
+ Twitter: <a href="http://twitter.com/kurtchen">http://twitter.com/kurtchen</a>
+ </li>
+ </ul>
+ </div>
+</div>
+<!--############################End About###########################################-->
+
+ </center>
</body>
</html>
diff --git a/index.php b/index.php
deleted file mode 100644
index 254253c..0000000
--- a/index.php
+++ /dev/null
@@ -1,87 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
-"http://www.w3.org/TR/html4/loose.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>HongKong & Macau in 5 Days</title>
- <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
- <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
- <link rel="stylesheet" type="text/css" href="css/main.css" />
- <script src="js/main.js" type="text/javascript"></script>
- </head>
- <body>
- <center>
- <div class="TabsArea">
- <div id="tab_menu" class="TabMenu">
- <img src="img/loading.gif" width="220" height="19"/>
- <!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
- <span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
- <span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
- <span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
- <span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
- </div>
-<!--############################Begine Slider###########################################-->
- <div id="slider">
- <img class="ScrollButtons left" src="img/leftarrow.png">
- <div class="ScrollPanes">
- <div class="ScrollContainer">
-<!-- <img src="img/loading.gif" width="220" height="19"/> -->
-<!--
- <div class="Panel" id="panel_1">
- <div class="inside">
- <img src="img/slider/1.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_2">
- <div class="inside">
- <img src="img/slider/2.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_3">
- <div class="inside">
- <img src="img/slider/3.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_4">
- <div class="inside">
- <img src="img/slider/4.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_5">
- <div class="inside">
- <img src="img/slider/5.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
--->
- </div>
- <div id="left_shadow"></div>
- <div id="right_shadow"></div>
- </div>
- <img class="ScrollButtons right" src="img/rightarrow.png">
- </div>
-<!--############################End Slider###########################################-->
- </div>
- <hr/>
-<!--############################Begine Map###########################################-->
- <div id="hk_map">
-
- </div>
-<!--############################End Map###########################################-->
-
-<!--
- <div>
- <img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
- <img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
- <img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
- <img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
- <img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
- </div>
--->
- </center>
- </body>
-</html>
diff --git a/index_static.html b/index_static.html
deleted file mode 100644
index 97c0aa8..0000000
--- a/index_static.html
+++ /dev/null
@@ -1,88 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
-"http://www.w3.org/TR/html4/loose.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>HongKong & Macau in 5 Days</title>
- <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
- <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
- <script src="js/markermanager.js" type="text/javascript"></script><!---->
- <link rel="stylesheet" type="text/css" href="css/main.css" />
- <script src="js/main.js" type="text/javascript"></script>
- </head>
- <body>
- <center>
- <div class="TabsArea">
- <div id="tab_menu" class="TabMenu">
- <img src="img/loading.gif" width="220" height="19"/>
- <!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
- <span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
- <span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
- <span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
- <span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
- </div>
-<!--############################Begine Slider###########################################-->
- <div id="slider">
- <img class="ScrollButtons left" src="img/leftarrow.png">
- <div class="ScrollPanes">
- <div class="ScrollContainer">
-<!-- <img src="img/loading.gif" width="220" height="19"/> -->
-<!--
- <div class="Panel" id="panel_1">
- <div class="inside">
- <img src="img/slider/1.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_2">
- <div class="inside">
- <img src="img/slider/2.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_3">
- <div class="inside">
- <img src="img/slider/3.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_4">
- <div class="inside">
- <img src="img/slider/4.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
- <div class="Panel" id="panel_5">
- <div class="inside">
- <img src="img/slider/5.jpg" alt="picture" />
- <span>News Heading</span>
- </div>
- </div>
--->
- </div>
- <div id="left_shadow"></div>
- <div id="right_shadow"></div>
- </div>
- <img class="ScrollButtons right" src="img/rightarrow.png">
- </div>
-<!--############################End Slider###########################################-->
- </div>
- <hr/>
-<!--############################Begine Map###########################################-->
- <div id="hk_map">
-
- </div>
-<!--############################End Map###########################################-->
-
-<!--
- <div>
- <img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
- <img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
- <img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
- <img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
- <img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
- </div>
--->
- </center>
- </body>
-</html>
diff --git a/index_try.html b/index_try.html
deleted file mode 100644
index 70aaae3..0000000
--- a/index_try.html
+++ /dev/null
@@ -1,49 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
-<head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>HongKong & Macau
-in 5 Days</title>
- <script src="js/jquery.js" type="text/javascript"></script>
- <link rel="stylesheet" type="text/css" href="css/main.css">
- <script src="js/main.js" type="text/javascript"></script>
-</head>
-<body>
-<center>
-<div class="TabsArea">
-<div class="TabMenu"><!--<img src="img/loading.gif"/>--> <span><img
- style="width: 24px; height: 32px;" alt="" src="img/camera.png">第ä¸å¤©</span>
-<span><img src="img/camera.png" align="middle" height="32" width="24">第äº
-天</span>
-<span><img src="img/camera.png" align="middle" height="32" width="24">第ä¸
-天</span>
-<span><img src="img/camera.png" align="middle" height="32" width="24">第å
-天</span>
-<span><img src="img/camera.png" align="middle" height="32" width="24">第äº
-天</span>
-</div>
-<!--
-<div class="ContentFrame">
-<div class="AllTabs">
-<div class="TabContent">
-<img src="photo/sample.jpg" height="100" width="100"/>
-</div>
-<div class="TabContent">
-<img src="photo/sample.jpg" height="100" width="100"/>
-</div>
-<div class="TabContent">
-<img src="photo/sample.jpg" height="200" width="200"/>
-</div>
-<div class="TabContent">
-<img src="photo/sample.jpg" height="100" width="100"/>
-</div>
-<div class="TabContent">
-<img src="photo/sample.jpg" height="100" width="100"/>
-</div>
-</div>
-</div>
--->
-</div>
-</center>
-</body>
-</html>
diff --git a/index_under.php b/index_under.php
deleted file mode 100644
index f0f4e5f..0000000
--- a/index_under.php
+++ /dev/null
@@ -1,31 +0,0 @@
-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
-<html>
-<head>
- <title>Hongkong & Macau
-in 5 Days</title>
-</head>
-<body style="background-color: rgb(0, 0, 0); color: rgb(0, 0, 0);"
- alink="#ee0000" link="#0000ee" vlink="#551a8b">
-<div style="text-align: center;"><img
- style="width: 500px; height: 300px;" alt=""
- src="img/under_construction.jpg"></div>
-<div style="text-align: center;"><img
- style="width: 134px; height: 88px;" alt=""
- src="img/hongkong/hongkong2.jpg"><img
- style="width: 134px; height: 88px;" alt=""
- src="img/hongkong/hongkong5.jpg"><img
- style="width: 134px; height: 88px;" alt="" src="img/macau/macau.jpg"></div>
-<div
- style="text-align: center; color: rgb(204, 204, 204); font-family: Verdana; font-weight: bold;"><br>
-Will come to you soon...<br>
-<br>
-<?php
- echo date("Y-m-d G:i:s");;
-?>
-<?php
- echo "<br/>This is git test, on hongkong branch";
-?>
-
-</div>
-</body>
-</html>
diff --git a/js/jquery.lightbox-0.5.js b/js/jquery.lightbox-0.5.js
new file mode 100644
index 0000000..f664240
--- /dev/null
+++ b/js/jquery.lightbox-0.5.js
@@ -0,0 +1,472 @@
+/**
+ * jQuery lightBox plugin
+ * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
+ * and adapted to me for use like a plugin from jQuery.
+ * @name jquery-lightbox-0.5.js
+ * @author Leandro Vieira Pinho - http://leandrovieira.com
+ * @version 0.5
+ * @date April 11, 2008
+ * @category jQuery plugin
+ * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
+ * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
+ * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
+ */
+
+// Offering a Custom Alias suport - More info: http://docs.jquery.com/Plugins/Authoring#Custom_Alias
+(function($) {
+ /**
+ * $ is an alias to jQuery object
+ *
+ */
+ $.fn.lightBox = function(settings) {
+ // Settings to configure the jQuery lightBox plugin how you like
+ settings = jQuery.extend({
+ // Configuration related to overlay
+ overlayBgColor: '#000', // (string) Background color to overlay; inform a hexadecimal value like: #RRGGBB. Where RR, GG, and BB are the hexadecimal values for the red, green, and blue values of the color.
+ overlayOpacity: 0.8, // (integer) Opacity value to overlay; inform: 0.X. Where X are number from 0 to 9
+ // Configuration related to navigation
+ fixedNavigation: false, // (boolean) Boolean that informs if the navigation (next and prev button) will be fixed or not in the interface.
+ // Configuration related to images
+ imageLoading: 'images/lightbox-ico-loading.gif', // (string) Path and the name of the loading icon
+ imageBtnPrev: 'images/lightbox-btn-prev.gif', // (string) Path and the name of the prev button image
+ imageBtnNext: 'images/lightbox-btn-next.gif', // (string) Path and the name of the next button image
+ imageBtnClose: 'images/lightbox-btn-close.gif', // (string) Path and the name of the close btn
+ imageBlank: 'images/lightbox-blank.gif', // (string) Path and the name of a blank image (one pixel)
+ // Configuration related to container image box
+ containerBorderSize: 10, // (integer) If you adjust the padding in the CSS for the container, #lightbox-container-image-box, you will need to update this value
+ containerResizeSpeed: 400, // (integer) Specify the resize duration of container image. These number are miliseconds. 400 is default.
+ // Configuration related to texts in caption. For example: Image 2 of 8. You can alter either "Image" and "of" texts.
+ txtImage: 'Image', // (string) Specify text "Image"
+ txtOf: 'of', // (string) Specify text "of"
+ // Configuration related to keyboard navigation
+ keyToClose: 'c', // (string) (c = close) Letter to close the jQuery lightBox interface. Beyond this letter, the letter X and the SCAPE key is used to.
+ keyToPrev: 'p', // (string) (p = previous) Letter to show the previous image
+ keyToNext: 'n', // (string) (n = next) Letter to show the next image.
+ // Don´t alter these variables in any way
+ imageArray: [],
+ activeImage: 0
+ },settings);
+ // Caching the jQuery object with all elements matched
+ var jQueryMatchedObj = this; // This, in this context, refer to jQuery object
+ /**
+ * Initializing the plugin calling the start function
+ *
+ * @return boolean false
+ */
+ function _initialize() {
+ _start(this,jQueryMatchedObj); // This, in this context, refer to object (link) which the user have clicked
+ return false; // Avoid the browser following the link
+ }
+ /**
+ * Start the jQuery lightBox plugin
+ *
+ * @param object objClicked The object (link) whick the user have clicked
+ * @param object jQueryMatchedObj The jQuery object with all elements matched
+ */
+ function _start(objClicked,jQueryMatchedObj) {
+ // Hime some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
+ $('embed, object, select').css({ 'visibility' : 'hidden' });
+ // Call the function to create the markup structure; style some elements; assign events in some elements.
+ _set_interface();
+ // Unset total images in imageArray
+ settings.imageArray.length = 0;
+ // Unset image active information
+ settings.activeImage = 0;
+ // We have an image set? Or just an image? Let´s see it.
+ if ( jQueryMatchedObj.length == 1 ) {
+ settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));
+ } else {
+ // Add an Array (as many as we have), with href and title atributes, inside the Array that storage the images references
+ for ( var i = 0; i < jQueryMatchedObj.length; i++ ) {
+ settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));
+ }
+ }
+ while ( settings.imageArray[settings.activeImage][0] != objClicked.getAttribute('href') ) {
+ settings.activeImage++;
+ }
+ // Call the function that prepares image exibition
+ _set_image_to_view();
+ }
+ /**
+ * Create the jQuery lightBox plugin interface
+ *
+ * The HTML markup will be like that:
+ <div id="jquery-overlay"></div>
+ <div id="jquery-lightbox">
+ <div id="lightbox-container-image-box">
+ <div id="lightbox-container-image">
+ <img src="../fotos/XX.jpg" id="lightbox-image">
+ <div id="lightbox-nav">
+ <a href="#" id="lightbox-nav-btnPrev"></a>
+ <a href="#" id="lightbox-nav-btnNext"></a>
+ </div>
+ <div id="lightbox-loading">
+ <a href="#" id="lightbox-loading-link">
+ <img src="../images/lightbox-ico-loading.gif">
+ </a>
+ </div>
+ </div>
+ </div>
+ <div id="lightbox-container-image-data-box">
+ <div id="lightbox-container-image-data">
+ <div id="lightbox-image-details">
+ <span id="lightbox-image-details-caption"></span>
+ <span id="lightbox-image-details-currentNumber"></span>
+ </div>
+ <div id="lightbox-secNav">
+ <a href="#" id="lightbox-secNav-btnClose">
+ <img src="../images/lightbox-btn-close.gif">
+ </a>
+ </div>
+ </div>
+ </div>
+ </div>
+ *
+ */
+ function _set_interface() {
+ // Apply the HTML markup into body tag
+ $('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="' + settings.imageLoading + '"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="' + settings.imageBtnClose + '"></a></div></div></div></div>');
+ // Get page sizes
+ var arrPageSizes = ___getPageSize();
+ // Style overlay and show it
+ $('#jquery-overlay').css({
+ backgroundColor: settings.overlayBgColor,
+ opacity: settings.overlayOpacity,
+ width: arrPageSizes[0],
+ height: arrPageSizes[1]
+ }).fadeIn();
+ // Get page scroll
+ var arrPageScroll = ___getPageScroll();
+ // Calculate top and left offset for the jquery-lightbox div object and show it
+ $('#jquery-lightbox').css({
+ top: arrPageScroll[1] + (arrPageSizes[3] / 10),
+ left: arrPageScroll[0]
+ }).show();
+ // Assigning click events in elements to close overlay
+ $('#jquery-overlay,#jquery-lightbox').click(function() {
+ _finish();
+ });
+ // Assign the _finish function to lightbox-loading-link and lightbox-secNav-btnClose objects
+ $('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function() {
+ _finish();
+ return false;
+ });
+ // If window was resized, calculate the new overlay dimensions
+ $(window).resize(function() {
+ // Get page sizes
+ var arrPageSizes = ___getPageSize();
+ // Style overlay and show it
+ $('#jquery-overlay').css({
+ width: arrPageSizes[0],
+ height: arrPageSizes[1]
+ });
+ // Get page scroll
+ var arrPageScroll = ___getPageScroll();
+ // Calculate top and left offset for the jquery-lightbox div object and show it
+ $('#jquery-lightbox').css({
+ top: arrPageScroll[1] + (arrPageSizes[3] / 10),
+ left: arrPageScroll[0]
+ });
+ });
+ }
+ /**
+ * Prepares image exibition; doing a image´s preloader to calculate it´s size
+ *
+ */
+ function _set_image_to_view() { // show the loading
+ // Show the loading
+ $('#lightbox-loading').show();
+ if ( settings.fixedNavigation ) {
+ $('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
+ } else {
+ // Hide some elements
+ $('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();
+ }
+ // Image preload process
+ var objImagePreloader = new Image();
+ objImagePreloader.onload = function() {
+ $('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);
+ // Perfomance an effect in the image container resizing it
+ _resize_container_image_box(objImagePreloader.width,objImagePreloader.height);
+ // clear onLoad, IE behaves irratically with animated gifs otherwise
+ objImagePreloader.onload=function(){};
+ };
+ objImagePreloader.src = settings.imageArray[settings.activeImage][0];
+ };
+ /**
+ * Perfomance an effect in the image container resizing it
+ *
+ * @param integer intImageWidth The image´s width that will be showed
+ * @param integer intImageHeight The image´s height that will be showed
+ */
+ function _resize_container_image_box(intImageWidth,intImageHeight) {
+ // Get current width and height
+ var intCurrentWidth = $('#lightbox-container-image-box').width();
+ var intCurrentHeight = $('#lightbox-container-image-box').height();
+ // Get the width and height of the selected image plus the padding
+ var intWidth = (intImageWidth + (settings.containerBorderSize * 2)); // Plus the image´s width and the left and right padding value
+ var intHeight = (intImageHeight + (settings.containerBorderSize * 2)); // Plus the image´s height and the left and right padding value
+ // Diferences
+ var intDiffW = intCurrentWidth - intWidth;
+ var intDiffH = intCurrentHeight - intHeight;
+ // Perfomance the effect
+ $('#lightbox-container-image-box').animate({ width: intWidth, height: intHeight },settings.containerResizeSpeed,function() { _show_image(); });
+ if ( ( intDiffW == 0 ) && ( intDiffH == 0 ) ) {
+ if ( $.browser.msie ) {
+ ___pause(250);
+ } else {
+ ___pause(100);
+ }
+ }
+ $('#lightbox-container-image-data-box').css({ width: intImageWidth });
+ $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ height: intImageHeight + (settings.containerBorderSize * 2) });
+ };
+ /**
+ * Show the prepared image
+ *
+ */
+ function _show_image() {
+ $('#lightbox-loading').hide();
+ $('#lightbox-image').fadeIn(function() {
+ _show_image_data();
+ _set_navigation();
+ });
+ _preload_neighbor_images();
+ };
+ /**
+ * Show the image information
+ *
+ */
+ function _show_image_data() {
+ $('#lightbox-container-image-data-box').slideDown('fast');
+ $('#lightbox-image-details-caption').hide();
+ if ( settings.imageArray[settings.activeImage][1] ) {
+ $('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();
+ }
+ // If we have a image set, display 'Image X of X'
+ if ( settings.imageArray.length > 1 ) {
+ $('#lightbox-image-details-currentNumber').html(settings.txtImage + ' ' + ( settings.activeImage + 1 ) + ' ' + settings.txtOf + ' ' + settings.imageArray.length).show();
+ }
+ }
+ /**
+ * Display the button navigations
+ *
+ */
+ function _set_navigation() {
+ $('#lightbox-nav').show();
+
+ // Instead to define this configuration in CSS file, we define here. And it´s need to IE. Just.
+ $('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
+
+ // Show the prev button, if not the first image in set
+ if ( settings.activeImage != 0 ) {
+ if ( settings.fixedNavigation ) {
+ $('#lightbox-nav-btnPrev').css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' })
+ .unbind()
+ .bind('click',function() {
+ settings.activeImage = settings.activeImage - 1;
+ _set_image_to_view();
+ return false;
+ });
+ } else {
+ // Show the images button for Next buttons
+ $('#lightbox-nav-btnPrev').unbind().hover(function() {
+ $(this).css({ 'background' : 'url(' + settings.imageBtnPrev + ') left 15% no-repeat' });
+ },function() {
+ $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
+ }).show().bind('click',function() {
+ settings.activeImage = settings.activeImage - 1;
+ _set_image_to_view();
+ return false;
+ });
+ }
+ }
+
+ // Show the next button, if not the last image in set
+ if ( settings.activeImage != ( settings.imageArray.length -1 ) ) {
+ if ( settings.fixedNavigation ) {
+ $('#lightbox-nav-btnNext').css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' })
+ .unbind()
+ .bind('click',function() {
+ settings.activeImage = settings.activeImage + 1;
+ _set_image_to_view();
+ return false;
+ });
+ } else {
+ // Show the images button for Next buttons
+ $('#lightbox-nav-btnNext').unbind().hover(function() {
+ $(this).css({ 'background' : 'url(' + settings.imageBtnNext + ') right 15% no-repeat' });
+ },function() {
+ $(this).css({ 'background' : 'transparent url(' + settings.imageBlank + ') no-repeat' });
+ }).show().bind('click',function() {
+ settings.activeImage = settings.activeImage + 1;
+ _set_image_to_view();
+ return false;
+ });
+ }
+ }
+ // Enable keyboard navigation
+ _enable_keyboard_navigation();
+ }
+ /**
+ * Enable a support to keyboard navigation
+ *
+ */
+ function _enable_keyboard_navigation() {
+ $(document).keydown(function(objEvent) {
+ _keyboard_action(objEvent);
+ });
+ }
+ /**
+ * Disable the support to keyboard navigation
+ *
+ */
+ function _disable_keyboard_navigation() {
+ $(document).unbind();
+ }
+ /**
+ * Perform the keyboard actions
+ *
+ */
+ function _keyboard_action(objEvent) {
+ // To ie
+ if ( objEvent == null ) {
+ keycode = event.keyCode;
+ escapeKey = 27;
+ // To Mozilla
+ } else {
+ keycode = objEvent.keyCode;
+ escapeKey = objEvent.DOM_VK_ESCAPE;
+ }
+ // Get the key in lower case form
+ key = String.fromCharCode(keycode).toLowerCase();
+ // Verify the keys to close the ligthBox
+ if ( ( key == settings.keyToClose ) || ( key == 'x' ) || ( keycode == escapeKey ) ) {
+ _finish();
+ }
+ // Verify the key to show the previous image
+ if ( ( key == settings.keyToPrev ) || ( keycode == 37 ) ) {
+ // If we´re not showing the first image, call the previous
+ if ( settings.activeImage != 0 ) {
+ settings.activeImage = settings.activeImage - 1;
+ _set_image_to_view();
+ _disable_keyboard_navigation();
+ }
+ }
+ // Verify the key to show the next image
+ if ( ( key == settings.keyToNext ) || ( keycode == 39 ) ) {
+ // If we´re not showing the last image, call the next
+ if ( settings.activeImage != ( settings.imageArray.length - 1 ) ) {
+ settings.activeImage = settings.activeImage + 1;
+ _set_image_to_view();
+ _disable_keyboard_navigation();
+ }
+ }
+ }
+ /**
+ * Preload prev and next images being showed
+ *
+ */
+ function _preload_neighbor_images() {
+ if ( (settings.imageArray.length -1) > settings.activeImage ) {
+ objNext = new Image();
+ objNext.src = settings.imageArray[settings.activeImage + 1][0];
+ }
+ if ( settings.activeImage > 0 ) {
+ objPrev = new Image();
+ objPrev.src = settings.imageArray[settings.activeImage -1][0];
+ }
+ }
+ /**
+ * Remove jQuery lightBox plugin HTML markup
+ *
+ */
+ function _finish() {
+ $('#jquery-lightbox').remove();
+ $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
+ // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
+ $('embed, object, select').css({ 'visibility' : 'visible' });
+ }
+ /**
+ / THIRD FUNCTION
+ * getPageSize() by quirksmode.com
+ *
+ * @return Array Return an array with page width, height and window width, height
+ */
+ function ___getPageSize() {
+ var xScroll, yScroll;
+ if (window.innerHeight && window.scrollMaxY) {
+ xScroll = window.innerWidth + window.scrollMaxX;
+ yScroll = window.innerHeight + window.scrollMaxY;
+ } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
+ xScroll = document.body.scrollWidth;
+ yScroll = document.body.scrollHeight;
+ } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
+ xScroll = document.body.offsetWidth;
+ yScroll = document.body.offsetHeight;
+ }
+ var windowWidth, windowHeight;
+ if (self.innerHeight) { // all except Explorer
+ if(document.documentElement.clientWidth){
+ windowWidth = document.documentElement.clientWidth;
+ } else {
+ windowWidth = self.innerWidth;
+ }
+ windowHeight = self.innerHeight;
+ } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
+ windowWidth = document.documentElement.clientWidth;
+ windowHeight = document.documentElement.clientHeight;
+ } else if (document.body) { // other Explorers
+ windowWidth = document.body.clientWidth;
+ windowHeight = document.body.clientHeight;
+ }
+ // for small pages with total height less then height of the viewport
+ if(yScroll < windowHeight){
+ pageHeight = windowHeight;
+ } else {
+ pageHeight = yScroll;
+ }
+ // for small pages with total width less then width of the viewport
+ if(xScroll < windowWidth){
+ pageWidth = xScroll;
+ } else {
+ pageWidth = windowWidth;
+ }
+ arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
+ return arrayPageSize;
+ };
+ /**
+ / THIRD FUNCTION
+ * getPageScroll() by quirksmode.com
+ *
+ * @return Array Return an array with x,y page scroll values.
+ */
+ function ___getPageScroll() {
+ var xScroll, yScroll;
+ if (self.pageYOffset) {
+ yScroll = self.pageYOffset;
+ xScroll = self.pageXOffset;
+ } else if (document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
+ yScroll = document.documentElement.scrollTop;
+ xScroll = document.documentElement.scrollLeft;
+ } else if (document.body) {// all other Explorers
+ yScroll = document.body.scrollTop;
+ xScroll = document.body.scrollLeft;
+ }
+ arrayPageScroll = new Array(xScroll,yScroll);
+ return arrayPageScroll;
+ };
+ /**
+ * Stop the code execution from a escified time in milisecond
+ *
+ */
+ function ___pause(ms) {
+ var date = new Date();
+ curDate = null;
+ do { var curDate = new Date(); }
+ while ( curDate - date < ms);
+ };
+ // Return the jQuery object for chaining. The unbind method is used to avoid click conflict when the plugin is called more than once
+ return this.unbind('click').click(_initialize);
+ };
+})(jQuery); // Call and execute the function immediately passing the jQuery object
\ No newline at end of file
diff --git a/js/main.js b/js/main.js
index ee6e6d5..6c18f57 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,309 +1,355 @@
$(document).ready(function(){
// Load Google Map
loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
- // Get the spots and update the slider
- $(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
- $.getJSON("json/group"+this.id.substr(this.id.lastIndexOf("_")+1)+".json", setSpot);
+ // Get the spots and update the slider
+ $(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
+ curGroup = this.id.substr(this.id.lastIndexOf("_")+1);
+ $.getJSON("json/group"+curGroup+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
+ curGroup = 1;
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
- var spotHtml = '<div class="Panel" id="panel_';
- spotHtml += (entryIdx+1);
- spotHtml += '"><div class="inside"><img src="';
- spotHtml += entry['image_url'];
- spotHtml += '" alt="';
- spotHtml += entry['description'];
- spotHtml += '" /><span>';
- spotHtml += entry['name'];
- spotHtml += '</span></div></div>';
- //alert(spotHtml);
- $('.ScrollContainer').append(spotHtml);
-
- // Set Lat & Lng info
- $("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
- $("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
- $("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
+ var spotHtml = '<div class="Panel" id="panel_';
+ spotHtml += (entryIdx+1);
+ spotHtml += '"><div class="inside"><img src="';
+ spotHtml += entry['image_url'];
+ spotHtml += '" alt="';
+ spotHtml += entry['description'];
+ spotHtml += '" /><span>';
+ spotHtml += entry['name'];
+ spotHtml += '</span></div></div>';
+ //alert(spotHtml);
+ $('.ScrollContainer').append(spotHtml);
+
+ // Set Lat & Lng info
+ $("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
+ $("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
+ $("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
- console.debug("calling initSlider");
+ //console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
- console.debug("calling moveMap");
+ //console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
- console.debug("==>"+$(".ScrollContainer").css("left"));
+ //console.debug("==>"+$(".ScrollContainer").css("left"));
if($("#slider").data("currentlyMoving")==true)
{
$("#slider").data("currentlyMoving", false);
- console.debug("Calling moveMap after animation");
+ //console.debug("Calling moveMap after animation");
moveMap();
}
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
map = new GMap2(document.getElementById("hk_map"));
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
- console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
+ //console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
zoom = parseInt(zoom);
map.setZoom(zoom);
//map.panTo(new GLatLng(lat,lng));
map.setCenter(new GLatLng(lat,lng));
// Show Marker and the Info window
showMarkerAndInfo(lat,lng, zoom);
}
return true;
}
/*
Show Maker on the map and show the info window.
*/
function showMarkerAndInfo(lat, lng, zoom){
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
map.closeInfoWindow();
var marker = markermanager.getMarker(lat,lng, zoom);
markermanager.removeMarker(marker);
markermanager.addMarker(marker,zoom);
//console.debug(markermanager.getMarkerCount(zoom));
markermanager.refresh();
var $curPanelImg = $("#panel_"+curPanel+" img");
// Set the click event for the marker
//GEvent.addListener(marker, "click", function(){
// marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//});
- marker.bindInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
+ marker.bindInfoWindowHtml("<div style=\"font-size:11px\"><a href=\"#\" onclick=\'getPhotos("+curGroup+","+curPanel+");return false;\'><img id=\"info_img\" src=\""+$curPanelImg.attr("src")+"\" width=\"150\"/><br/>ç¹å»æ¥çç¸å</a></div>");
- console.debug($curPanelImg.attr("src"));
+ //console.debug($curPanelImg.attr("src"));
//marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
//GEvent.trigger(marker, "click");
setTimeout(function(){GEvent.trigger(marker, "click");},1000);
return true;
}
+/*
+ Get the photos when the img in infowindow is clicked.
+*/
+function getPhotos(group, spot){
+ //console.debug("Enter getPhotos");
+ // Show waiting notice
+ $("#notice").empty().append("æ£å¨è·åç¸åï¼è¯·ç¨åã").css("display","inherit");
+ //console.debug("Get the photos");
+ //console.debug('json/photos_'+group+'_'+spot+'.json');
+ // Get the photos
+ $.getJSON('json/photos_'+group+'_'+spot+'.json', showLightBox);
+
+}
+
+/*
+ Show light box for the photos.
+*/
+function showLightBox(data){
+
+ //console.debug("Enter showLightBox");
+ $("#notice").empty().css("display","none");
+
+ // Remove the previous photos
+ $("#gallery").empty();
+ // Add the photos
+ $.each(data, function(entryIdx, entry){
+ var galleryHtml = "<a href=\"";
+ galleryHtml+=entry['photo_big'];
+ galleryHtml+="\" title=\"";
+ galleryHtml+= entry['title'];
+ galleryHtml+="\"><img src=\"";
+ galleryHtml+=entry['photo_small'];
+ galleryHtml+="\" width=\"72\" height=\"72\" alt=\"\" /></a>";
+
+ //console.debug(""+galleryHtml);
+ $("#gallery").append(galleryHtml);
+ });
+
+ // Trigger the light box
+ $('#gallery a').lightBox({txtImage:'å¾ç',txtOf:'/'});
+ $("#gallery a:eq(0)").trigger("click");
+}
+
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
+var curGroup = 0;
// The map
var map;
var markermanager;
\ No newline at end of file
diff --git a/json/group1.json b/json/group1.json
index c9461c2..97b9a27 100644
--- a/json/group1.json
+++ b/json/group1.json
@@ -1,119 +1,119 @@
[
{
"id": "1",
"name": "ä¸å鍿±½è½¦ç«",
"image_url": "photo/dayone/zhm_bus_station.jpg",
"description": "ä¹åæºåºå¤§å·´",
"latitude": "32.00882197319293",
"longitude": "118.7757682800293",
"zoom": "15"
},
{
"id": "2",
"name": "ç¦å£æºåº",
"image_url": "photo/dayone/lk_airport.jpg",
"description": "å飿º",
"latitude": "31.78472759839612",
"longitude": "118.86876583099365",
"zoom": "15"
},
{
"id": "3",
"name": "广å·",
"image_url": "photo/dayone/guangzhou.jpg",
"description": "广å·",
"latitude": "23.385591961067536",
"longitude": "113.30517768859863",
"zoom": "15"
},
{
"id": "4",
"name": "éç´«è广åº",
"image_url": "photo/dayone/jzj_square.jpg",
"description": "éç´«è广åº",
"latitude": "22.2843412100226",
"longitude": "114.17347848415375",
"zoom": "17"
},
{
"id": "5",
"name": "ä¼å±ä¸å¿",
"image_url": "photo/dayone/meeting_center.jpg",
"description": "ä¼å±ä¸å¿",
"latitude": "22.28282725263975",
"longitude": "114.17293131351471",
"zoom": "17"
},
{
"id": "6",
"name": "ç«æ³ä¼å¤§æ¥¼",
"image_url": "photo/dayone/law.jpg",
"description": "ç«æ³ä¼å¤§æ¥¼",
"latitude": "22.28107997652926",
"longitude": "114.16016399860382",
"zoom": "17"
},
{
"id": "7",
"name": "ä¸å½é¶è¡",
"image_url": "photo/dayone/cob.jpg",
"description": "ä¸å½é¶è¡",
"latitude": "22.280380067189995",
"longitude": "114.16034370660782",
"zoom": "17"
},
{
"id": "8",
"name": "礼宾åºç¹åº",
"image_url": "photo/dayone/libinfu.jpg",
"description": "礼宾åºç¹åº",
"latitude": "22.27875934169057",
"longitude": "114.15763199329376",
"zoom": "18"
},
{
"id": "9",
"name": "æ¿åºæ»é¨",
"image_url": "photo/dayone/gov.jpg",
"description": "æ¿åºæ»é¨",
"latitude": "22.27888592276567",
"longitude": "114.15872633457184",
"zoom": "17"
},
{
"id": "10",
"name": "æµ·æ´å
Œ",
"image_url": "photo/dayone/sea_park.jpg",
"description": "æµ·æ´å
Œ",
"latitude": "22.24527090215842",
"longitude": "114.17679369449615",
"zoom": "17"
},
{
"id": "11",
"name": "æµ
æ°´æ¹¾",
"image_url": "photo/dayone/repulse_bay.jpg",
"description": "æµ
æ°´æ¹¾",
"latitude": "22.237589598654903",
"longitude": "114.19914722442627",
"zoom": "17"
},
{
"id": "12",
"name": "太平山",
"image_url": "photo/dayone/taiping.jpg",
"description": "太平山",
"latitude": "22.27039232678379",
"longitude": "114.15189743041992",
"zoom": "17"
},
{
"id": "13",
"name": "宾é¦",
"image_url": "photo/dayone/hotel.jpg",
"description": "宾é¦",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.457657550575618",
+ "longitude": "114.00574922561646",
+ "zoom": "15"
}
-]
\ No newline at end of file
+]
diff --git a/json/group2.json b/json/group2.json
index 8642c85..264fe55 100644
--- a/json/group2.json
+++ b/json/group2.json
@@ -1,101 +1,92 @@
[
{
"id": "14",
"name": "é»å¤§ä»åº",
"image_url": "photo/daytwo/hdx.jpg",
"description": "é»å¤§ä»åº",
"latitude": "22.343268556904317",
"longitude": "114.19339656829834",
"zoom": "15"
},
{
"id": "15",
"name": "ç å®å±ç¤ºä¸å¿",
"image_url": "photo/daytwo/jewelry.jpg",
"description": "ç å®å±ç¤ºä¸å¿",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.32662115005807",
+ "longitude": "114.2052572965622",
+ "zoom": "17"
},
{
"id": "16",
"name": "ç¾è´§åº",
"image_url": "photo/daytwo/store.jpg",
"description": "ç¾è´§åº",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.407854560288325",
+ "longitude": "114.15138244628906",
+ "zoom": "10"
},
{
"id": "17",
"name": "åé¤",
"image_url": "photo/daytwo/lunch.jpg",
"description": "åé¤",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.407854560288325",
+ "longitude": "114.15138244628906",
+ "zoom": "10"
},
{
"id": "18",
"name": "DFS",
"image_url": "photo/daytwo/dfs.jpg",
"description": "DFS",
"latitude": "22.29681708367642",
"longitude": "114.16930228471756",
"zoom": "18"
},
{
"id": "19",
"name": "æå
大é",
"image_url": "photo/daytwo/start.jpg",
"description": "æå
大é",
"latitude": "22.293960661077",
"longitude": "114.17190670967102",
"zoom": "18"
},
{
"id": "20",
"name": "å°æ²åæåä¸å¿",
"image_url": "photo/daytwo/jsz.jpg",
"description": "å°æ²åæåä¸å¿",
"latitude": "22.29335015831739",
"longitude": "114.16998624801636",
"zoom": "17"
},
{
"id": "21",
"name": "大鿥¼",
"image_url": "photo/daytwo/tower.jpg",
"description": "大鿥¼",
"latitude": "22.2933997927877",
"longitude": "114.16951149702072",
"zoom": "18"
},
{
"id": "22",
"name": "æµ·é²å¤§é¤",
"image_url": "photo/daytwo/sea_food.jpg",
"description": "æµ·é²å¤§é¤",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.407854560288325",
+ "longitude": "114.15138244628906",
+ "zoom": "10"
},
{
"id": "23",
"name": "ç»´å¤å©äºæ¸¯",
"image_url": "photo/daytwo/victoria.jpg",
"description": "ç»´å¤å©äºæ¸¯",
"latitude": "22.29529085297506",
"longitude": "114.16202545166016",
"zoom": "13"
- },
- {
- "id": "25",
- "name": "宾é¦2",
- "image_url": "photo/daytwo/hotel.jpg",
- "description": "宾é¦2",
- "latitude": "",
- "longitude": "",
- "zoom": ""
}
-]
\ No newline at end of file
+]
diff --git a/json/group4.json b/json/group4.json
index 3410e1a..e623074 100644
--- a/json/group4.json
+++ b/json/group4.json
@@ -1,92 +1,74 @@
[
{
"id": "27",
"name": "大ä¸å·´çå",
"image_url": "photo/dayfour/dsb.jpg",
"description": "大ä¸å·´çå",
"latitude": "22.197420997723434",
"longitude": "113.54090631008148",
"zoom": "18"
},
{
"id": "28",
"name": "å¦éåº",
"image_url": "photo/dayfour/mgm.jpg",
"description": "å¦éåº",
"latitude": "22.18748446661309",
"longitude": "113.5330581665039",
"zoom": "15"
},
{
"id": "29",
"name": "è§é³å",
"image_url": "photo/dayfour/gyx.jpg",
"description": "è§é³å",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
},
{
"id": "30",
"name": "主æå±±",
"image_url": "photo/dayfour/zjs.jpg",
"description": "主æå±±",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
},
{
"id": "31",
"name": "è²è±å¹¿åº",
"image_url": "photo/dayfour/lotus.jpg",
"description": "è²è±å¹¿åº",
- "latitude": "",
- "longitude": "",
- "zoom": ""
- },
- {
- "id": "32",
- "name": "åé¤4",
- "image_url": "photo/dayfour/lunch.jpg",
- "description": "åé¤4",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
},
{
"id": "33",
"name": "ç¯å²æ¸¸",
"image_url": "photo/dayfour/round.jpg",
"description": "ç¯å²æ¸¸",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
},
{
"id": "34",
"name": "éè´æ¾³é¨æä¿¡ç¤¼å",
"image_url": "photo/dayfour/sx.jpg",
"description": "éè´æ¾³é¨æä¿¡ç¤¼å",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
},
{
"id": "35",
"name": "娱ä¹åº",
"image_url": "photo/dayfour/entertain.jpg",
"description": "娱ä¹åº",
- "latitude": "",
- "longitude": "",
- "zoom": ""
- },
- {
- "id": "36",
- "name": "宾é¦4",
- "image_url": "photo/dayfour/hotel.jpg",
- "description": "宾é¦4",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.190981331530466",
+ "longitude": "113.55125427246094",
+ "zoom": "16"
}
-]
\ No newline at end of file
+]
diff --git a/json/group5.json b/json/group5.json
index 90c6d2b..44d2fb5 100644
--- a/json/group5.json
+++ b/json/group5.json
@@ -1,56 +1,38 @@
[
{
"id": "43",
"name": "æ±åå
³",
"image_url": "photo/dayfive/gbg.jpg",
"description": "æ±åå
³",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "latitude": "22.22443556792428",
+ "longitude": "113.56189727783203",
+ "zoom": "12"
},
{
"id": "44",
"name": "æ
侣路",
"image_url": "photo/dayfive/lover.jpg",
"description": "æ
侣路",
"latitude": "22.26129750157242",
"longitude": "113.5856294631958",
"zoom": "14"
},
{
"id": "45",
"name": "æ¸å¥³å",
"image_url": "photo/dayfive/fisher.jpg",
"description": "æ¸å¥³å",
"latitude": "22.261793959247537",
"longitude": "113.58962059020996",
"zoom": "15"
},
{
- "id": "46",
- "name": "åé¤5",
- "image_url": "photo/dayfive/lunch.jpg",
- "description": "åé¤5",
- "latitude": "",
- "longitude": "",
- "zoom": ""
- },
- {
- "id": "47",
- "name": "ç¾è´§åº5",
- "image_url": "photo/dayfive/store.jpg",
- "description": "ç¾è´§åº5",
- "latitude": "",
- "longitude": "",
- "zoom": ""
- },
- {
- "id": "48",
- "name": "å¹¿å·æºåº",
- "image_url": "photo/dayfive/gz_airport.jpg",
- "description": "å¹¿å·æºåº",
- "latitude": "",
- "longitude": "",
- "zoom": ""
+ "id": "49",
+ "name": "å京æºåº",
+ "image_url": "photo/dayfive/nkg.jpg",
+ "description": "å京æºåº",
+ "latitude": "31.78472759839612",
+ "longitude": "118.86876583099365",
+ "zoom": "15"
}
-]
\ No newline at end of file
+]
diff --git a/json/photos_1_1.json b/json/photos_1_1.json
new file mode 100644
index 0000000..a8013d2
--- /dev/null
+++ b/json/photos_1_1.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/zhm_bus_station.jpg",
+ "title": "å¾çæ¥èªç½ç»",
+ "photo_small": "photo/dayone/zhm_bus_station.jpg"
+ }
+]
diff --git a/json/photos_1_10.json b/json/photos_1_10.json
new file mode 100644
index 0000000..40b5033
--- /dev/null
+++ b/json/photos_1_10.json
@@ -0,0 +1,72 @@
+[
+ {
+ "photo_big": "photo/dayone/sea_park.jpg",
+ "title": "æµ·æ´å
¬å大é¨",
+ "photo_small": "photo/dayone/sea_park.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/mm.jpg",
+ "title": "好ä¸å®¹ææ¾å°ä¸ä¸ªæ²¡äººçå°æ¹",
+ "photo_small": "photo/dayone/sea_park/mm.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/zaji.jpg",
+ "title": "ææè¡¨æ¼",
+ "photo_small": "photo/dayone/sea_park/zaji.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/qiqiu.jpg",
+ "title": "大æ°ç",
+ "photo_small": "photo/dayone/sea_park/qiqiu.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/panda.jpg",
+ "title": "çç«é¦",
+ "photo_small": "photo/dayone/sea_park/panda.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/lanche.jpg",
+ "title": "æµ·æ´å
¬åçç¼è½¦åé¿åå¤",
+ "photo_small": "photo/dayone/sea_park/lanche.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/haitun.jpg",
+ "title": "è§çæµ·è±è¡¨æ¼",
+ "photo_small": "photo/dayone/sea_park/haitun.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/haiyang.jpg",
+ "title": "廿µ·æ´é¦çæµ·æ´çç©",
+ "photo_small": "photo/dayone/sea_park/haiyang.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/star.jpg",
+ "title": "æµ·æ",
+ "photo_small": "photo/dayone/sea_park/star.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/nimo.jpg",
+ "title": "å°ä¸é±¼å°¼è«",
+ "photo_small": "photo/dayone/sea_park/nimo.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/evil.jpg",
+ "title": "å°å¤é½æ¯é鬼鱼",
+ "photo_small": "photo/dayone/sea_park/evil.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/shuimu.jpg",
+ "title": "æ¼äº®çæ°´æ¯é¦",
+ "photo_small": "photo/dayone/sea_park/shuimu.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/shuimuyi.jpg",
+ "title": "æ°´æ¯ä¸åå½±",
+ "photo_small": "photo/dayone/sea_park/shuimuyi.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/sea_park/fish.jpg",
+ "title": "好å¤é±¼",
+ "photo_small": "photo/dayone/sea_park/fish.jpg"
+ }
+]
diff --git a/json/photos_1_11.json b/json/photos_1_11.json
new file mode 100644
index 0000000..a4dac5d
--- /dev/null
+++ b/json/photos_1_11.json
@@ -0,0 +1,17 @@
+[
+ {
+ "photo_big": "photo/dayone/repulse_bay.jpg",
+ "title": "æä¸å»çæµ
æ°´æ¹¾ï¼ç½å¤©çç
§çåªè½ç½ä¸çäº",
+ "photo_small": "photo/dayone/repulse_bay.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/repulse_bay/night.jpg",
+ "title": "æµ
æ°´æ¹¾å¤æ¯",
+ "photo_small": "photo/dayone/repulse_bay/night.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/repulse_bay/love.jpg",
+ "title": "â¦â¦",
+ "photo_small": "photo/dayone/repulse_bay/love.jpg"
+ }
+]
diff --git a/json/photos_1_12.json b/json/photos_1_12.json
new file mode 100644
index 0000000..a455733
--- /dev/null
+++ b/json/photos_1_12.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/dayone/taiping.jpg",
+ "title": "å°å¤ªå¹³å±±é½æ¯ç夿¯å§",
+ "photo_small": "photo/dayone/taiping.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/taiping/night.jpg",
+ "title": "太平山ç夿¯ï¼æç
§æ¸¯å¸20å",
+ "photo_small": "photo/dayone/taiping/night.jpg"
+ }
+]
diff --git a/json/photos_1_13.json b/json/photos_1_13.json
new file mode 100644
index 0000000..6ca20a1
--- /dev/null
+++ b/json/photos_1_13.json
@@ -0,0 +1,22 @@
+[
+ {
+ "photo_big": "photo/dayone/hotel.jpg",
+ "title": "ä½çæ¯æåè¯çäºæçº§é
åºï¼æµ·é¸ãhttp://www.harbour-plaza.com/sc/index.aspx",
+ "photo_small": "photo/dayone/hotel.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/hotel/hotel1.jpg",
+ "title": "å±
ç¶æ¯ä¸å®¤ä¸å
ä¸å¨ä¸å«",
+ "photo_small": "photo/dayone/hotel/hotel1.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/hotel/hotel2.jpg",
+ "title": "é
åºå¨æ¿",
+ "photo_small": "photo/dayone/hotel/hotel2.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/hotel/hotel3.jpg",
+ "title": "é
åºçªæ·ä¸åæ ç馿¸¯å¤æ¯",
+ "photo_small": "photo/dayone/hotel/hotel3.jpg"
+ }
+]
diff --git a/json/photos_1_2.json b/json/photos_1_2.json
new file mode 100644
index 0000000..e2693c5
--- /dev/null
+++ b/json/photos_1_2.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/dayone/lk_airport.jpg",
+ "title": "å¾çæ¥èªç½ç»",
+ "photo_small": "photo/dayone/lk_airport.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/lk_airport/lk_airport_inside.jpg",
+ "title": "ç¡ææ£æµæ¥å°æºåºï¼ç¨å°ææºæäºä¸å¼ ",
+ "photo_small": "photo/dayone/lk_airport/lk_airport_inside.jpg"
+ }
+]
diff --git a/json/photos_1_3.json b/json/photos_1_3.json
new file mode 100644
index 0000000..ed5d02a
--- /dev/null
+++ b/json/photos_1_3.json
@@ -0,0 +1,17 @@
+[
+ {
+ "photo_big": "photo/dayone/guangzhou.jpg",
+ "title": "广å·ç½äºæºåºï¼å¾çæ¥èªç½ç»",
+ "photo_small": "photo/dayone/guangzhou.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/guangzhou/tower.jpg",
+ "title": "è¿ä¸ªä¸è¥¿æ³ææ²¡ææå°",
+ "photo_small": "photo/dayone/guangzhou/tower.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/guangzhou/gz_airport.jpg",
+ "title": "åªæ¯å¨è¿æºåºçç ´è½¦ä¸æäºä¸å¼ ",
+ "photo_small": "photo/dayone/guangzhou/gz_airport.jpg"
+ }
+]
diff --git a/json/photos_1_4.json b/json/photos_1_4.json
new file mode 100644
index 0000000..474bcf7
--- /dev/null
+++ b/json/photos_1_4.json
@@ -0,0 +1,37 @@
+[
+ {
+ "photo_big": "photo/dayone/jzj_square.jpg",
+ "title": "è¿ä¸ªä¼¼ä¹æç¹é¾æï¼äººæå¾å¤ªä¸ï¼è¿æ¯ç¨ç½ä¸çå§",
+ "photo_small": "photo/dayone/jzj_square.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/jzj.jpg",
+ "title": "ä¼å±ä¸å¿å±æªä¸è§",
+ "photo_small": "photo/dayone/jzj/jzj.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/ship.jpg",
+ "title": "è½®è¹",
+ "photo_small": "photo/dayone/jzj/ship.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/sea_building.jpg",
+ "title": "饿坹岏",
+ "photo_small": "photo/dayone/jzj/sea_building.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/return.jpg",
+ "title": "馿¸¯åå½çºªå¿µç¢",
+ "photo_small": "photo/dayone/jzj/return.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/mm.jpg",
+ "title": "æå¼ ç念ç
§",
+ "photo_small": "photo/dayone/jzj/mm.jpg"
+ },
+ {
+ "photo_big": "photo/dayone/jzj/cut.jpg",
+ "title": "åªå½±",
+ "photo_small": "photo/dayone/jzj/cut.jpg"
+ }
+]
diff --git a/json/photos_1_5.json b/json/photos_1_5.json
new file mode 100644
index 0000000..985b9f9
--- /dev/null
+++ b/json/photos_1_5.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/meeting_center.jpg",
+ "title": "ä¼å±ä¸å¿å
³é¨å¤§åï¼æ²¡æè¿å»",
+ "photo_small": "photo/dayone/meeting_center.jpg"
+ }
+]
diff --git a/json/photos_1_6.json b/json/photos_1_6.json
new file mode 100644
index 0000000..b3b3e67
--- /dev/null
+++ b/json/photos_1_6.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/law.jpg",
+ "title": "被忽æ äºï¼æ ¹æ¬å°±æ²¡å»",
+ "photo_small": "photo/dayone/law.jpg"
+ }
+]
diff --git a/json/photos_1_7.json b/json/photos_1_7.json
new file mode 100644
index 0000000..b2fbeab
--- /dev/null
+++ b/json/photos_1_7.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/cob.jpg",
+ "title": "被忽æ äºï¼æ ¹æ¬å°±æ²¡å»",
+ "photo_small": "photo/dayone/cob.jpg"
+ }
+]
diff --git a/json/photos_1_8.json b/json/photos_1_8.json
new file mode 100644
index 0000000..6f98813
--- /dev/null
+++ b/json/photos_1_8.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/libinfu.jpg",
+ "title": "被忽æ äºï¼æ ¹æ¬å°±æ²¡å»",
+ "photo_small": "photo/dayone/libinfu.jpg"
+ }
+]
diff --git a/json/photos_1_9.json b/json/photos_1_9.json
new file mode 100644
index 0000000..afb1fdc
--- /dev/null
+++ b/json/photos_1_9.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayone/gov.jpg",
+ "title": "被忽æ äºï¼æ ¹æ¬å°±æ²¡å»",
+ "photo_small": "photo/dayone/gov.jpg"
+ }
+]
diff --git a/json/photos_2_1.json b/json/photos_2_1.json
new file mode 100644
index 0000000..2b459c1
--- /dev/null
+++ b/json/photos_2_1.json
@@ -0,0 +1,17 @@
+[
+ {
+ "photo_big": "photo/daytwo/hdx.jpg",
+ "title": "é»å¤§ä»åºç°å¸¸å°",
+ "photo_small": "photo/daytwo/hdx.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/hdx/hdx1.jpg",
+ "title": "è·è±æ± ",
+ "photo_small": "photo/daytwo/hdx/hdx1.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/hdx/hdx2.jpg",
+ "title": "æäººç§é¦æäººæç
§",
+ "photo_small": "photo/daytwo/hdx/hdx2.jpg"
+ }
+]
diff --git a/json/photos_2_10.json b/json/photos_2_10.json
new file mode 100644
index 0000000..3e81f1b
--- /dev/null
+++ b/json/photos_2_10.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/daytwo/victoria.jpg",
+ "title": "å䏿¡ç ´è¹å¤æ¸¸ç»´å¤å©äºæ¸¯",
+ "photo_small": "photo/daytwo/victoria.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/victoria/victoria.jpg",
+ "title": "å»çç¸æºæä¸åºææï¼èä¸è¹é¢ 徿æ³å",
+ "photo_small": "photo/daytwo/victoria/victoria.jpg"
+ }
+]
diff --git a/json/photos_2_2.json b/json/photos_2_2.json
new file mode 100644
index 0000000..918a9b4
--- /dev/null
+++ b/json/photos_2_2.json
@@ -0,0 +1,17 @@
+[
+ {
+ "photo_big": "photo/daytwo/jewelry.jpg",
+ "title": "导游带å»çå°æ¹åä¸ä¸è¦ä¹°ä¸è¥¿ï¼",
+ "photo_small": "photo/daytwo/jewelry.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/jewelry/kaixuan.jpg",
+ "title": "åä¸ï¼",
+ "photo_small": "photo/daytwo/jewelry/kaixuan.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/jewelry/kaixuan1.jpg",
+ "title": "ååä¸!",
+ "photo_small": "photo/daytwo/jewelry/kaixuan1.jpg"
+ }
+]
diff --git a/json/photos_2_3.json b/json/photos_2_3.json
new file mode 100644
index 0000000..7f0c447
--- /dev/null
+++ b/json/photos_2_3.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/daytwo/store.jpg",
+ "title": "被导游带å»ä¸ä¸ªçµå¨åï¼",
+ "photo_small": "photo/daytwo/store.jpg"
+ }
+]
diff --git a/json/photos_2_4.json b/json/photos_2_4.json
new file mode 100644
index 0000000..ac0c306
--- /dev/null
+++ b/json/photos_2_4.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/daytwo/lunch.jpg",
+ "title": "æ¯ä¸é¡¿é¥å°±å妿 ¡é¨å¤çå¤§ææ¡£ä¸æ ·ï¼",
+ "photo_small": "photo/daytwo/lunch.jpg"
+ }
+]
diff --git a/json/photos_2_5.json b/json/photos_2_5.json
new file mode 100644
index 0000000..51354a6
--- /dev/null
+++ b/json/photos_2_5.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/daytwo/dfs.jpg",
+ "title": "DFSéé¢ä¸æ ·ä¸è¥¿é½ä¹°ä¸èµ·ï¼",
+ "photo_small": "photo/daytwo/dfs.jpg"
+ }
+]
diff --git a/json/photos_2_6.json b/json/photos_2_6.json
new file mode 100644
index 0000000..822e5c0
--- /dev/null
+++ b/json/photos_2_6.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/daytwo/start.jpg",
+ "title": "æå
大éåªå¾
äº5åé",
+ "photo_small": "photo/daytwo/start.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/start/start.jpg",
+ "title": "导游说ï¼èµ°å°æå°é¾åç«å»è¿åï¼",
+ "photo_small": "photo/daytwo/start/start.jpg"
+ }
+]
diff --git a/json/photos_2_7.json b/json/photos_2_7.json
new file mode 100644
index 0000000..6f8cb41
--- /dev/null
+++ b/json/photos_2_7.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/daytwo/jsz.jpg",
+ "title": "被忽æ äºï¼æ ¹æ¬å°±æ²¡å»",
+ "photo_small": "photo/daytwo/jsz.jpg"
+ }
+]
diff --git a/json/photos_2_8.json b/json/photos_2_8.json
new file mode 100644
index 0000000..7e33afd
--- /dev/null
+++ b/json/photos_2_8.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/daytwo/tower.jpg",
+ "title": "忬¡è¢«å¿½æ äº",
+ "photo_small": "photo/daytwo/tower.jpg"
+ },
+ {
+ "photo_big": "photo/daytwo/tower/tower.jpg",
+ "title": "ç½ä¸çå
¨æ¯å¾",
+ "photo_small": "photo/daytwo/tower/tower.jpg"
+ }
+]
diff --git a/json/photos_2_9.json b/json/photos_2_9.json
new file mode 100644
index 0000000..5e5cfc5
--- /dev/null
+++ b/json/photos_2_9.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/daytwo/sea_food.jpg",
+ "title": "ä»ç¶è¢«å¿½æ ï¼æµ·é²å¤§é¤è¿æ¯å¤§ææ¡£",
+ "photo_small": "photo/daytwo/sea_food.jpg"
+ }
+]
diff --git a/json/photos_3_1.json b/json/photos_3_1.json
new file mode 100644
index 0000000..e344aa8
--- /dev/null
+++ b/json/photos_3_1.json
@@ -0,0 +1,197 @@
+[
+ {
+ "photo_big": "photo/daythree/disney.jpg",
+ "title": "åªæè¿ªæ¯å°¼ç©å¾æç½",
+ "photo_small": "photo/daythree/disney.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/gate.jpg",
+ "title": "大é¨",
+ "photo_small": "photo/daythree/gate.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/jinggai.jpg",
+ "title": "䏿°´éçåä¸ä¹æç±³å¥",
+ "photo_small": "photo/daythree/jinggai.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/mikey.jpg",
+ "title": "ç±³å¥å²æµª",
+ "photo_small": "photo/daythree/mikey.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/outside.jpg",
+ "title": "èµ¶ä¸ä¸å£èäº",
+ "photo_small": "photo/daythree/outside.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/usa.jpg",
+ "title": "ç¾å½å¤§è¡å°é",
+ "photo_small": "photo/daythree/usa.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/usa1.jpg",
+ "title": "为äºä¸å£èå°å¤è£
饰äºéª·é«
",
+ "photo_small": "photo/daythree/usa1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/chengbao.jpg",
+ "title": "è¿å¤çåå ¡",
+ "photo_small": "photo/daythree/chengbao.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/tommorrow.jpg",
+ "title": "ææ¥ä¸ç",
+ "photo_small": "photo/daythree/tommorrow.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/basi.jpg",
+ "title": "æå欢çå·´æ¯ï¼æ£é¢å¤ªä¸ï¼æ¾å¼ ä¾§é¢çå§",
+ "photo_small": "photo/daythree/basi.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/lunch.jpg",
+ "title": "50åä¸ä»½çåç§é¥",
+ "photo_small": "photo/daythree/lunch.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small1.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small2.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small2.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small3.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small3.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small4.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small4.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/small5.jpg",
+ "title": "å°å°ä¸ç",
+ "photo_small": "photo/daythree/small5.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/gaofei.jpg",
+ "title": "åé«é£åå½±",
+ "photo_small": "photo/daythree/gaofei.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/winnie.jpg",
+ "title": "ç»´å°¼ççæ
äº",
+ "photo_small": "photo/daythree/winnie.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/winnie1.jpg",
+ "title": "ç»´å°¼ççæ
äº",
+ "photo_small": "photo/daythree/winnie1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/youxing.jpg",
+ "title": "ä¸åå¼å§æ¸¸è¡",
+ "photo_small": "photo/daythree/youxing.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/youxing1.jpg",
+ "title": "彩车",
+ "photo_small": "photo/daythree/youxing1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/youxing2.jpg",
+ "title": "ç©å
·æ»å¨åæ¥äº",
+ "photo_small": "photo/daythree/youxing2.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/youxing3.jpg",
+ "title": "Daisy",
+ "photo_small": "photo/daythree/youxing3.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/duck.jpg",
+ "title": "åèé¸",
+ "photo_small": "photo/daythree/duck.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/youxing4.jpg",
+ "title": "è¿ä¸¤ä½è·³çæå¼å¿",
+ "photo_small": "photo/daythree/youxing4.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/oska.jpg",
+ "title": "é¢å¥å
¸ç¤¼ï¼å¤§é¨åç»å
¸äººç©é½åºç°é¸",
+ "photo_small": "photo/daythree/oska.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/lion.jpg",
+ "title": "ååºé£é©¬å¡å¡ï¼ç®åçåºå
¸ãçå°äºå½å½åè¾å·´ã",
+ "photo_small": "photo/daythree/lion.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/shop3.jpg",
+ "title": "æä¸åééååºã",
+ "photo_small": "photo/daythree/shop3.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/shop4.jpg",
+ "title": "å¨ççã",
+ "photo_small": "photo/daythree/shop4.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/shop5.jpg",
+ "title": "æ ä»·è¿æ¯ä»¤äººæèå´æ¥å",
+ "photo_small": "photo/daythree/shop5.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/wanshengjie.jpg",
+ "title": "æä¸çä¸å£è大游è¡",
+ "photo_small": "photo/daythree/wanshengjie.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/wanshengjie1.jpg",
+ "title": "æä¸çä¸å£è大游è¡",
+ "photo_small": "photo/daythree/wanshengjie1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/wanshengjie2.jpg",
+ "title": "æä¸çä¸å£è大游è¡",
+ "photo_small": "photo/daythree/wanshengjie2.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/wanshengjie3.jpg",
+ "title": "æä¸çä¸å£è大游è¡",
+ "photo_small": "photo/daythree/wanshengjie3.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/fire.jpg",
+ "title": "æç²¾å½©ççè±è¡¨æ¼ç
§ç¸æºå·²ç»æ²¡çµäº",
+ "photo_small": "photo/daythree/fire.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/subway.jpg",
+ "title": "æä¸8ç¹åºæ¥åå迪æ¯å°¼ä¸åå¾å°æ²åæ¹åå»",
+ "photo_small": "photo/daythree/subway.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/subway1.jpg",
+ "title": "齿¯ç±³å¥å¤´",
+ "photo_small": "photo/daythree/subway1.jpg"
+ },
+ {
+ "photo_big": "photo/daythree/jianshaozui.jpg",
+ "title": "ç»äºè½æ½ç¹æ¶é´åºæ¥è´è´ç©äº",
+ "photo_small": "photo/daythree/jianshaozui.jpg"
+ }
+]
diff --git a/json/photos_4_1.json b/json/photos_4_1.json
new file mode 100644
index 0000000..1ae6578
--- /dev/null
+++ b/json/photos_4_1.json
@@ -0,0 +1,37 @@
+[
+ {
+ "photo_big": "photo/dayfour/dsb.jpg",
+ "title": "æ¾³é¨å¤§ä¸å·´çå",
+ "photo_small": "photo/dayfour/dsb.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/macau_air.jpg",
+ "title": "åä¸ä¸ªå°æ¶è¹æ¥å°æ¾³é¨",
+ "photo_small": "photo/dayfour/dsb/macau_air.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/dsb.jpg",
+ "title": "大ä¸å·´å¥½å¤§ï¼åªè½å°ä¸é¢æ¥æ",
+ "photo_small": "photo/dayfour/dsb/dsb.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/pujing.jpg",
+ "title": "è¿æè¡äº¬",
+ "photo_small": "photo/dayfour/dsb/pujing.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/bowuguan.jpg",
+ "title": "大ä¸å·´ä¸é¢æ¯åç©é¦",
+ "photo_small": "photo/dayfour/dsb/bowuguan.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/dsb1.jpg",
+ "title": "æ¾³é¨å¤§ä¸å·´çå",
+ "photo_small": "photo/dayfour/dsb/dsb1.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/dsb/dsb2.jpg",
+ "title": "æ¾³é¨å¤§ä¸å·´çå",
+ "photo_small": "photo/dayfour/dsb/dsb2.jpg"
+ }
+]
diff --git a/json/photos_4_2.json b/json/photos_4_2.json
new file mode 100644
index 0000000..dd7f4cb
--- /dev/null
+++ b/json/photos_4_2.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/dayfour/mgm.jpg",
+ "title": "éçå¦éåº",
+ "photo_small": "photo/dayfour/mgm.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/mgm/mgm.jpg",
+ "title": "没æ¥å¾åä¸å»",
+ "photo_small": "photo/dayfour/mgm/mgm.jpg"
+ }
+]
diff --git a/json/photos_4_3.json b/json/photos_4_3.json
new file mode 100644
index 0000000..e8c7296
--- /dev/null
+++ b/json/photos_4_3.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfour/gyx.jpg",
+ "title": "åªè½å¨è½¦ä¸æ",
+ "photo_small": "photo/dayfour/gyx.jpg"
+ }
+]
diff --git a/json/photos_4_4.json b/json/photos_4_4.json
new file mode 100644
index 0000000..e617db0
--- /dev/null
+++ b/json/photos_4_4.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfour/zjs.jpg",
+ "title": "主æå±±æ²¡å»",
+ "photo_small": "photo/dayfour/zjs.jpg"
+ }
+]
diff --git a/json/photos_4_5.json b/json/photos_4_5.json
new file mode 100644
index 0000000..a777195
--- /dev/null
+++ b/json/photos_4_5.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfour/lotus.jpg",
+ "title": "æè°çè²è±å¹¿åºï¼ï¼",
+ "photo_small": "photo/dayfour/lotus.jpg"
+ }
+]
diff --git a/json/photos_4_6.json b/json/photos_4_6.json
new file mode 100644
index 0000000..6b72b64
--- /dev/null
+++ b/json/photos_4_6.json
@@ -0,0 +1,22 @@
+[
+ {
+ "photo_big": "photo/dayfour/round.jpg",
+ "title": "åå¨è½¦ä¸å
äºä¸åå°±ç®æ¯ç¯å²æ¸¸ï¼é±ç½ç»äº",
+ "photo_small": "photo/dayfour/round.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/round/round.jpg",
+ "title": "åå¨è½¦ä¸å
äºä¸åå°±ç®æ¯ç¯å²æ¸¸ï¼é±ç½ç»äº",
+ "photo_small": "photo/dayfour/round/round.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/round/round1.jpg",
+ "title": "åå¨è½¦ä¸å
äºä¸åå°±ç®æ¯ç¯å²æ¸¸ï¼é±ç½ç»äº",
+ "photo_small": "photo/dayfour/round/round1.jpg"
+ },
+ {
+ "photo_big": "photo/dayfour/round/round2.jpg",
+ "title": "åå¨è½¦ä¸å
äºä¸åå°±ç®æ¯ç¯å²æ¸¸ï¼é±ç½ç»äº",
+ "photo_small": "photo/dayfour/round/round2.jpg"
+ }
+]
diff --git a/json/photos_4_7.json b/json/photos_4_7.json
new file mode 100644
index 0000000..7f0ec7c
--- /dev/null
+++ b/json/photos_4_7.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfour/sx.jpg",
+ "title": "忝买ä¸è¥¿ï¼",
+ "photo_small": "photo/dayfour/sx.jpg"
+ }
+]
diff --git a/json/photos_4_8.json b/json/photos_4_8.json
new file mode 100644
index 0000000..8e3ad74
--- /dev/null
+++ b/json/photos_4_8.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfour/entertain.jpg",
+ "title": "å°±å¨é
åºä¸é¢çå°èµåºç©äºå æ",
+ "photo_small": "photo/dayfour/entertain.jpg"
+ }
+]
diff --git a/json/photos_5_1.json b/json/photos_5_1.json
new file mode 100644
index 0000000..ab8df8e
--- /dev/null
+++ b/json/photos_5_1.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfive/gbg.jpg",
+ "title": "å°äºç æµ·å°±æ¯æµªè´¹æ¶é´äº",
+ "photo_small": "photo/dayfive/gbg.jpg"
+ }
+]
diff --git a/json/photos_5_2.json b/json/photos_5_2.json
new file mode 100644
index 0000000..603478d
--- /dev/null
+++ b/json/photos_5_2.json
@@ -0,0 +1,12 @@
+[
+ {
+ "photo_big": "photo/dayfive/lover.jpg",
+ "title": "æ
侣路",
+ "photo_small": "photo/dayfive/lover.jpg"
+ },
+ {
+ "photo_big": "photo/dayfive/lover/lover.jpg",
+ "title": "æ
侣路å¯ä»¥é¥ææ¾³é¨",
+ "photo_small": "photo/dayfive/lover/lover.jpg"
+ }
+]
diff --git a/json/photos_5_3.json b/json/photos_5_3.json
new file mode 100644
index 0000000..3d60e62
--- /dev/null
+++ b/json/photos_5_3.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfive/fisher.jpg",
+ "title": "æ¸å¥³å乿²¡å»ç",
+ "photo_small": "photo/dayfive/fisher.jpg"
+ }
+]
diff --git a/json/photos_5_4.json b/json/photos_5_4.json
new file mode 100644
index 0000000..8756c2d
--- /dev/null
+++ b/json/photos_5_4.json
@@ -0,0 +1,7 @@
+[
+ {
+ "photo_big": "photo/dayfive/nkg.jpg",
+ "title": "åå°åäº¬å·²ç»æä¸11ç¹å¤äº",
+ "photo_small": "photo/dayfive/nkg.jpg"
+ }
+]
diff --git a/photo/dayfive/fisher.jpg b/photo/dayfive/fisher.jpg
index 6524901..baca78f 100644
Binary files a/photo/dayfive/fisher.jpg and b/photo/dayfive/fisher.jpg differ
diff --git a/photo/dayfive/gbg.jpg b/photo/dayfive/gbg.jpg
index d9d7e18..e6df5be 100644
Binary files a/photo/dayfive/gbg.jpg and b/photo/dayfive/gbg.jpg differ
diff --git a/photo/dayfive/lover.jpg b/photo/dayfive/lover.jpg
index beb5f3e..ba368e8 100644
Binary files a/photo/dayfive/lover.jpg and b/photo/dayfive/lover.jpg differ
diff --git a/photo/dayfive/lover/lover.jpg b/photo/dayfive/lover/lover.jpg
new file mode 100644
index 0000000..d2271f4
Binary files /dev/null and b/photo/dayfive/lover/lover.jpg differ
diff --git a/photo/dayfive/nkg.jpg b/photo/dayfive/nkg.jpg
new file mode 100644
index 0000000..ee6f0ae
Binary files /dev/null and b/photo/dayfive/nkg.jpg differ
diff --git a/photo/dayfour/dsb.jpg b/photo/dayfour/dsb.jpg
index 0c1a293..3da8a67 100644
Binary files a/photo/dayfour/dsb.jpg and b/photo/dayfour/dsb.jpg differ
diff --git a/photo/dayfour/dsb/bowuguan.jpg b/photo/dayfour/dsb/bowuguan.jpg
new file mode 100644
index 0000000..f41aaa3
Binary files /dev/null and b/photo/dayfour/dsb/bowuguan.jpg differ
diff --git a/photo/dayfour/dsb/dsb.jpg b/photo/dayfour/dsb/dsb.jpg
new file mode 100644
index 0000000..99cd312
Binary files /dev/null and b/photo/dayfour/dsb/dsb.jpg differ
diff --git a/photo/dayfour/dsb/dsb1.jpg b/photo/dayfour/dsb/dsb1.jpg
new file mode 100644
index 0000000..626b777
Binary files /dev/null and b/photo/dayfour/dsb/dsb1.jpg differ
diff --git a/photo/dayfour/dsb/dsb2.jpg b/photo/dayfour/dsb/dsb2.jpg
new file mode 100644
index 0000000..2f5bce5
Binary files /dev/null and b/photo/dayfour/dsb/dsb2.jpg differ
diff --git a/photo/dayfour/dsb/macau_air.jpg b/photo/dayfour/dsb/macau_air.jpg
new file mode 100644
index 0000000..29a2838
Binary files /dev/null and b/photo/dayfour/dsb/macau_air.jpg differ
diff --git a/photo/dayfour/dsb/pujing.jpg b/photo/dayfour/dsb/pujing.jpg
new file mode 100644
index 0000000..5aed755
Binary files /dev/null and b/photo/dayfour/dsb/pujing.jpg differ
diff --git a/photo/dayfour/entertain.jpg b/photo/dayfour/entertain.jpg
index ec0ce4a..c0e828e 100644
Binary files a/photo/dayfour/entertain.jpg and b/photo/dayfour/entertain.jpg differ
diff --git a/photo/dayfour/gyx.jpg b/photo/dayfour/gyx.jpg
index d96c96f..cc25241 100644
Binary files a/photo/dayfour/gyx.jpg and b/photo/dayfour/gyx.jpg differ
diff --git a/photo/dayfour/lotus.jpg b/photo/dayfour/lotus.jpg
index fa6c519..8e6fde7 100644
Binary files a/photo/dayfour/lotus.jpg and b/photo/dayfour/lotus.jpg differ
diff --git a/photo/dayfour/mgm.jpg b/photo/dayfour/mgm.jpg
index 3b1494d..8d230b1 100644
Binary files a/photo/dayfour/mgm.jpg and b/photo/dayfour/mgm.jpg differ
diff --git a/photo/dayfour/mgm/mgm.jpg b/photo/dayfour/mgm/mgm.jpg
new file mode 100644
index 0000000..b6a8aad
Binary files /dev/null and b/photo/dayfour/mgm/mgm.jpg differ
diff --git a/photo/dayfour/round.jpg b/photo/dayfour/round.jpg
index be2dd5c..8020dde 100644
Binary files a/photo/dayfour/round.jpg and b/photo/dayfour/round.jpg differ
diff --git a/photo/dayfour/round/round.jpg b/photo/dayfour/round/round.jpg
new file mode 100644
index 0000000..783cf39
Binary files /dev/null and b/photo/dayfour/round/round.jpg differ
diff --git a/photo/dayfour/round/round1.jpg b/photo/dayfour/round/round1.jpg
new file mode 100644
index 0000000..eb6e08a
Binary files /dev/null and b/photo/dayfour/round/round1.jpg differ
diff --git a/photo/dayfour/round/round2.jpg b/photo/dayfour/round/round2.jpg
new file mode 100644
index 0000000..8ae951d
Binary files /dev/null and b/photo/dayfour/round/round2.jpg differ
diff --git a/photo/dayfour/sx.jpg b/photo/dayfour/sx.jpg
index f8ef6b4..15ad8ee 100644
Binary files a/photo/dayfour/sx.jpg and b/photo/dayfour/sx.jpg differ
diff --git a/photo/dayfour/zjs.jpg b/photo/dayfour/zjs.jpg
index 619cff3..3e9b292 100644
Binary files a/photo/dayfour/zjs.jpg and b/photo/dayfour/zjs.jpg differ
diff --git a/photo/dayone/cob.jpg b/photo/dayone/cob.jpg
index 65a0587..952b490 100644
Binary files a/photo/dayone/cob.jpg and b/photo/dayone/cob.jpg differ
diff --git a/photo/dayone/gov.jpg b/photo/dayone/gov.jpg
index 8fbec99..6ac06b1 100644
Binary files a/photo/dayone/gov.jpg and b/photo/dayone/gov.jpg differ
diff --git a/photo/dayone/guangzhou.jpg b/photo/dayone/guangzhou.jpg
index 0214dca..4cfafd7 100644
Binary files a/photo/dayone/guangzhou.jpg and b/photo/dayone/guangzhou.jpg differ
diff --git a/photo/dayone/guangzhou/gz_airport.jpg b/photo/dayone/guangzhou/gz_airport.jpg
new file mode 100755
index 0000000..d6382d7
Binary files /dev/null and b/photo/dayone/guangzhou/gz_airport.jpg differ
diff --git a/photo/dayone/guangzhou/tower.jpg b/photo/dayone/guangzhou/tower.jpg
new file mode 100644
index 0000000..c869f88
Binary files /dev/null and b/photo/dayone/guangzhou/tower.jpg differ
diff --git a/photo/dayone/hotel.jpg b/photo/dayone/hotel.jpg
index 7a1294c..7e556e7 100644
Binary files a/photo/dayone/hotel.jpg and b/photo/dayone/hotel.jpg differ
diff --git a/photo/dayone/hotel/hotel1.jpg b/photo/dayone/hotel/hotel1.jpg
new file mode 100644
index 0000000..bccbac3
Binary files /dev/null and b/photo/dayone/hotel/hotel1.jpg differ
diff --git a/photo/dayone/hotel/hotel2.jpg b/photo/dayone/hotel/hotel2.jpg
new file mode 100644
index 0000000..e18ec63
Binary files /dev/null and b/photo/dayone/hotel/hotel2.jpg differ
diff --git a/photo/dayone/hotel/hotel3.jpg b/photo/dayone/hotel/hotel3.jpg
new file mode 100644
index 0000000..11428c1
Binary files /dev/null and b/photo/dayone/hotel/hotel3.jpg differ
diff --git a/photo/dayone/jzj/cut.jpg b/photo/dayone/jzj/cut.jpg
new file mode 100644
index 0000000..39f0bc6
Binary files /dev/null and b/photo/dayone/jzj/cut.jpg differ
diff --git a/photo/dayone/jzj/jzj.jpg b/photo/dayone/jzj/jzj.jpg
new file mode 100644
index 0000000..d574396
Binary files /dev/null and b/photo/dayone/jzj/jzj.jpg differ
diff --git a/photo/dayone/jzj/mm.jpg b/photo/dayone/jzj/mm.jpg
new file mode 100644
index 0000000..d9fb308
Binary files /dev/null and b/photo/dayone/jzj/mm.jpg differ
diff --git a/photo/dayone/jzj/return.jpg b/photo/dayone/jzj/return.jpg
new file mode 100644
index 0000000..21c84c0
Binary files /dev/null and b/photo/dayone/jzj/return.jpg differ
diff --git a/photo/dayone/jzj/sea_building.jpg b/photo/dayone/jzj/sea_building.jpg
new file mode 100644
index 0000000..a3b22d6
Binary files /dev/null and b/photo/dayone/jzj/sea_building.jpg differ
diff --git a/photo/dayone/jzj/ship.jpg b/photo/dayone/jzj/ship.jpg
new file mode 100644
index 0000000..a7afe3b
Binary files /dev/null and b/photo/dayone/jzj/ship.jpg differ
diff --git a/photo/dayone/jzj_square.jpg b/photo/dayone/jzj_square.jpg
index 0214dca..191e38b 100644
Binary files a/photo/dayone/jzj_square.jpg and b/photo/dayone/jzj_square.jpg differ
diff --git a/photo/dayone/law.jpg b/photo/dayone/law.jpg
index 12fa849..bab314e 100644
Binary files a/photo/dayone/law.jpg and b/photo/dayone/law.jpg differ
diff --git a/photo/dayone/libinfu.jpg b/photo/dayone/libinfu.jpg
index 8f2238d..115cc8f 100644
Binary files a/photo/dayone/libinfu.jpg and b/photo/dayone/libinfu.jpg differ
diff --git a/photo/dayone/lk_airport.jpg b/photo/dayone/lk_airport.jpg
index 0214dca..83c396b 100644
Binary files a/photo/dayone/lk_airport.jpg and b/photo/dayone/lk_airport.jpg differ
diff --git a/photo/dayone/lk_airport/lk_airport_inside.jpg b/photo/dayone/lk_airport/lk_airport_inside.jpg
new file mode 100755
index 0000000..030c951
Binary files /dev/null and b/photo/dayone/lk_airport/lk_airport_inside.jpg differ
diff --git a/photo/dayone/meeting_center.jpg b/photo/dayone/meeting_center.jpg
index 0214dca..74ce8fa 100644
Binary files a/photo/dayone/meeting_center.jpg and b/photo/dayone/meeting_center.jpg differ
diff --git a/photo/dayone/repulse_bay.jpg b/photo/dayone/repulse_bay.jpg
index 1045bde..e793f1e 100644
Binary files a/photo/dayone/repulse_bay.jpg and b/photo/dayone/repulse_bay.jpg differ
diff --git a/photo/dayone/repulse_bay/love.jpg b/photo/dayone/repulse_bay/love.jpg
new file mode 100644
index 0000000..f45fc41
Binary files /dev/null and b/photo/dayone/repulse_bay/love.jpg differ
diff --git a/photo/dayone/repulse_bay/night.jpg b/photo/dayone/repulse_bay/night.jpg
new file mode 100644
index 0000000..634b410
Binary files /dev/null and b/photo/dayone/repulse_bay/night.jpg differ
diff --git a/photo/dayone/sea_park.jpg b/photo/dayone/sea_park.jpg
index 9d411b2..603c253 100644
Binary files a/photo/dayone/sea_park.jpg and b/photo/dayone/sea_park.jpg differ
diff --git a/photo/dayone/sea_park/evil.jpg b/photo/dayone/sea_park/evil.jpg
new file mode 100644
index 0000000..5a5f853
Binary files /dev/null and b/photo/dayone/sea_park/evil.jpg differ
diff --git a/photo/dayone/sea_park/fish.jpg b/photo/dayone/sea_park/fish.jpg
new file mode 100644
index 0000000..4de2058
Binary files /dev/null and b/photo/dayone/sea_park/fish.jpg differ
diff --git a/photo/dayone/sea_park/haitun.jpg b/photo/dayone/sea_park/haitun.jpg
new file mode 100644
index 0000000..59f25b0
Binary files /dev/null and b/photo/dayone/sea_park/haitun.jpg differ
diff --git a/photo/dayone/sea_park/haiyang.jpg b/photo/dayone/sea_park/haiyang.jpg
new file mode 100644
index 0000000..19e5a35
Binary files /dev/null and b/photo/dayone/sea_park/haiyang.jpg differ
diff --git a/photo/dayone/sea_park/lanche.jpg b/photo/dayone/sea_park/lanche.jpg
new file mode 100644
index 0000000..853d38f
Binary files /dev/null and b/photo/dayone/sea_park/lanche.jpg differ
diff --git a/photo/dayone/sea_park/mm.jpg b/photo/dayone/sea_park/mm.jpg
new file mode 100644
index 0000000..cfe6697
Binary files /dev/null and b/photo/dayone/sea_park/mm.jpg differ
diff --git a/photo/dayone/sea_park/nimo.jpg b/photo/dayone/sea_park/nimo.jpg
new file mode 100644
index 0000000..a36e414
Binary files /dev/null and b/photo/dayone/sea_park/nimo.jpg differ
diff --git a/photo/dayone/sea_park/panda.jpg b/photo/dayone/sea_park/panda.jpg
new file mode 100644
index 0000000..dee672a
Binary files /dev/null and b/photo/dayone/sea_park/panda.jpg differ
diff --git a/photo/dayone/sea_park/qiqiu.jpg b/photo/dayone/sea_park/qiqiu.jpg
new file mode 100644
index 0000000..5deeeec
Binary files /dev/null and b/photo/dayone/sea_park/qiqiu.jpg differ
diff --git a/photo/dayone/sea_park/shuimu.jpg b/photo/dayone/sea_park/shuimu.jpg
new file mode 100644
index 0000000..68c72c6
Binary files /dev/null and b/photo/dayone/sea_park/shuimu.jpg differ
diff --git a/photo/dayone/sea_park/shuimuyi.jpg b/photo/dayone/sea_park/shuimuyi.jpg
new file mode 100644
index 0000000..e3ca1ee
Binary files /dev/null and b/photo/dayone/sea_park/shuimuyi.jpg differ
diff --git a/photo/dayone/sea_park/star.jpg b/photo/dayone/sea_park/star.jpg
new file mode 100644
index 0000000..8e901c5
Binary files /dev/null and b/photo/dayone/sea_park/star.jpg differ
diff --git a/photo/dayone/sea_park/zaji.jpg b/photo/dayone/sea_park/zaji.jpg
new file mode 100644
index 0000000..4e2c26a
Binary files /dev/null and b/photo/dayone/sea_park/zaji.jpg differ
diff --git a/photo/dayone/taiping.jpg b/photo/dayone/taiping.jpg
index 4a5c7fb..80447fb 100644
Binary files a/photo/dayone/taiping.jpg and b/photo/dayone/taiping.jpg differ
diff --git a/photo/dayone/taiping/night.jpg b/photo/dayone/taiping/night.jpg
new file mode 100644
index 0000000..a1c562c
Binary files /dev/null and b/photo/dayone/taiping/night.jpg differ
diff --git a/photo/dayone/zhm_bus_station.jpg b/photo/dayone/zhm_bus_station.jpg
index 3cea46d..c3aaa3a 100644
Binary files a/photo/dayone/zhm_bus_station.jpg and b/photo/dayone/zhm_bus_station.jpg differ
diff --git a/photo/daythree/basi.jpg b/photo/daythree/basi.jpg
new file mode 100644
index 0000000..2f7c5a3
Binary files /dev/null and b/photo/daythree/basi.jpg differ
diff --git a/photo/daythree/chengbao.jpg b/photo/daythree/chengbao.jpg
new file mode 100644
index 0000000..1ec65ef
Binary files /dev/null and b/photo/daythree/chengbao.jpg differ
diff --git a/photo/daythree/disney.jpg b/photo/daythree/disney.jpg
index c84fd9b..cd74119 100644
Binary files a/photo/daythree/disney.jpg and b/photo/daythree/disney.jpg differ
diff --git a/photo/daythree/duck.jpg b/photo/daythree/duck.jpg
new file mode 100644
index 0000000..703cf1d
Binary files /dev/null and b/photo/daythree/duck.jpg differ
diff --git a/photo/daythree/fire.jpg b/photo/daythree/fire.jpg
new file mode 100644
index 0000000..6605341
Binary files /dev/null and b/photo/daythree/fire.jpg differ
diff --git a/photo/daythree/gaofei.jpg b/photo/daythree/gaofei.jpg
new file mode 100644
index 0000000..a373138
Binary files /dev/null and b/photo/daythree/gaofei.jpg differ
diff --git a/photo/daythree/gate.jpg b/photo/daythree/gate.jpg
new file mode 100644
index 0000000..03128f8
Binary files /dev/null and b/photo/daythree/gate.jpg differ
diff --git a/photo/daythree/jianshaozui.jpg b/photo/daythree/jianshaozui.jpg
new file mode 100644
index 0000000..9bbca3c
Binary files /dev/null and b/photo/daythree/jianshaozui.jpg differ
diff --git a/photo/daythree/jinggai.jpg b/photo/daythree/jinggai.jpg
new file mode 100644
index 0000000..8e92fc1
Binary files /dev/null and b/photo/daythree/jinggai.jpg differ
diff --git a/photo/daythree/lion.jpg b/photo/daythree/lion.jpg
new file mode 100644
index 0000000..a9b9073
Binary files /dev/null and b/photo/daythree/lion.jpg differ
diff --git a/photo/daythree/lunch.jpg b/photo/daythree/lunch.jpg
new file mode 100644
index 0000000..b3ce89c
Binary files /dev/null and b/photo/daythree/lunch.jpg differ
diff --git a/photo/daythree/mikey.jpg b/photo/daythree/mikey.jpg
new file mode 100644
index 0000000..de5feb4
Binary files /dev/null and b/photo/daythree/mikey.jpg differ
diff --git a/photo/daythree/oska.jpg b/photo/daythree/oska.jpg
new file mode 100644
index 0000000..da684e1
Binary files /dev/null and b/photo/daythree/oska.jpg differ
diff --git a/photo/daythree/outside.jpg b/photo/daythree/outside.jpg
new file mode 100644
index 0000000..b33db91
Binary files /dev/null and b/photo/daythree/outside.jpg differ
diff --git a/photo/daythree/shop.jpg b/photo/daythree/shop.jpg
new file mode 100644
index 0000000..6ac0e73
Binary files /dev/null and b/photo/daythree/shop.jpg differ
diff --git a/photo/daythree/shop1.jpg b/photo/daythree/shop1.jpg
new file mode 100644
index 0000000..0b960fb
Binary files /dev/null and b/photo/daythree/shop1.jpg differ
diff --git a/photo/daythree/shop2.jpg b/photo/daythree/shop2.jpg
new file mode 100644
index 0000000..38f2a72
Binary files /dev/null and b/photo/daythree/shop2.jpg differ
diff --git a/photo/daythree/shop3.jpg b/photo/daythree/shop3.jpg
new file mode 100644
index 0000000..e37ce06
Binary files /dev/null and b/photo/daythree/shop3.jpg differ
diff --git a/photo/daythree/shop4.jpg b/photo/daythree/shop4.jpg
new file mode 100644
index 0000000..ed33958
Binary files /dev/null and b/photo/daythree/shop4.jpg differ
diff --git a/photo/daythree/shop5.jpg b/photo/daythree/shop5.jpg
new file mode 100644
index 0000000..00418f8
Binary files /dev/null and b/photo/daythree/shop5.jpg differ
diff --git a/photo/daythree/small.jpg b/photo/daythree/small.jpg
new file mode 100644
index 0000000..163e987
Binary files /dev/null and b/photo/daythree/small.jpg differ
diff --git a/photo/daythree/small1.jpg b/photo/daythree/small1.jpg
new file mode 100644
index 0000000..bd451b5
Binary files /dev/null and b/photo/daythree/small1.jpg differ
diff --git a/photo/daythree/small2.jpg b/photo/daythree/small2.jpg
new file mode 100644
index 0000000..6ce8a53
Binary files /dev/null and b/photo/daythree/small2.jpg differ
diff --git a/photo/daythree/small3.jpg b/photo/daythree/small3.jpg
new file mode 100644
index 0000000..f586c70
Binary files /dev/null and b/photo/daythree/small3.jpg differ
diff --git a/photo/daythree/small4.jpg b/photo/daythree/small4.jpg
new file mode 100644
index 0000000..4929c77
Binary files /dev/null and b/photo/daythree/small4.jpg differ
diff --git a/photo/daythree/small5.jpg b/photo/daythree/small5.jpg
new file mode 100644
index 0000000..77f5608
Binary files /dev/null and b/photo/daythree/small5.jpg differ
diff --git a/photo/daythree/subway.jpg b/photo/daythree/subway.jpg
new file mode 100644
index 0000000..25d2879
Binary files /dev/null and b/photo/daythree/subway.jpg differ
diff --git a/photo/daythree/subway1.jpg b/photo/daythree/subway1.jpg
new file mode 100644
index 0000000..d4a2d72
Binary files /dev/null and b/photo/daythree/subway1.jpg differ
diff --git a/photo/daythree/tommorrow.jpg b/photo/daythree/tommorrow.jpg
new file mode 100644
index 0000000..a442e76
Binary files /dev/null and b/photo/daythree/tommorrow.jpg differ
diff --git a/photo/daythree/usa.jpg b/photo/daythree/usa.jpg
new file mode 100644
index 0000000..fab2295
Binary files /dev/null and b/photo/daythree/usa.jpg differ
diff --git a/photo/daythree/usa1.jpg b/photo/daythree/usa1.jpg
new file mode 100644
index 0000000..cc11fed
Binary files /dev/null and b/photo/daythree/usa1.jpg differ
diff --git a/photo/daythree/wanshengjie.jpg b/photo/daythree/wanshengjie.jpg
new file mode 100644
index 0000000..2ff02b5
Binary files /dev/null and b/photo/daythree/wanshengjie.jpg differ
diff --git a/photo/daythree/wanshengjie1.jpg b/photo/daythree/wanshengjie1.jpg
new file mode 100644
index 0000000..fbc5c1f
Binary files /dev/null and b/photo/daythree/wanshengjie1.jpg differ
diff --git a/photo/daythree/wanshengjie2.jpg b/photo/daythree/wanshengjie2.jpg
new file mode 100644
index 0000000..94b488a
Binary files /dev/null and b/photo/daythree/wanshengjie2.jpg differ
diff --git a/photo/daythree/wanshengjie3.jpg b/photo/daythree/wanshengjie3.jpg
new file mode 100644
index 0000000..794df01
Binary files /dev/null and b/photo/daythree/wanshengjie3.jpg differ
diff --git a/photo/daythree/winnie.jpg b/photo/daythree/winnie.jpg
new file mode 100644
index 0000000..f6a20d3
Binary files /dev/null and b/photo/daythree/winnie.jpg differ
diff --git a/photo/daythree/winnie1.jpg b/photo/daythree/winnie1.jpg
new file mode 100644
index 0000000..c86508f
Binary files /dev/null and b/photo/daythree/winnie1.jpg differ
diff --git a/photo/daythree/youxing.jpg b/photo/daythree/youxing.jpg
new file mode 100644
index 0000000..2524817
Binary files /dev/null and b/photo/daythree/youxing.jpg differ
diff --git a/photo/daythree/youxing1.jpg b/photo/daythree/youxing1.jpg
new file mode 100644
index 0000000..7a9f1fc
Binary files /dev/null and b/photo/daythree/youxing1.jpg differ
diff --git a/photo/daythree/youxing2.jpg b/photo/daythree/youxing2.jpg
new file mode 100644
index 0000000..a6a24a6
Binary files /dev/null and b/photo/daythree/youxing2.jpg differ
diff --git a/photo/daythree/youxing3.jpg b/photo/daythree/youxing3.jpg
new file mode 100644
index 0000000..9e811ea
Binary files /dev/null and b/photo/daythree/youxing3.jpg differ
diff --git a/photo/daythree/youxing4.jpg b/photo/daythree/youxing4.jpg
new file mode 100644
index 0000000..d0b1495
Binary files /dev/null and b/photo/daythree/youxing4.jpg differ
diff --git a/photo/daytwo/dfs.jpg b/photo/daytwo/dfs.jpg
index 90149b1..1318967 100644
Binary files a/photo/daytwo/dfs.jpg and b/photo/daytwo/dfs.jpg differ
diff --git a/photo/daytwo/hdx.jpg b/photo/daytwo/hdx.jpg
index 7cf62cc..c979b8b 100644
Binary files a/photo/daytwo/hdx.jpg and b/photo/daytwo/hdx.jpg differ
diff --git a/photo/daytwo/hdx/hdx1.jpg b/photo/daytwo/hdx/hdx1.jpg
new file mode 100644
index 0000000..f4839cb
Binary files /dev/null and b/photo/daytwo/hdx/hdx1.jpg differ
diff --git a/photo/daytwo/hdx/hdx2.jpg b/photo/daytwo/hdx/hdx2.jpg
new file mode 100644
index 0000000..fe327a1
Binary files /dev/null and b/photo/daytwo/hdx/hdx2.jpg differ
diff --git a/photo/daytwo/jewelry.jpg b/photo/daytwo/jewelry.jpg
index 222aed4..cf857bc 100644
Binary files a/photo/daytwo/jewelry.jpg and b/photo/daytwo/jewelry.jpg differ
diff --git a/photo/daytwo/jewelry/kaixuan.jpg b/photo/daytwo/jewelry/kaixuan.jpg
new file mode 100644
index 0000000..eebadaf
Binary files /dev/null and b/photo/daytwo/jewelry/kaixuan.jpg differ
diff --git a/photo/daytwo/jewelry/kaixuan1.jpg b/photo/daytwo/jewelry/kaixuan1.jpg
new file mode 100644
index 0000000..d8d331e
Binary files /dev/null and b/photo/daytwo/jewelry/kaixuan1.jpg differ
diff --git a/photo/daytwo/jsz.jpg b/photo/daytwo/jsz.jpg
index af84421..f575566 100644
Binary files a/photo/daytwo/jsz.jpg and b/photo/daytwo/jsz.jpg differ
diff --git a/photo/daytwo/lunch.jpg b/photo/daytwo/lunch.jpg
index 4ba6e1e..8b48424 100644
Binary files a/photo/daytwo/lunch.jpg and b/photo/daytwo/lunch.jpg differ
diff --git a/photo/daytwo/sea_food.jpg b/photo/daytwo/sea_food.jpg
index ec7dbdc..0de2400 100644
Binary files a/photo/daytwo/sea_food.jpg and b/photo/daytwo/sea_food.jpg differ
diff --git a/photo/daytwo/start.jpg b/photo/daytwo/start.jpg
index 9f6f205..66fa5fe 100644
Binary files a/photo/daytwo/start.jpg and b/photo/daytwo/start.jpg differ
diff --git a/photo/daytwo/start/start.jpg b/photo/daytwo/start/start.jpg
new file mode 100644
index 0000000..414c669
Binary files /dev/null and b/photo/daytwo/start/start.jpg differ
diff --git a/photo/daytwo/store.jpg b/photo/daytwo/store.jpg
index 573c78e..09032b7 100644
Binary files a/photo/daytwo/store.jpg and b/photo/daytwo/store.jpg differ
diff --git a/photo/daytwo/tower.jpg b/photo/daytwo/tower.jpg
index 5fdade4..5dfebe8 100644
Binary files a/photo/daytwo/tower.jpg and b/photo/daytwo/tower.jpg differ
diff --git a/photo/daytwo/tower/tower.jpg b/photo/daytwo/tower/tower.jpg
new file mode 100644
index 0000000..727f317
Binary files /dev/null and b/photo/daytwo/tower/tower.jpg differ
diff --git a/photo/daytwo/victoria.jpg b/photo/daytwo/victoria.jpg
index 523ae5a..f0741af 100644
Binary files a/photo/daytwo/victoria.jpg and b/photo/daytwo/victoria.jpg differ
diff --git a/photo/daytwo/victoria/victoria.jpg b/photo/daytwo/victoria/victoria.jpg
new file mode 100644
index 0000000..c609413
Binary files /dev/null and b/photo/daytwo/victoria/victoria.jpg differ
|
kurtchen/hk_macau
|
baa70322c410df7adbba56cc8c7bc1b55b28b449
|
Added marker and info window on map
|
diff --git a/index_static.html b/index_static.html
index 254253c..97c0aa8 100644
--- a/index_static.html
+++ b/index_static.html
@@ -1,87 +1,88 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>HongKong & Macau in 5 Days</title>
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
+ <script src="js/markermanager.js" type="text/javascript"></script><!---->
<link rel="stylesheet" type="text/css" href="css/main.css" />
<script src="js/main.js" type="text/javascript"></script>
</head>
<body>
<center>
<div class="TabsArea">
<div id="tab_menu" class="TabMenu">
<img src="img/loading.gif" width="220" height="19"/>
<!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
<span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
<span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
<span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
<span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
</div>
<!--############################Begine Slider###########################################-->
<div id="slider">
<img class="ScrollButtons left" src="img/leftarrow.png">
<div class="ScrollPanes">
<div class="ScrollContainer">
<!-- <img src="img/loading.gif" width="220" height="19"/> -->
<!--
<div class="Panel" id="panel_1">
<div class="inside">
<img src="img/slider/1.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_2">
<div class="inside">
<img src="img/slider/2.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_3">
<div class="inside">
<img src="img/slider/3.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_4">
<div class="inside">
<img src="img/slider/4.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
<div class="Panel" id="panel_5">
<div class="inside">
<img src="img/slider/5.jpg" alt="picture" />
<span>News Heading</span>
</div>
</div>
-->
</div>
<div id="left_shadow"></div>
<div id="right_shadow"></div>
</div>
<img class="ScrollButtons right" src="img/rightarrow.png">
</div>
<!--############################End Slider###########################################-->
</div>
<hr/>
<!--############################Begine Map###########################################-->
<div id="hk_map">
</div>
<!--############################End Map###########################################-->
<!--
<div>
<img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
<img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
<img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
<img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
<img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
</div>
-->
</center>
</body>
</html>
diff --git a/js/main.js b/js/main.js
index f7d93ce..ee6e6d5 100644
--- a/js/main.js
+++ b/js/main.js
@@ -1,256 +1,309 @@
$(document).ready(function(){
// Load Google Map
- loadGMap();
+ loadGMap();
// Setup for Google Map
$("body").bind("unload", GUnload);
// Get the groups
$.getJSON('json/groups.json', setGroups);
});
/*
After get the group data from server, add them to tab area.
*/
function setGroups(data){
// Remove the loading image
$('#tab_menu').empty();
// Add the groups
$.each(data, function(entryInx, entry){
var groupsHtml = '<span id="tab_';
groupsHtml += entry['id'];
groupsHtml += '"><img class="CameraIcon" src="';
groupsHtml += entry['image_url'];
groupsHtml += '"/>';
groupsHtml += entry['name'];
groupsHtml += '</span>';
$('#tab_menu').append(groupsHtml);
});
// Init the group tabs
initTabs();
}
/*
Init the group tabs.
*/
function initTabs(){
// Selet first group
$(".TabsArea .TabMenu span:first").addClass("selector");
//Set hover effect for the tabs
$(".TabsArea .TabMenu span").mouseover(function(){
$(this).addClass("hovering");
});
$(".TabsArea .TabMenu span").mouseout(function(){
$(this).removeClass("hovering");
});
//Add click action to tab menu
$(".TabsArea .TabMenu span").click(function(){
//Remove the exist selector
$(".selector").removeClass("selector");
//Add the selector class to the sender
$(this).addClass("selector");
// Get the spots and update the slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
$.getJSON("json/group"+this.id.substr(this.id.lastIndexOf("_")+1)+".json", setSpot);
});
// Init loading image for slider
$(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
// Get First group of spots
$.getJSON("json/group1.json", setSpot);
}
/*
Set the spots to the slider.
*/
function setSpot(data){
// Remove the previous group of spots or the loading image
$('.ScrollContainer').empty();
// Add the spots
$.each(data, function(entryIdx, entry){
var spotHtml = '<div class="Panel" id="panel_';
spotHtml += (entryIdx+1);
spotHtml += '"><div class="inside"><img src="';
spotHtml += entry['image_url'];
spotHtml += '" alt="';
spotHtml += entry['description'];
spotHtml += '" /><span>';
spotHtml += entry['name'];
spotHtml += '</span></div></div>';
//alert(spotHtml);
$('.ScrollContainer').append(spotHtml);
// Set Lat & Lng info
$("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
$("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
$("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
});
// Init Slider
+ console.debug("calling initSlider");
initSlider();
}
/*
Init Slider.
*/
function initSlider(){
// Caculte the total width of the slider
var $panels = $(".Panel");
var width = $panels[0].offsetWidth * $panels.length + 100;
// The first spot is in the middle at the begining
$(".ScrollContainer").css("width", width).css("left", "350px");
// The first spot will be bigger at first
makeBigger("#panel_1");
curPanel = 1;
updatePanelEventHandlers();
maxPanel = $panels.length;
$("#slider").data("currentlyMoving", false);
// Add event handler for navigate buttons
$(".right").click(function(){ navigate(true); });
$(".left").click(function(){ navigate(false); });
+ console.debug("calling moveMap");
moveMap();
}
/*
Make the panel bigger.
*/
function makeBigger(element){
$(element).animate({ width: biggerWidth })
.find("img").animate({width: biggerImgWidth})
.end()
.find("span").animate({fontSize: biggerFontSize});
}
/*
Make the panel to normal size
*/
function makeNormal(element){
$(element).animate({ width: normalWidth })
.find("img").animate({width: normalImgWidth})
.end()
.find("span").animate({fontSize: normalFontSize});
}
/*
Navigate.
*/
function navigate(moving2left){
var steps = arguments[1]?arguments[1]:1;
// Invalid cases
if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
return false;
}
// If currently the slider is not moving
if(($("#slider").data("currentlyMoving") == false)){
$("#slider").data("currentlyMoving", true);
var nextPanel = moving2left?curPanel+steps:curPanel-steps;
var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
var movement = moving2left?curPos-step*steps:curPos+step*steps;
// Move the panels
$(".ScrollContainer")
.stop()
.animate({"left": movement},
function() {
- $("#slider").data("currentlyMoving", false);
- moveMap();
+ console.debug("==>"+$(".ScrollContainer").css("left"));
+ if($("#slider").data("currentlyMoving")==true)
+ {
+ $("#slider").data("currentlyMoving", false);
+ console.debug("Calling moveMap after animation");
+ moveMap();
+ }
});
// Make the previous panel to normal size
makeNormal("#panel_"+curPanel);
// Make current panel bigger
makeBigger("#panel_"+nextPanel);
curPanel = nextPanel;
updatePanelEventHandlers();
//moveMap();
}
return true;
}
/*
Bind click event for all the spots.
*/
function updatePanelEventHandlers(){
var $panels = $(".Panel");
$panels.unbind();
$panels.click(function(){
var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
if(inx!=curPanel){
navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
}
});
}
/*
Load Google Map.
*/
function loadGMap(){
//alert("Load GMap");
map = new GMap2(document.getElementById("hk_map"));
//map.setCenter(new GLatLng(37.4419, -122.1419), 13);
map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
map.setUIToDefault();
+
+ markermanager = new MarkerManager(map);
}
/*
Move Map.
*/
function moveMap(){
var $curPanel = $("#panel_"+curPanel);
var lat = $curPanel.data("lat");
var lng = $curPanel.data("lng");
if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
return false;
}
var zoom = $curPanel.data("zoom");
if(zoom == undefined || zoom == null || zoom <= 0){
zoom = 15;
}
- //console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
+ console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
if(map){
- map.setZoom(parseInt(zoom));
- map.panTo(new GLatLng(lat,lng));
+ zoom = parseInt(zoom);
+ map.setZoom(zoom);
+ //map.panTo(new GLatLng(lat,lng));
+ map.setCenter(new GLatLng(lat,lng));
+
+ // Show Marker and the Info window
+ showMarkerAndInfo(lat,lng, zoom);
+ }
+
+ return true;
+}
+
+/*
+ Show Maker on the map and show the info window.
+*/
+function showMarkerAndInfo(lat, lng, zoom){
+ if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
+ return false;
}
+ if(zoom == undefined || zoom == null || zoom <= 0){
+ zoom = 15;
+ }
+
+ map.closeInfoWindow();
+
+ var marker = markermanager.getMarker(lat,lng, zoom);
+ markermanager.removeMarker(marker);
+ markermanager.addMarker(marker,zoom);
+
+ //console.debug(markermanager.getMarkerCount(zoom));
+
+ markermanager.refresh();
+
+ var $curPanelImg = $("#panel_"+curPanel+" img");
+
+ // Set the click event for the marker
+ //GEvent.addListener(marker, "click", function(){
+ // marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
+ //});
+ marker.bindInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
+
+ console.debug($curPanelImg.attr("src"));
+ //marker.openInfoWindowHtml("<img src=\""+$curPanelImg.attr("src")+"\"/>");
+ //GEvent.trigger(marker, "click");
+ setTimeout(function(){GEvent.trigger(marker, "click");},1000);
+
return true;
}
// Constants for bigger panel
var biggerWidth = "150px";
var biggerImgWidth = "120px";
var biggerFontSize = "14px";
// Constants for normal panel
var normalWidth = "130px";
var normalImgWidth = "100px";
var normalFontSize = "12px";
// Moving step
var step = 150;
// Global Vars
var curPanel = 0;
var maxPanel = 0;
// The map
-var map;
\ No newline at end of file
+var map;
+var markermanager;
\ No newline at end of file
diff --git a/js/markermanager.js b/js/markermanager.js
new file mode 100644
index 0000000..51e99f9
--- /dev/null
+++ b/js/markermanager.js
@@ -0,0 +1,815 @@
+/**
+ * @name MarkerManager
+ * @version 1.0
+ * @copyright (c) 2007 Google Inc.
+ * @author Doug Ricket, others
+ *
+ * @fileoverview Marker manager is an interface between the map and the user,
+ * designed to manage adding and removing many points when the viewport changes.
+ * <br /><br />
+ * <b>How it Works</b>:<br/>
+ * The MarkerManager places its markers onto a grid, similar to the map tiles.
+ * When the user moves the viewport, it computes which grid cells have
+ * entered or left the viewport, and shows or hides all the markers in those
+ * cells.
+ * (If the users scrolls the viewport beyond the markers that are loaded,
+ * no markers will be visible until the <code>EVENT_moveend</code>
+ * triggers an update.)
+ * In practical consequences, this allows 10,000 markers to be distributed over
+ * a large area, and as long as only 100-200 are visible in any given viewport,
+ * the user will see good performance corresponding to the 100 visible markers,
+ * rather than poor performance corresponding to the total 10,000 markers.
+ * Note that some code is optimized for speed over space,
+ * with the goal of accommodating thousands of markers.
+ */
+
+/*
+ * 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.
+ */
+
+/**
+ * @name MarkerManagerOptions
+ * @class This class represents optional arguments to the {@link MarkerManager}
+ * constructor.
+ * @property {Number} [maxZoom] Sets the maximum zoom level monitored by a
+ * marker manager. If not given, the manager assumes the maximum map zoom
+ * level. This value is also used when markers are added to the manager
+ * without the optional {@link maxZoom} parameter.
+ * @property {Number} [borderPadding] Specifies, in pixels, the extra padding
+ * outside the map's current viewport monitored by a manager. Markers that
+ * fall within this padding are added to the map, even if they are not fully
+ * visible.
+ * @property {Boolean} [trackMarkers=false] Indicates whether or not a marker
+ * manager should track markers' movements. If you wish to move managed
+ * markers using the {@link setPoint}/{@link setLatLng} methods,
+ * this option should be set to {@link true}.
+ */
+
+/**
+ * Creates a new MarkerManager that will show/hide markers on a map.
+ *
+ * @constructor
+ * @param {Map} map The map to manage.
+ * @param {Object} opt_opts A container for optional arguments:
+ * {Number} maxZoom The maximum zoom level for which to create tiles.
+ * {Number} borderPadding The width in pixels beyond the map border,
+ * where markers should be display.
+ * {Boolean} trackMarkers Whether or not this manager should track marker
+ * movements.
+ */
+function MarkerManager(map, opt_opts) {
+ var me = this;
+ me.map_ = map;
+ me.mapZoom_ = map.getZoom();
+ me.projection_ = map.getCurrentMapType().getProjection();
+
+ opt_opts = opt_opts || {};
+ me.tileSize_ = MarkerManager.DEFAULT_TILE_SIZE_;
+
+ var mapTypes = map.getMapTypes();
+ var mapMaxZoom = mapTypes[0].getMaximumResolution();
+ for (var i = 0; i < mapTypes.length; i++) {
+ var mapTypeMaxZoom = mapTypes[i].getMaximumResolution();
+ if (mapTypeMaxZoom > mapMaxZoom) {
+ mapMaxZoom = mapTypeMaxZoom;
+ }
+ }
+ me.maxZoom_ = opt_opts.maxZoom || mapMaxZoom;
+
+ me.trackMarkers_ = opt_opts.trackMarkers;
+ me.show_ = opt_opts.show || true;
+
+ var padding;
+ if (typeof opt_opts.borderPadding === "number") {
+ padding = opt_opts.borderPadding;
+ } else {
+ padding = MarkerManager.DEFAULT_BORDER_PADDING_;
+ }
+ // The padding in pixels beyond the viewport, where we will pre-load markers.
+ me.swPadding_ = new GSize(-padding, padding);
+ me.nePadding_ = new GSize(padding, -padding);
+ me.borderPadding_ = padding;
+
+ me.gridWidth_ = [];
+
+ me.grid_ = [];
+ me.grid_[me.maxZoom_] = [];
+ me.numMarkers_ = [];
+ me.numMarkers_[me.maxZoom_] = 0;
+
+ GEvent.bind(map, "moveend", me, me.onMapMoveEnd_);
+
+ // NOTE: These two closures provide easy access to the map.
+ // They are used as callbacks, not as methods.
+ me.removeOverlay_ = function (marker) {
+ map.removeOverlay(marker);
+ me.shownMarkers_--;
+ };
+ me.addOverlay_ = function (marker) {
+ if (me.show_) {
+ map.addOverlay(marker);
+ me.shownMarkers_++;
+ }
+ };
+
+ me.resetManager_();
+ me.shownMarkers_ = 0;
+
+ me.shownBounds_ = me.getMapGridBounds_();
+}
+
+// Static constants:
+MarkerManager.DEFAULT_TILE_SIZE_ = 1024;
+MarkerManager.DEFAULT_BORDER_PADDING_ = 100;
+MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE = 256;
+
+
+/**
+ * Initializes MarkerManager arrays for all zoom levels
+ * Called by constructor and by clearAllMarkers
+ */
+MarkerManager.prototype.resetManager_ = function () {
+ var me = this;
+ var mapWidth = MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE;
+ for (var zoom = 0; zoom <= me.maxZoom_; ++zoom) {
+ me.grid_[zoom] = [];
+ me.numMarkers_[zoom] = 0;
+ me.gridWidth_[zoom] = Math.ceil(mapWidth / me.tileSize_);
+ mapWidth <<= 1;
+ }
+};
+
+/**
+ * Removes all markers in the manager, and
+ * removes any visible markers from the map.
+ */
+MarkerManager.prototype.clearMarkers = function () {
+ var me = this;
+ me.processAll_(me.shownBounds_, me.removeOverlay_);
+ me.resetManager_();
+};
+
+
+/**
+ * Gets the tile coordinate for a given latlng point.
+ *
+ * @param {LatLng} latlng The geographical point.
+ * @param {Number} zoom The zoom level.
+ * @param {GSize} padding The padding used to shift the pixel coordinate.
+ * Used for expanding a bounds to include an extra padding
+ * of pixels surrounding the bounds.
+ * @return {GPoint} The point in tile coordinates.
+ *
+ */
+MarkerManager.prototype.getTilePoint_ = function (latlng, zoom, padding) {
+ var pixelPoint = this.projection_.fromLatLngToPixel(latlng, zoom);
+ return new GPoint(
+ Math.floor((pixelPoint.x + padding.width) / this.tileSize_),
+ Math.floor((pixelPoint.y + padding.height) / this.tileSize_));
+};
+
+
+/**
+ * Finds the appropriate place to add the marker to the grid.
+ * Optimized for speed; does not actually add the marker to the map.
+ * Designed for batch-processing thousands of markers.
+ *
+ * @param {Marker} marker The marker to add.
+ * @param {Number} minZoom The minimum zoom for displaying the marker.
+ * @param {Number} maxZoom The maximum zoom for displaying the marker.
+ */
+MarkerManager.prototype.addMarkerBatch_ = function (marker, minZoom, maxZoom) {
+ var mPoint = marker.getPoint();
+ marker.MarkerManager_minZoom = minZoom;
+ // Tracking markers is expensive, so we do this only if the
+ // user explicitly requested it when creating marker manager.
+ if (this.trackMarkers_) {
+ GEvent.bind(marker, "changed", this, this.onMarkerMoved_);
+ }
+
+ var gridPoint = this.getTilePoint_(mPoint, maxZoom, GSize.ZERO);
+
+ for (var zoom = maxZoom; zoom >= minZoom; zoom--) {
+ var cell = this.getGridCellCreate_(gridPoint.x, gridPoint.y, zoom);
+ cell.push(marker);
+
+ gridPoint.x = gridPoint.x >> 1;
+ gridPoint.y = gridPoint.y >> 1;
+ }
+};
+
+
+/**
+ * Returns whether or not the given point is visible in the shown bounds. This
+ * is a helper method that takes care of the corner case, when shownBounds have
+ * negative minX value.
+ *
+ * @param {Point} point a point on a grid.
+ * @return {Boolean} Whether or not the given point is visible in the currently
+ * shown bounds.
+ */
+MarkerManager.prototype.isGridPointVisible_ = function (point) {
+ var me = this;
+ var vertical = me.shownBounds_.minY <= point.y &&
+ point.y <= me.shownBounds_.maxY;
+ var minX = me.shownBounds_.minX;
+ var horizontal = minX <= point.x && point.x <= me.shownBounds_.maxX;
+ if (!horizontal && minX < 0) {
+ // Shifts the negative part of the rectangle. As point.x is always less
+ // than grid width, only test shifted minX .. 0 part of the shown bounds.
+ var width = me.gridWidth_[me.shownBounds_.z];
+ horizontal = minX + width <= point.x && point.x <= width - 1;
+ }
+ return vertical && horizontal;
+};
+
+
+/**
+ * Reacts to a notification from a marker that it has moved to a new location.
+ * It scans the grid all all zoom levels and moves the marker from the old grid
+ * location to a new grid location.
+ *
+ * @param {Marker} marker The marker that moved.
+ * @param {LatLng} oldPoint The old position of the marker.
+ * @param {LatLng} newPoint The new position of the marker.
+ */
+MarkerManager.prototype.onMarkerMoved_ = function (marker, oldPoint, newPoint) {
+ // NOTE: We do not know the minimum or maximum zoom the marker was
+ // added at, so we start at the absolute maximum. Whenever we successfully
+ // remove a marker at a given zoom, we add it at the new grid coordinates.
+ var me = this;
+ var zoom = me.maxZoom_;
+ var changed = false;
+ var oldGrid = me.getTilePoint_(oldPoint, zoom, GSize.ZERO);
+ var newGrid = me.getTilePoint_(newPoint, zoom, GSize.ZERO);
+ while (zoom >= 0 && (oldGrid.x !== newGrid.x || oldGrid.y !== newGrid.y)) {
+ var cell = me.getGridCellNoCreate_(oldGrid.x, oldGrid.y, zoom);
+ if (cell) {
+ if (me.removeFromArray_(cell, marker)) {
+ me.getGridCellCreate_(newGrid.x, newGrid.y, zoom).push(marker);
+ }
+ }
+ // For the current zoom we also need to update the map. Markers that no
+ // longer are visible are removed from the map. Markers that moved into
+ // the shown bounds are added to the map. This also lets us keep the count
+ // of visible markers up to date.
+ if (zoom === me.mapZoom_) {
+ if (me.isGridPointVisible_(oldGrid)) {
+ if (!me.isGridPointVisible_(newGrid)) {
+ me.removeOverlay_(marker);
+ changed = true;
+ }
+ } else {
+ if (me.isGridPointVisible_(newGrid)) {
+ me.addOverlay_(marker);
+ changed = true;
+ }
+ }
+ }
+ oldGrid.x = oldGrid.x >> 1;
+ oldGrid.y = oldGrid.y >> 1;
+ newGrid.x = newGrid.x >> 1;
+ newGrid.y = newGrid.y >> 1;
+ --zoom;
+ }
+ if (changed) {
+ me.notifyListeners_();
+ }
+};
+
+
+/**
+ * Removes marker from the manager and from the map
+ * (if it's currently visible).
+ * @param {GMarker} marker The marker to delete.
+ */
+MarkerManager.prototype.removeMarker = function (marker) {
+ var me = this;
+ var zoom = me.maxZoom_;
+ var changed = false;
+ var point = marker.getPoint();
+ var grid = me.getTilePoint_(point, zoom, GSize.ZERO);
+ while (zoom >= 0) {
+ var cell = me.getGridCellNoCreate_(grid.x, grid.y, zoom);
+
+ if (cell) {
+ me.removeFromArray_(cell, marker);
+ }
+ // For the current zoom we also need to update the map. Markers that no
+ // longer are visible are removed from the map. This also lets us keep the count
+ // of visible markers up to date.
+ if (zoom === me.mapZoom_) {
+ if (me.isGridPointVisible_(grid)) {
+ me.removeOverlay_(marker);
+ changed = true;
+ }
+ }
+ grid.x = grid.x >> 1;
+ grid.y = grid.y >> 1;
+ --zoom;
+ }
+ if (changed) {
+ me.notifyListeners_();
+ }
+ me.numMarkers_[marker.MarkerManager_minZoom]--;
+};
+
+
+/**
+ * Add many markers at once.
+ * Does not actually update the map, just the internal grid.
+ *
+ * @param {Array of Marker} markers The markers to add.
+ * @param {Number} minZoom The minimum zoom level to display the markers.
+ * @param {Number} opt_maxZoom The maximum zoom level to display the markers.
+ */
+MarkerManager.prototype.addMarkers = function (markers, minZoom, opt_maxZoom) {
+ var maxZoom = this.getOptMaxZoom_(opt_maxZoom);
+ for (var i = markers.length - 1; i >= 0; i--) {
+ this.addMarkerBatch_(markers[i], minZoom, maxZoom);
+ }
+
+ this.numMarkers_[minZoom] += markers.length;
+};
+
+
+/**
+ * Returns the value of the optional maximum zoom. This method is defined so
+ * that we have just one place where optional maximum zoom is calculated.
+ *
+ * @param {Number} opt_maxZoom The optinal maximum zoom.
+ * @return The maximum zoom.
+ */
+MarkerManager.prototype.getOptMaxZoom_ = function (opt_maxZoom) {
+ return opt_maxZoom || this.maxZoom_;
+};
+
+
+/**
+ * Calculates the total number of markers potentially visible at a given
+ * zoom level.
+ *
+ * @param {Number} zoom The zoom level to check.
+ */
+MarkerManager.prototype.getMarkerCount = function (zoom) {
+ var total = 0;
+ for (var z = 0; z <= zoom; z++) {
+ total += this.numMarkers_[z];
+ }
+ return total;
+};
+
+/**
+ * Returns a marker given latitude, longitude and zoom. If the marker does not
+ * exist, the method will return a new marker. If a new marker is created,
+ * it will NOT be added to the manager.
+ *
+ * @param {Number} lat - the latitude of a marker.
+ * @param {Number} lng - the longitude of a marker.
+ * @param {Number} zoom - the zoom level
+ * @return {GMarker} marker - the marker found at lat and lng
+ */
+MarkerManager.prototype.getMarker = function(lat, lng, zoom) {
+ var me = this;
+ var mPoint = new GLatLng(lat, lng);
+ var gridPoint = me.getTilePoint_(mPoint, zoom, GSize.ZERO);
+
+ var marker = new GMarker(mPoint);
+ var cellArray = me.getGridCellNoCreate_(gridPoint.x, gridPoint.y, zoom);
+ if(cellArray != undefined){
+ for (var i = 0; i < cellArray.length; i++)
+ {
+ if(lat == cellArray[i].getLatLng().lat() &&
+ lng == cellArray[i].getLatLng().lng())
+ {
+ marker = cellArray[i];
+ }
+ }
+ }
+ return marker;
+};
+
+/**
+ * Add a single marker to the map.
+ *
+ * @param {Marker} marker The marker to add.
+ * @param {Number} minZoom The minimum zoom level to display the marker.
+ * @param {Number} opt_maxZoom The maximum zoom level to display the marker.
+ */
+MarkerManager.prototype.addMarker = function (marker, minZoom, opt_maxZoom) {
+ var me = this;
+ var maxZoom = this.getOptMaxZoom_(opt_maxZoom);
+ me.addMarkerBatch_(marker, minZoom, maxZoom);
+ var gridPoint = me.getTilePoint_(marker.getPoint(), me.mapZoom_, GSize.ZERO);
+ if (me.isGridPointVisible_(gridPoint) &&
+ minZoom <= me.shownBounds_.z &&
+ me.shownBounds_.z <= maxZoom) {
+ me.addOverlay_(marker);
+ me.notifyListeners_();
+ }
+ this.numMarkers_[minZoom]++;
+};
+
+/**
+ * Returns true if this bounds (inclusively) contains the given point.
+ * @param {Point} point The point to test.
+ * @return {Boolean} This Bounds contains the given Point.
+ */
+GBounds.prototype.containsPoint = function (point) {
+ var outer = this;
+ return (outer.minX <= point.x &&
+ outer.maxX >= point.x &&
+ outer.minY <= point.y &&
+ outer.maxY >= point.y);
+};
+
+/**
+ * Get a cell in the grid, creating it first if necessary.
+ *
+ * Optimization candidate
+ *
+ * @param {Number} x The x coordinate of the cell.
+ * @param {Number} y The y coordinate of the cell.
+ * @param {Number} z The z coordinate of the cell.
+ * @return {Array} The cell in the array.
+ */
+MarkerManager.prototype.getGridCellCreate_ = function (x, y, z) {
+ var grid = this.grid_[z];
+ if (x < 0) {
+ x += this.gridWidth_[z];
+ }
+ var gridCol = grid[x];
+ if (!gridCol) {
+ gridCol = grid[x] = [];
+ return (gridCol[y] = []);
+ }
+ var gridCell = gridCol[y];
+ if (!gridCell) {
+ return (gridCol[y] = []);
+ }
+ return gridCell;
+};
+
+
+/**
+ * Get a cell in the grid, returning undefined if it does not exist.
+ *
+ * NOTE: Optimized for speed -- otherwise could combine with getGridCellCreate_.
+ *
+ * @param {Number} x The x coordinate of the cell.
+ * @param {Number} y The y coordinate of the cell.
+ * @param {Number} z The z coordinate of the cell.
+ * @return {Array} The cell in the array.
+ */
+MarkerManager.prototype.getGridCellNoCreate_ = function (x, y, z) {
+ var grid = this.grid_[z];
+ if (x < 0) {
+ x += this.gridWidth_[z];
+ }
+ var gridCol = grid[x];
+ return gridCol ? gridCol[y] : undefined;
+};
+
+
+/**
+ * Turns at geographical bounds into a grid-space bounds.
+ *
+ * @param {LatLngBounds} bounds The geographical bounds.
+ * @param {Number} zoom The zoom level of the bounds.
+ * @param {GSize} swPadding The padding in pixels to extend beyond the
+ * given bounds.
+ * @param {GSize} nePadding The padding in pixels to extend beyond the
+ * given bounds.
+ * @return {GBounds} The bounds in grid space.
+ */
+MarkerManager.prototype.getGridBounds_ = function (bounds, zoom, swPadding, nePadding) {
+ zoom = Math.min(zoom, this.maxZoom_);
+
+ var bl = bounds.getSouthWest();
+ var tr = bounds.getNorthEast();
+ var sw = this.getTilePoint_(bl, zoom, swPadding);
+ var ne = this.getTilePoint_(tr, zoom, nePadding);
+ var gw = this.gridWidth_[zoom];
+
+ // Crossing the prime meridian requires correction of bounds.
+ if (tr.lng() < bl.lng() || ne.x < sw.x) {
+ sw.x -= gw;
+ }
+ if (ne.x - sw.x + 1 >= gw) {
+ // Computed grid bounds are larger than the world; truncate.
+ sw.x = 0;
+ ne.x = gw - 1;
+ }
+ var gridBounds = new GBounds([sw, ne]);
+ gridBounds.z = zoom;
+ return gridBounds;
+};
+
+
+/**
+ * Gets the grid-space bounds for the current map viewport.
+ *
+ * @return {Bounds} The bounds in grid space.
+ */
+MarkerManager.prototype.getMapGridBounds_ = function () {
+ var me = this;
+ return me.getGridBounds_(me.map_.getBounds(), me.mapZoom_, me.swPadding_, me.nePadding_);
+};
+
+
+/**
+ * Event listener for map:movend.
+ * NOTE: Use a timeout so that the user is not blocked
+ * from moving the map.
+ *
+ */
+MarkerManager.prototype.onMapMoveEnd_ = function () {
+ var me = this;
+ me.objectSetTimeout_(this, this.updateMarkers_, 0);
+};
+
+
+/**
+ * Call a function or evaluate an expression after a specified number of
+ * milliseconds.
+ *
+ * Equivalent to the standard window.setTimeout function, but the given
+ * function executes as a method of this instance. So the function passed to
+ * objectSetTimeout can contain references to this.
+ * objectSetTimeout(this, function () { alert(this.x) }, 1000);
+ *
+ * @param {Object} object The target object.
+ * @param {Function} command The command to run.
+ * @param {Number} milliseconds The delay.
+ * @return {Boolean} Success.
+ */
+MarkerManager.prototype.objectSetTimeout_ = function (object, command, milliseconds) {
+ return window.setTimeout(function () {
+ command.call(object);
+ }, milliseconds);
+};
+
+
+/**
+ * Is this layer visible?
+ *
+ * Returns visibility setting
+ *
+ * @return {Boolean} Visible
+ */
+MarkerManager.prototype.visible = function () {
+ return this.show_ ? true : false;
+};
+
+
+/**
+ * Returns true if the manager is hidden.
+ * Otherwise returns false.
+ * @return {Boolean} Hidden
+ */
+MarkerManager.prototype.isHidden = function () {
+ return !this.show_;
+};
+
+
+/**
+ * Shows the manager if it's currently hidden.
+ */
+MarkerManager.prototype.show = function () {
+ this.show_ = true;
+ this.refresh();
+};
+
+
+/**
+ * Hides the manager if it's currently visible
+ */
+MarkerManager.prototype.hide = function () {
+ this.show_ = false;
+ this.refresh();
+};
+
+
+/**
+ * Toggles the visibility of the manager.
+ */
+MarkerManager.prototype.toggle = function () {
+ this.show_ = !this.show_;
+ this.refresh();
+};
+
+
+/**
+ * Refresh forces the marker-manager into a good state.
+ * <ol>
+ * <li>If never before initialized, shows all the markers.</li>
+ * <li>If previously initialized, removes and re-adds all markers.</li>
+ * </ol>
+ */
+MarkerManager.prototype.refresh = function () {
+ var me = this;
+ if (me.shownMarkers_ > 0) {
+ me.processAll_(me.shownBounds_, me.removeOverlay_);
+ }
+ // An extra check on me.show_ to increase performance (no need to processAll_)
+ if (me.show_) {
+ me.processAll_(me.shownBounds_, me.addOverlay_);
+ }
+ me.notifyListeners_();
+};
+
+
+/**
+ * After the viewport may have changed, add or remove markers as needed.
+ */
+MarkerManager.prototype.updateMarkers_ = function () {
+ var me = this;
+ me.mapZoom_ = this.map_.getZoom();
+ var newBounds = me.getMapGridBounds_();
+
+ // If the move does not include new grid sections,
+ // we have no work to do:
+ if (newBounds.equals(me.shownBounds_) && newBounds.z === me.shownBounds_.z) {
+ return;
+ }
+
+ if (newBounds.z !== me.shownBounds_.z) {
+ me.processAll_(me.shownBounds_, me.removeOverlay_);
+ if (me.show_) { // performance
+ me.processAll_(newBounds, me.addOverlay_);
+ }
+ } else {
+ // Remove markers:
+ me.rectangleDiff_(me.shownBounds_, newBounds, me.removeCellMarkers_);
+
+ // Add markers:
+ if (me.show_) { // performance
+ me.rectangleDiff_(newBounds, me.shownBounds_, me.addCellMarkers_);
+ }
+ }
+ me.shownBounds_ = newBounds;
+
+ me.notifyListeners_();
+};
+
+
+/**
+ * Notify listeners when the state of what is displayed changes.
+ */
+MarkerManager.prototype.notifyListeners_ = function () {
+ GEvent.trigger(this, "changed", this.shownBounds_, this.shownMarkers_);
+};
+
+
+/**
+ * Process all markers in the bounds provided, using a callback.
+ *
+ * @param {Bounds} bounds The bounds in grid space.
+ * @param {Function} callback The function to call for each marker.
+ */
+MarkerManager.prototype.processAll_ = function (bounds, callback) {
+ for (var x = bounds.minX; x <= bounds.maxX; x++) {
+ for (var y = bounds.minY; y <= bounds.maxY; y++) {
+ this.processCellMarkers_(x, y, bounds.z, callback);
+ }
+ }
+};
+
+
+/**
+ * Process all markers in the grid cell, using a callback.
+ *
+ * @param {Number} x The x coordinate of the cell.
+ * @param {Number} y The y coordinate of the cell.
+ * @param {Number} z The z coordinate of the cell.
+ * @param {Function} callback The function to call for each marker.
+ */
+MarkerManager.prototype.processCellMarkers_ = function (x, y, z, callback) {
+ var cell = this.getGridCellNoCreate_(x, y, z);
+ if (cell) {
+ for (var i = cell.length - 1; i >= 0; i--) {
+ callback(cell[i]);
+ }
+ }
+};
+
+
+/**
+ * Remove all markers in a grid cell.
+ *
+ * @param {Number} x The x coordinate of the cell.
+ * @param {Number} y The y coordinate of the cell.
+ * @param {Number} z The z coordinate of the cell.
+ */
+MarkerManager.prototype.removeCellMarkers_ = function (x, y, z) {
+ this.processCellMarkers_(x, y, z, this.removeOverlay_);
+};
+
+
+/**
+ * Add all markers in a grid cell.
+ *
+ * @param {Number} x The x coordinate of the cell.
+ * @param {Number} y The y coordinate of the cell.
+ * @param {Number} z The z coordinate of the cell.
+ */
+MarkerManager.prototype.addCellMarkers_ = function (x, y, z) {
+ this.processCellMarkers_(x, y, z, this.addOverlay_);
+};
+
+
+/**
+ * Use the rectangleDiffCoords_ function to process all grid cells
+ * that are in bounds1 but not bounds2, using a callback, and using
+ * the current MarkerManager object as the instance.
+ *
+ * Pass the z parameter to the callback in addition to x and y.
+ *
+ * @param {Bounds} bounds1 The bounds of all points we may process.
+ * @param {Bounds} bounds2 The bounds of points to exclude.
+ * @param {Function} callback The callback function to call
+ * for each grid coordinate (x, y, z).
+ */
+MarkerManager.prototype.rectangleDiff_ = function (bounds1, bounds2, callback) {
+ var me = this;
+ me.rectangleDiffCoords_(bounds1, bounds2, function (x, y) {
+ callback.apply(me, [x, y, bounds1.z]);
+ });
+};
+
+
+/**
+ * Calls the function for all points in bounds1, not in bounds2
+ *
+ * @param {Bounds} bounds1 The bounds of all points we may process.
+ * @param {Bounds} bounds2 The bounds of points to exclude.
+ * @param {Function} callback The callback function to call
+ * for each grid coordinate.
+ */
+MarkerManager.prototype.rectangleDiffCoords_ = function (bounds1, bounds2, callback) {
+ var minX1 = bounds1.minX;
+ var minY1 = bounds1.minY;
+ var maxX1 = bounds1.maxX;
+ var maxY1 = bounds1.maxY;
+ var minX2 = bounds2.minX;
+ var minY2 = bounds2.minY;
+ var maxX2 = bounds2.maxX;
+ var maxY2 = bounds2.maxY;
+
+ var x, y;
+ for (x = minX1; x <= maxX1; x++) { // All x in R1
+ // All above:
+ for (y = minY1; y <= maxY1 && y < minY2; y++) { // y in R1 above R2
+ callback(x, y);
+ }
+ // All below:
+ for (y = Math.max(maxY2 + 1, minY1); // y in R1 below R2
+ y <= maxY1; y++) {
+ callback(x, y);
+ }
+ }
+
+ for (y = Math.max(minY1, minY2);
+ y <= Math.min(maxY1, maxY2); y++) { // All y in R2 and in R1
+ // Strictly left:
+ for (x = Math.min(maxX1 + 1, minX2) - 1;
+ x >= minX1; x--) { // x in R1 left of R2
+ callback(x, y);
+ }
+ // Strictly right:
+ for (x = Math.max(minX1, maxX2 + 1); // x in R1 right of R2
+ x <= maxX1; x++) {
+ callback(x, y);
+ }
+ }
+};
+
+
+/**
+ * Removes value from array. O(N).
+ *
+ * @param {Array} array The array to modify.
+ * @param {any} value The value to remove.
+ * @param {Boolean} opt_notype Flag to disable type checking in equality.
+ * @return {Number} The number of instances of value that were removed.
+ */
+MarkerManager.prototype.removeFromArray_ = function (array, value, opt_notype) {
+ var shift = 0;
+ for (var i = 0; i < array.length; ++i) {
+ if (array[i] === value || (opt_notype && array[i] === value)) {
+ array.splice(i--, 1);
+ shift++;
+ }
+ }
+ return shift;
+};
|
kurtchen/hk_macau
|
38f302e8f4ba4565a7ed524c3397b57a224658f3
|
Initial Creation
|
diff --git a/css/main.css b/css/main.css
new file mode 100644
index 0000000..1908b48
--- /dev/null
+++ b/css/main.css
@@ -0,0 +1,178 @@
+body
+{
+ margin:0;
+ padding:0;
+}
+/* ---------------Tabs-------------------- */
+.TabsArea
+{
+ overflow:hidden;
+ margin:auto;
+}
+.TabsArea .TabMenu
+{
+ position: relative;
+ top: 5px;
+ left: 2px;
+ z-index: 10;
+}
+.TabsArea .TabMenu span
+{
+ display: inline-block;
+ height: 85px;
+ width: 130px;
+ margin: 0px;
+ padding:0px;
+ font-family: "é»ä½","å®ä½",Verdana,Serif;
+ font-size: large;
+ font-weight: bold;
+ text-align: center;
+ vertical-align: middle;
+ cursor: pointer;
+}
+.TabsArea .TabMenu .CameraIcon
+{
+ height: 56px;
+ width: 56px;
+ margin-top: 2px;
+ margin-left: 3px;
+ margin-right: 3px;
+}
+/* ---------------Slider-------------------- */
+#slider {
+ width: 800px;
+ margin-top: 10px;
+ position: relative;
+ border: 10px solid #ccc;
+}
+.ScrollPanes {
+ overflow: hidden;
+ height: 150px;
+ width: 800px;
+ margin: 0 auto;
+ position: relative;
+}
+.ScrollContainer {
+ position: relative;
+}
+.ScrollContainer img{
+ margin-top: 65px;
+}
+.ScrollContainer div{
+ float: left;
+ position: relative;
+}
+
+.ScrollContainer div.Panel {
+ padding: 10px;
+ width: 130px;
+ /*height: 318px;*/
+}
+
+.ScrollContainer .Panel .inside {
+ padding: 5px;
+ border: 1px solid #999;
+}
+
+.ScrollContainer .Panel .inside img {
+ display: block;
+ border: 1px solid #666;
+ margin: 0 0 3px 0;
+ width: 100px;
+}
+
+.ScrollContainer .Panel .inside span {
+ font-weight: normal;
+ color: #111;
+ font-size: 12px;
+}
+
+.ScrollContainer .Panel .inside p {
+ font-size: 11px;
+ color: #ccc;
+}
+a {
+ color: #999;
+ text-decoration: none;
+ border-bottom: 1px dotted #ccc;
+}
+
+a:hover {
+ border-bottom: 1px solid #999;
+}
+
+.ScrollButtons {
+ position: absolute;
+ top: 46px;
+ cursor: pointer;
+}
+
+.ScrollButtons.left {
+ left: -45px;
+}
+
+.ScrollButtons.right {
+ right: -45px;
+}
+
+#left_shadow {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 12px;
+ bottom: 0;
+ background: url(../img/leftshadow.png) repeat-y;
+}
+#right_shadow {
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: 12px;
+ bottom: 0;
+ background: url(../img/rightshadow.png) repeat-y;
+}
+/* ---------------Map-------------------- */
+#hk_map {
+ position: relative;
+ width: 800px;
+ height: 430px;
+ border: 10px solid #ccc;
+}
+/*.TabsArea .ContentFrame
+{
+ height:206px;
+ left: 10px;
+ position: relative;
+ overflow:hidden;
+}
+.TabsArea .ContentFrame .AllTabs
+{
+ position: relative;
+ left:0px;
+ width: 1190px;
+ height: 206px;
+ overflow:hidden;
+}
+.TabsArea .ContentFrame .AllTabs .TabContent
+{
+ height: 200px;
+ margin-right:20px;
+ text-align: justify;
+ float:left;
+ overflow:hidden;
+}*/
+/*------------------Others-----------------------*/
+.hide {
+ display: none;
+}
+.selector
+{
+ background: url(../img/selector.png);
+}
+
+.hovering
+{
+ background: url(../img/selector.png);
+ opacity: 0.5;
+ filter: alpha(opacity=50);
+}
\ No newline at end of file
diff --git a/img/Contact.png b/img/Contact.png
new file mode 100644
index 0000000..9a93e12
Binary files /dev/null and b/img/Contact.png differ
diff --git a/img/Drive.png b/img/Drive.png
new file mode 100644
index 0000000..8007fcb
Binary files /dev/null and b/img/Drive.png differ
diff --git a/img/Thumbs.db b/img/Thumbs.db
new file mode 100644
index 0000000..f81ec69
Binary files /dev/null and b/img/Thumbs.db differ
diff --git a/img/camera/camera_1.png b/img/camera/camera_1.png
new file mode 100644
index 0000000..4377acd
Binary files /dev/null and b/img/camera/camera_1.png differ
diff --git a/img/camera/camera_2.png b/img/camera/camera_2.png
new file mode 100644
index 0000000..293bc86
Binary files /dev/null and b/img/camera/camera_2.png differ
diff --git a/img/camera/camera_21.png b/img/camera/camera_21.png
new file mode 100644
index 0000000..8a7ae53
Binary files /dev/null and b/img/camera/camera_21.png differ
diff --git a/img/camera/camera_22.png b/img/camera/camera_22.png
new file mode 100644
index 0000000..2423752
Binary files /dev/null and b/img/camera/camera_22.png differ
diff --git a/img/camera/camera_23.png b/img/camera/camera_23.png
new file mode 100644
index 0000000..50fee87
Binary files /dev/null and b/img/camera/camera_23.png differ
diff --git a/img/camera/camera_24.png b/img/camera/camera_24.png
new file mode 100644
index 0000000..df6c080
Binary files /dev/null and b/img/camera/camera_24.png differ
diff --git a/img/camera/camera_25.png b/img/camera/camera_25.png
new file mode 100644
index 0000000..fe19d8e
Binary files /dev/null and b/img/camera/camera_25.png differ
diff --git a/img/camera/camera_3.png b/img/camera/camera_3.png
new file mode 100644
index 0000000..f7203d6
Binary files /dev/null and b/img/camera/camera_3.png differ
diff --git a/img/camera/camera_31.png b/img/camera/camera_31.png
new file mode 100644
index 0000000..fb35c82
Binary files /dev/null and b/img/camera/camera_31.png differ
diff --git a/img/camera/camera_32.png b/img/camera/camera_32.png
new file mode 100644
index 0000000..1653a37
Binary files /dev/null and b/img/camera/camera_32.png differ
diff --git a/img/camera/camera_4.png b/img/camera/camera_4.png
new file mode 100644
index 0000000..fc1c26d
Binary files /dev/null and b/img/camera/camera_4.png differ
diff --git a/img/camera/camera_41.png b/img/camera/camera_41.png
new file mode 100644
index 0000000..8f6dd86
Binary files /dev/null and b/img/camera/camera_41.png differ
diff --git a/img/camera/camera_42.png b/img/camera/camera_42.png
new file mode 100644
index 0000000..7880201
Binary files /dev/null and b/img/camera/camera_42.png differ
diff --git a/img/camera/camera_43.png b/img/camera/camera_43.png
new file mode 100644
index 0000000..3bad578
Binary files /dev/null and b/img/camera/camera_43.png differ
diff --git a/img/camera/camera_44.png b/img/camera/camera_44.png
new file mode 100644
index 0000000..dad7b34
Binary files /dev/null and b/img/camera/camera_44.png differ
diff --git a/img/camera/camera_45.png b/img/camera/camera_45.png
new file mode 100644
index 0000000..ea35e72
Binary files /dev/null and b/img/camera/camera_45.png differ
diff --git a/img/camera/camera_46.png b/img/camera/camera_46.png
new file mode 100644
index 0000000..28eb801
Binary files /dev/null and b/img/camera/camera_46.png differ
diff --git a/img/camera/camera_47.png b/img/camera/camera_47.png
new file mode 100644
index 0000000..a5e5b4c
Binary files /dev/null and b/img/camera/camera_47.png differ
diff --git a/img/camera/camera_49.png b/img/camera/camera_49.png
new file mode 100644
index 0000000..78b6878
Binary files /dev/null and b/img/camera/camera_49.png differ
diff --git a/img/camera/camera_5.png b/img/camera/camera_5.png
new file mode 100644
index 0000000..9332cdd
Binary files /dev/null and b/img/camera/camera_5.png differ
diff --git a/img/hongkong/hongkong1.jpg b/img/hongkong/hongkong1.jpg
new file mode 100644
index 0000000..0a31f7e
Binary files /dev/null and b/img/hongkong/hongkong1.jpg differ
diff --git a/img/hongkong/hongkong2.jpg b/img/hongkong/hongkong2.jpg
new file mode 100644
index 0000000..23adf09
Binary files /dev/null and b/img/hongkong/hongkong2.jpg differ
diff --git a/img/hongkong/hongkong3.jpg b/img/hongkong/hongkong3.jpg
new file mode 100644
index 0000000..bcbd324
Binary files /dev/null and b/img/hongkong/hongkong3.jpg differ
diff --git a/img/hongkong/hongkong4.jpg b/img/hongkong/hongkong4.jpg
new file mode 100644
index 0000000..b49df10
Binary files /dev/null and b/img/hongkong/hongkong4.jpg differ
diff --git a/img/hongkong/hongkong5.jpg b/img/hongkong/hongkong5.jpg
new file mode 100644
index 0000000..2141d3c
Binary files /dev/null and b/img/hongkong/hongkong5.jpg differ
diff --git a/img/iPod.png b/img/iPod.png
new file mode 100644
index 0000000..8f7fe10
Binary files /dev/null and b/img/iPod.png differ
diff --git a/img/leftarrow.png b/img/leftarrow.png
new file mode 100644
index 0000000..5702bb1
Binary files /dev/null and b/img/leftarrow.png differ
diff --git a/img/leftshadow.png b/img/leftshadow.png
new file mode 100644
index 0000000..2bbc771
Binary files /dev/null and b/img/leftshadow.png differ
diff --git a/img/loading.gif b/img/loading.gif
new file mode 100644
index 0000000..d84f653
Binary files /dev/null and b/img/loading.gif differ
diff --git a/img/macau/macau.jpg b/img/macau/macau.jpg
new file mode 100644
index 0000000..12cf762
Binary files /dev/null and b/img/macau/macau.jpg differ
diff --git a/img/rightarrow.png b/img/rightarrow.png
new file mode 100644
index 0000000..2a63e46
Binary files /dev/null and b/img/rightarrow.png differ
diff --git a/img/rightshadow.png b/img/rightshadow.png
new file mode 100644
index 0000000..58b2b03
Binary files /dev/null and b/img/rightshadow.png differ
diff --git a/img/selector.png b/img/selector.png
new file mode 100644
index 0000000..2ff3a29
Binary files /dev/null and b/img/selector.png differ
diff --git a/img/selector2.png b/img/selector2.png
new file mode 100644
index 0000000..862e25f
Binary files /dev/null and b/img/selector2.png differ
diff --git a/img/selector_bak.png b/img/selector_bak.png
new file mode 100644
index 0000000..ec54831
Binary files /dev/null and b/img/selector_bak.png differ
diff --git a/img/slideTabbg.png b/img/slideTabbg.png
new file mode 100644
index 0000000..3e4f4ff
Binary files /dev/null and b/img/slideTabbg.png differ
diff --git a/img/slider/1.jpg b/img/slider/1.jpg
new file mode 100644
index 0000000..d025210
Binary files /dev/null and b/img/slider/1.jpg differ
diff --git a/img/slider/2.jpg b/img/slider/2.jpg
new file mode 100644
index 0000000..63292eb
Binary files /dev/null and b/img/slider/2.jpg differ
diff --git a/img/slider/3.jpg b/img/slider/3.jpg
new file mode 100644
index 0000000..3908aab
Binary files /dev/null and b/img/slider/3.jpg differ
diff --git a/img/slider/4.jpg b/img/slider/4.jpg
new file mode 100644
index 0000000..29c6f64
Binary files /dev/null and b/img/slider/4.jpg differ
diff --git a/img/slider/5.jpg b/img/slider/5.jpg
new file mode 100644
index 0000000..63892a2
Binary files /dev/null and b/img/slider/5.jpg differ
diff --git a/img/under_construction.jpg b/img/under_construction.jpg
new file mode 100644
index 0000000..060e1c4
Binary files /dev/null and b/img/under_construction.jpg differ
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..5100765
--- /dev/null
+++ b/index.html
@@ -0,0 +1,43 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <title>HongKong & Macau in 5 Days</title>
+ <script src="js/jquery.js" type="text/javascript"></script>
+ <link rel="stylesheet" type="text/css" href="css/main.css" />
+ <script src="js/main.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <center>
+ <div class="TabsArea">
+ <div class="TabMenu">
+ <span><img src="img/contact.png" /></span>
+ <span><img src="img/ipod.png" /></span>
+ <span><img src="img/drive.png" /></span>
+ <span><img src="img/ipod.png" /></span>
+ <span><img src="img/drive.png" /></span>
+ </div>
+ <div class="ContentFrame">
+ <div class="AllTabs">
+ <div class="TabContent">
+ <img src="photo/sample.jpg" height="100" width="100"/>
+ </div>
+ <div class="TabContent">
+ <img src="photo/sample.jpg" height="100" width="100"/>
+ </div>
+ <div class="TabContent">
+ <img src="photo/sample.jpg" height="200" width="200"/>
+ </div>
+ <div class="TabContent">
+ <img src="photo/sample.jpg" height="100" width="100"/>
+ </div>
+ <div class="TabContent">
+ <img src="photo/sample.jpg" height="100" width="100"/>
+ </div>
+ </div>
+ </div>
+ </div>
+ </center>
+ </body>
+</html>
diff --git a/index.php b/index.php
new file mode 100644
index 0000000..254253c
--- /dev/null
+++ b/index.php
@@ -0,0 +1,87 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <title>HongKong & Macau in 5 Days</title>
+ <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
+ <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
+ <link rel="stylesheet" type="text/css" href="css/main.css" />
+ <script src="js/main.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <center>
+ <div class="TabsArea">
+ <div id="tab_menu" class="TabMenu">
+ <img src="img/loading.gif" width="220" height="19"/>
+ <!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
+ <span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
+ <span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
+ <span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
+ <span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
+ </div>
+<!--############################Begine Slider###########################################-->
+ <div id="slider">
+ <img class="ScrollButtons left" src="img/leftarrow.png">
+ <div class="ScrollPanes">
+ <div class="ScrollContainer">
+<!-- <img src="img/loading.gif" width="220" height="19"/> -->
+<!--
+ <div class="Panel" id="panel_1">
+ <div class="inside">
+ <img src="img/slider/1.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_2">
+ <div class="inside">
+ <img src="img/slider/2.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_3">
+ <div class="inside">
+ <img src="img/slider/3.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_4">
+ <div class="inside">
+ <img src="img/slider/4.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_5">
+ <div class="inside">
+ <img src="img/slider/5.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+-->
+ </div>
+ <div id="left_shadow"></div>
+ <div id="right_shadow"></div>
+ </div>
+ <img class="ScrollButtons right" src="img/rightarrow.png">
+ </div>
+<!--############################End Slider###########################################-->
+ </div>
+ <hr/>
+<!--############################Begine Map###########################################-->
+ <div id="hk_map">
+
+ </div>
+<!--############################End Map###########################################-->
+
+<!--
+ <div>
+ <img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
+ </div>
+-->
+ </center>
+ </body>
+</html>
diff --git a/index_static.html b/index_static.html
new file mode 100644
index 0000000..254253c
--- /dev/null
+++ b/index_static.html
@@ -0,0 +1,87 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
+"http://www.w3.org/TR/html4/loose.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+ <title>HongKong & Macau in 5 Days</title>
+ <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
+ <script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAQxf6EB9sjqpbWG4uIOotDxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxToVRqLDusJ3X-caFKb4JyuMzk6Kw&sensor=true" type="text/javascript"></script>
+ <link rel="stylesheet" type="text/css" href="css/main.css" />
+ <script src="js/main.js" type="text/javascript"></script>
+ </head>
+ <body>
+ <center>
+ <div class="TabsArea">
+ <div id="tab_menu" class="TabMenu">
+ <img src="img/loading.gif" width="220" height="19"/>
+ <!--<span id="tab_1"><img class="CameraIcon" src="img/camera/camera_1.png"/>第ä¸å¤©</span>
+ <span id="tab_2"><img class="CameraIcon" src="img/camera/camera_2.png"/>第äºå¤©</span>
+ <span id="tab_3"><img class="CameraIcon" src="img/camera/camera_3.png"/>第ä¸å¤©</span>
+ <span id="tab_4"><img class="CameraIcon" src="img/camera/camera_4.png"/>第å天</span>
+ <span id="tab_5"><img class="CameraIcon" src="img/camera/camera_5.png"/>第äºå¤©</span>-->
+ </div>
+<!--############################Begine Slider###########################################-->
+ <div id="slider">
+ <img class="ScrollButtons left" src="img/leftarrow.png">
+ <div class="ScrollPanes">
+ <div class="ScrollContainer">
+<!-- <img src="img/loading.gif" width="220" height="19"/> -->
+<!--
+ <div class="Panel" id="panel_1">
+ <div class="inside">
+ <img src="img/slider/1.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_2">
+ <div class="inside">
+ <img src="img/slider/2.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_3">
+ <div class="inside">
+ <img src="img/slider/3.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_4">
+ <div class="inside">
+ <img src="img/slider/4.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+ <div class="Panel" id="panel_5">
+ <div class="inside">
+ <img src="img/slider/5.jpg" alt="picture" />
+ <span>News Heading</span>
+ </div>
+ </div>
+-->
+ </div>
+ <div id="left_shadow"></div>
+ <div id="right_shadow"></div>
+ </div>
+ <img class="ScrollButtons right" src="img/rightarrow.png">
+ </div>
+<!--############################End Slider###########################################-->
+ </div>
+ <hr/>
+<!--############################Begine Map###########################################-->
+ <div id="hk_map">
+
+ </div>
+<!--############################End Map###########################################-->
+
+<!--
+ <div>
+ <img border="0" src="http://www.w3schools.com/images/compatible_ie.gif" width="31" height="30" alt="Internet Explorer" title="Internet Explorer 6" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_firefox.gif" width="31" height="30" alt="Firefox" title="Firefox 3.5" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_opera.gif" width="32" height="30" alt="Opera" title="Opera 10" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_chrome.gif" width="31" height="30" alt="Google Chrome" title="Google Chrome 2" />
+ <img border="0" src="http://www.w3schools.com/images/compatible_safari.gif" width="28" height="30" alt="Safari" title="Safari 3.2.3" />
+ </div>
+-->
+ </center>
+ </body>
+</html>
diff --git a/index_try.html b/index_try.html
new file mode 100644
index 0000000..70aaae3
--- /dev/null
+++ b/index_try.html
@@ -0,0 +1,49 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
+ <title>HongKong & Macau
+in 5 Days</title>
+ <script src="js/jquery.js" type="text/javascript"></script>
+ <link rel="stylesheet" type="text/css" href="css/main.css">
+ <script src="js/main.js" type="text/javascript"></script>
+</head>
+<body>
+<center>
+<div class="TabsArea">
+<div class="TabMenu"><!--<img src="img/loading.gif"/>--> <span><img
+ style="width: 24px; height: 32px;" alt="" src="img/camera.png">第ä¸å¤©</span>
+<span><img src="img/camera.png" align="middle" height="32" width="24">第äº
+天</span>
+<span><img src="img/camera.png" align="middle" height="32" width="24">第ä¸
+天</span>
+<span><img src="img/camera.png" align="middle" height="32" width="24">第å
+天</span>
+<span><img src="img/camera.png" align="middle" height="32" width="24">第äº
+天</span>
+</div>
+<!--
+<div class="ContentFrame">
+<div class="AllTabs">
+<div class="TabContent">
+<img src="photo/sample.jpg" height="100" width="100"/>
+</div>
+<div class="TabContent">
+<img src="photo/sample.jpg" height="100" width="100"/>
+</div>
+<div class="TabContent">
+<img src="photo/sample.jpg" height="200" width="200"/>
+</div>
+<div class="TabContent">
+<img src="photo/sample.jpg" height="100" width="100"/>
+</div>
+<div class="TabContent">
+<img src="photo/sample.jpg" height="100" width="100"/>
+</div>
+</div>
+</div>
+-->
+</div>
+</center>
+</body>
+</html>
diff --git a/index_under.php b/index_under.php
new file mode 100644
index 0000000..f0f4e5f
--- /dev/null
+++ b/index_under.php
@@ -0,0 +1,31 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
+<html>
+<head>
+ <title>Hongkong & Macau
+in 5 Days</title>
+</head>
+<body style="background-color: rgb(0, 0, 0); color: rgb(0, 0, 0);"
+ alink="#ee0000" link="#0000ee" vlink="#551a8b">
+<div style="text-align: center;"><img
+ style="width: 500px; height: 300px;" alt=""
+ src="img/under_construction.jpg"></div>
+<div style="text-align: center;"><img
+ style="width: 134px; height: 88px;" alt=""
+ src="img/hongkong/hongkong2.jpg"><img
+ style="width: 134px; height: 88px;" alt=""
+ src="img/hongkong/hongkong5.jpg"><img
+ style="width: 134px; height: 88px;" alt="" src="img/macau/macau.jpg"></div>
+<div
+ style="text-align: center; color: rgb(204, 204, 204); font-family: Verdana; font-weight: bold;"><br>
+Will come to you soon...<br>
+<br>
+<?php
+ echo date("Y-m-d G:i:s");;
+?>
+<?php
+ echo "<br/>This is git test, on hongkong branch";
+?>
+
+</div>
+</body>
+</html>
diff --git a/js/jquery-1.3.2.min.js b/js/jquery-1.3.2.min.js
new file mode 100644
index 0000000..003c313
--- /dev/null
+++ b/js/jquery-1.3.2.min.js
@@ -0,0 +1,19 @@
+/*
+ * jQuery JavaScript Library v1.3.2
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-02-19 17:34:21 -0500 (Thu, 19 Feb 2009)
+ * Revision: 6246
+ */
+(function(){var l=this,g,y=l.jQuery,p=l.$,o=l.jQuery=l.$=function(E,F){return new o.fn.init(E,F)},D=/^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,f=/^.[^:#\[\.,]*$/;o.fn=o.prototype={init:function(E,H){E=E||document;if(E.nodeType){this[0]=E;this.length=1;this.context=E;return this}if(typeof E==="string"){var G=D.exec(E);if(G&&(G[1]||!H)){if(G[1]){E=o.clean([G[1]],H)}else{var I=document.getElementById(G[3]);if(I&&I.id!=G[3]){return o().find(E)}var F=o(I||[]);F.context=document;F.selector=E;return F}}else{return o(H).find(E)}}else{if(o.isFunction(E)){return o(document).ready(E)}}if(E.selector&&E.context){this.selector=E.selector;this.context=E.context}return this.setArray(o.isArray(E)?E:o.makeArray(E))},selector:"",jquery:"1.3.2",size:function(){return this.length},get:function(E){return E===g?Array.prototype.slice.call(this):this[E]},pushStack:function(F,H,E){var G=o(F);G.prevObject=this;G.context=this.context;if(H==="find"){G.selector=this.selector+(this.selector?" ":"")+E}else{if(H){G.selector=this.selector+"."+H+"("+E+")"}}return G},setArray:function(E){this.length=0;Array.prototype.push.apply(this,E);return this},each:function(F,E){return o.each(this,F,E)},index:function(E){return o.inArray(E&&E.jquery?E[0]:E,this)},attr:function(F,H,G){var E=F;if(typeof F==="string"){if(H===g){return this[0]&&o[G||"attr"](this[0],F)}else{E={};E[F]=H}}return this.each(function(I){for(F in E){o.attr(G?this.style:this,F,o.prop(this,E[F],G,I,F))}})},css:function(E,F){if((E=="width"||E=="height")&&parseFloat(F)<0){F=g}return this.attr(E,F,"curCSS")},text:function(F){if(typeof F!=="object"&&F!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(F))}var E="";o.each(F||this,function(){o.each(this.childNodes,function(){if(this.nodeType!=8){E+=this.nodeType!=1?this.nodeValue:o.fn.text([this])}})});return E},wrapAll:function(E){if(this[0]){var F=o(E,this[0].ownerDocument).clone();if(this[0].parentNode){F.insertBefore(this[0])}F.map(function(){var G=this;while(G.firstChild){G=G.firstChild}return G}).append(this)}return this},wrapInner:function(E){return this.each(function(){o(this).contents().wrapAll(E)})},wrap:function(E){return this.each(function(){o(this).wrapAll(E)})},append:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.appendChild(E)}})},prepend:function(){return this.domManip(arguments,true,function(E){if(this.nodeType==1){this.insertBefore(E,this.firstChild)}})},before:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this)})},after:function(){return this.domManip(arguments,false,function(E){this.parentNode.insertBefore(E,this.nextSibling)})},end:function(){return this.prevObject||o([])},push:[].push,sort:[].sort,splice:[].splice,find:function(E){if(this.length===1){var F=this.pushStack([],"find",E);F.length=0;o.find(E,this[0],F);return F}else{return this.pushStack(o.unique(o.map(this,function(G){return o.find(E,G)})),"find",E)}},clone:function(G){var E=this.map(function(){if(!o.support.noCloneEvent&&!o.isXMLDoc(this)){var I=this.outerHTML;if(!I){var J=this.ownerDocument.createElement("div");J.appendChild(this.cloneNode(true));I=J.innerHTML}return o.clean([I.replace(/ jQuery\d+="(?:\d+|null)"/g,"").replace(/^\s*/,"")])[0]}else{return this.cloneNode(true)}});if(G===true){var H=this.find("*").andSelf(),F=0;E.find("*").andSelf().each(function(){if(this.nodeName!==H[F].nodeName){return}var I=o.data(H[F],"events");for(var K in I){for(var J in I[K]){o.event.add(this,K,I[K][J],I[K][J].data)}}F++})}return E},filter:function(E){return this.pushStack(o.isFunction(E)&&o.grep(this,function(G,F){return E.call(G,F)})||o.multiFilter(E,o.grep(this,function(F){return F.nodeType===1})),"filter",E)},closest:function(E){var G=o.expr.match.POS.test(E)?o(E):null,F=0;return this.map(function(){var H=this;while(H&&H.ownerDocument){if(G?G.index(H)>-1:o(H).is(E)){o.data(H,"closest",F);return H}H=H.parentNode;F++}})},not:function(E){if(typeof E==="string"){if(f.test(E)){return this.pushStack(o.multiFilter(E,this,true),"not",E)}else{E=o.multiFilter(E,this)}}var F=E.length&&E[E.length-1]!==g&&!E.nodeType;return this.filter(function(){return F?o.inArray(this,E)<0:this!=E})},add:function(E){return this.pushStack(o.unique(o.merge(this.get(),typeof E==="string"?o(E):o.makeArray(E))))},is:function(E){return !!E&&o.multiFilter(E,this).length>0},hasClass:function(E){return !!E&&this.is("."+E)},val:function(K){if(K===g){var E=this[0];if(E){if(o.nodeName(E,"option")){return(E.attributes.value||{}).specified?E.value:E.text}if(o.nodeName(E,"select")){var I=E.selectedIndex,L=[],M=E.options,H=E.type=="select-one";if(I<0){return null}for(var F=H?I:0,J=H?I+1:M.length;F<J;F++){var G=M[F];if(G.selected){K=o(G).val();if(H){return K}L.push(K)}}return L}return(E.value||"").replace(/\r/g,"")}return g}if(typeof K==="number"){K+=""}return this.each(function(){if(this.nodeType!=1){return}if(o.isArray(K)&&/radio|checkbox/.test(this.type)){this.checked=(o.inArray(this.value,K)>=0||o.inArray(this.name,K)>=0)}else{if(o.nodeName(this,"select")){var N=o.makeArray(K);o("option",this).each(function(){this.selected=(o.inArray(this.value,N)>=0||o.inArray(this.text,N)>=0)});if(!N.length){this.selectedIndex=-1}}else{this.value=K}}})},html:function(E){return E===g?(this[0]?this[0].innerHTML.replace(/ jQuery\d+="(?:\d+|null)"/g,""):null):this.empty().append(E)},replaceWith:function(E){return this.after(E).remove()},eq:function(E){return this.slice(E,+E+1)},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments),"slice",Array.prototype.slice.call(arguments).join(","))},map:function(E){return this.pushStack(o.map(this,function(G,F){return E.call(G,F,G)}))},andSelf:function(){return this.add(this.prevObject)},domManip:function(J,M,L){if(this[0]){var I=(this[0].ownerDocument||this[0]).createDocumentFragment(),F=o.clean(J,(this[0].ownerDocument||this[0]),I),H=I.firstChild;if(H){for(var G=0,E=this.length;G<E;G++){L.call(K(this[G],H),this.length>1||G>0?I.cloneNode(true):I)}}if(F){o.each(F,z)}}return this;function K(N,O){return M&&o.nodeName(N,"table")&&o.nodeName(O,"tr")?(N.getElementsByTagName("tbody")[0]||N.appendChild(N.ownerDocument.createElement("tbody"))):N}}};o.fn.init.prototype=o.fn;function z(E,F){if(F.src){o.ajax({url:F.src,async:false,dataType:"script"})}else{o.globalEval(F.text||F.textContent||F.innerHTML||"")}if(F.parentNode){F.parentNode.removeChild(F)}}function e(){return +new Date}o.extend=o.fn.extend=function(){var J=arguments[0]||{},H=1,I=arguments.length,E=false,G;if(typeof J==="boolean"){E=J;J=arguments[1]||{};H=2}if(typeof J!=="object"&&!o.isFunction(J)){J={}}if(I==H){J=this;--H}for(;H<I;H++){if((G=arguments[H])!=null){for(var F in G){var K=J[F],L=G[F];if(J===L){continue}if(E&&L&&typeof L==="object"&&!L.nodeType){J[F]=o.extend(E,K||(L.length!=null?[]:{}),L)}else{if(L!==g){J[F]=L}}}}}return J};var b=/z-?index|font-?weight|opacity|zoom|line-?height/i,q=document.defaultView||{},s=Object.prototype.toString;o.extend({noConflict:function(E){l.$=p;if(E){l.jQuery=y}return o},isFunction:function(E){return s.call(E)==="[object Function]"},isArray:function(E){return s.call(E)==="[object Array]"},isXMLDoc:function(E){return E.nodeType===9&&E.documentElement.nodeName!=="HTML"||!!E.ownerDocument&&o.isXMLDoc(E.ownerDocument)},globalEval:function(G){if(G&&/\S/.test(G)){var F=document.getElementsByTagName("head")[0]||document.documentElement,E=document.createElement("script");E.type="text/javascript";if(o.support.scriptEval){E.appendChild(document.createTextNode(G))}else{E.text=G}F.insertBefore(E,F.firstChild);F.removeChild(E)}},nodeName:function(F,E){return F.nodeName&&F.nodeName.toUpperCase()==E.toUpperCase()},each:function(G,K,F){var E,H=0,I=G.length;if(F){if(I===g){for(E in G){if(K.apply(G[E],F)===false){break}}}else{for(;H<I;){if(K.apply(G[H++],F)===false){break}}}}else{if(I===g){for(E in G){if(K.call(G[E],E,G[E])===false){break}}}else{for(var J=G[0];H<I&&K.call(J,H,J)!==false;J=G[++H]){}}}return G},prop:function(H,I,G,F,E){if(o.isFunction(I)){I=I.call(H,F)}return typeof I==="number"&&G=="curCSS"&&!b.test(E)?I+"px":I},className:{add:function(E,F){o.each((F||"").split(/\s+/),function(G,H){if(E.nodeType==1&&!o.className.has(E.className,H)){E.className+=(E.className?" ":"")+H}})},remove:function(E,F){if(E.nodeType==1){E.className=F!==g?o.grep(E.className.split(/\s+/),function(G){return !o.className.has(F,G)}).join(" "):""}},has:function(F,E){return F&&o.inArray(E,(F.className||F).toString().split(/\s+/))>-1}},swap:function(H,G,I){var E={};for(var F in G){E[F]=H.style[F];H.style[F]=G[F]}I.call(H);for(var F in G){H.style[F]=E[F]}},css:function(H,F,J,E){if(F=="width"||F=="height"){var L,G={position:"absolute",visibility:"hidden",display:"block"},K=F=="width"?["Left","Right"]:["Top","Bottom"];function I(){L=F=="width"?H.offsetWidth:H.offsetHeight;if(E==="border"){return}o.each(K,function(){if(!E){L-=parseFloat(o.curCSS(H,"padding"+this,true))||0}if(E==="margin"){L+=parseFloat(o.curCSS(H,"margin"+this,true))||0}else{L-=parseFloat(o.curCSS(H,"border"+this+"Width",true))||0}})}if(H.offsetWidth!==0){I()}else{o.swap(H,G,I)}return Math.max(0,Math.round(L))}return o.curCSS(H,F,J)},curCSS:function(I,F,G){var L,E=I.style;if(F=="opacity"&&!o.support.opacity){L=o.attr(E,"opacity");return L==""?"1":L}if(F.match(/float/i)){F=w}if(!G&&E&&E[F]){L=E[F]}else{if(q.getComputedStyle){if(F.match(/float/i)){F="float"}F=F.replace(/([A-Z])/g,"-$1").toLowerCase();var M=q.getComputedStyle(I,null);if(M){L=M.getPropertyValue(F)}if(F=="opacity"&&L==""){L="1"}}else{if(I.currentStyle){var J=F.replace(/\-(\w)/g,function(N,O){return O.toUpperCase()});L=I.currentStyle[F]||I.currentStyle[J];if(!/^\d+(px)?$/i.test(L)&&/^\d/.test(L)){var H=E.left,K=I.runtimeStyle.left;I.runtimeStyle.left=I.currentStyle.left;E.left=L||0;L=E.pixelLeft+"px";E.left=H;I.runtimeStyle.left=K}}}}return L},clean:function(F,K,I){K=K||document;if(typeof K.createElement==="undefined"){K=K.ownerDocument||K[0]&&K[0].ownerDocument||document}if(!I&&F.length===1&&typeof F[0]==="string"){var H=/^<(\w+)\s*\/?>$/.exec(F[0]);if(H){return[K.createElement(H[1])]}}var G=[],E=[],L=K.createElement("div");o.each(F,function(P,S){if(typeof S==="number"){S+=""}if(!S){return}if(typeof S==="string"){S=S.replace(/(<(\w+)[^>]*?)\/>/g,function(U,V,T){return T.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?U:V+"></"+T+">"});var O=S.replace(/^\s+/,"").substring(0,10).toLowerCase();var Q=!O.indexOf("<opt")&&[1,"<select multiple='multiple'>","</select>"]||!O.indexOf("<leg")&&[1,"<fieldset>","</fieldset>"]||O.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"<table>","</table>"]||!O.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!O.indexOf("<td")||!O.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||!O.indexOf("<col")&&[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"]||!o.support.htmlSerialize&&[1,"div<div>","</div>"]||[0,"",""];L.innerHTML=Q[1]+S+Q[2];while(Q[0]--){L=L.lastChild}if(!o.support.tbody){var R=/<tbody/i.test(S),N=!O.indexOf("<table")&&!R?L.firstChild&&L.firstChild.childNodes:Q[1]=="<table>"&&!R?L.childNodes:[];for(var M=N.length-1;M>=0;--M){if(o.nodeName(N[M],"tbody")&&!N[M].childNodes.length){N[M].parentNode.removeChild(N[M])}}}if(!o.support.leadingWhitespace&&/^\s/.test(S)){L.insertBefore(K.createTextNode(S.match(/^\s*/)[0]),L.firstChild)}S=o.makeArray(L.childNodes)}if(S.nodeType){G.push(S)}else{G=o.merge(G,S)}});if(I){for(var J=0;G[J];J++){if(o.nodeName(G[J],"script")&&(!G[J].type||G[J].type.toLowerCase()==="text/javascript")){E.push(G[J].parentNode?G[J].parentNode.removeChild(G[J]):G[J])}else{if(G[J].nodeType===1){G.splice.apply(G,[J+1,0].concat(o.makeArray(G[J].getElementsByTagName("script"))))}I.appendChild(G[J])}}return E}return G},attr:function(J,G,K){if(!J||J.nodeType==3||J.nodeType==8){return g}var H=!o.isXMLDoc(J),L=K!==g;G=H&&o.props[G]||G;if(J.tagName){var F=/href|src|style/.test(G);if(G=="selected"&&J.parentNode){J.parentNode.selectedIndex}if(G in J&&H&&!F){if(L){if(G=="type"&&o.nodeName(J,"input")&&J.parentNode){throw"type property can't be changed"}J[G]=K}if(o.nodeName(J,"form")&&J.getAttributeNode(G)){return J.getAttributeNode(G).nodeValue}if(G=="tabIndex"){var I=J.getAttributeNode("tabIndex");return I&&I.specified?I.value:J.nodeName.match(/(button|input|object|select|textarea)/i)?0:J.nodeName.match(/^(a|area)$/i)&&J.href?0:g}return J[G]}if(!o.support.style&&H&&G=="style"){return o.attr(J.style,"cssText",K)}if(L){J.setAttribute(G,""+K)}var E=!o.support.hrefNormalized&&H&&F?J.getAttribute(G,2):J.getAttribute(G);return E===null?g:E}if(!o.support.opacity&&G=="opacity"){if(L){J.zoom=1;J.filter=(J.filter||"").replace(/alpha\([^)]*\)/,"")+(parseInt(K)+""=="NaN"?"":"alpha(opacity="+K*100+")")}return J.filter&&J.filter.indexOf("opacity=")>=0?(parseFloat(J.filter.match(/opacity=([^)]*)/)[1])/100)+"":""}G=G.replace(/-([a-z])/ig,function(M,N){return N.toUpperCase()});if(L){J[G]=K}return J[G]},trim:function(E){return(E||"").replace(/^\s+|\s+$/g,"")},makeArray:function(G){var E=[];if(G!=null){var F=G.length;if(F==null||typeof G==="string"||o.isFunction(G)||G.setInterval){E[0]=G}else{while(F){E[--F]=G[F]}}}return E},inArray:function(G,H){for(var E=0,F=H.length;E<F;E++){if(H[E]===G){return E}}return -1},merge:function(H,E){var F=0,G,I=H.length;if(!o.support.getAll){while((G=E[F++])!=null){if(G.nodeType!=8){H[I++]=G}}}else{while((G=E[F++])!=null){H[I++]=G}}return H},unique:function(K){var F=[],E={};try{for(var G=0,H=K.length;G<H;G++){var J=o.data(K[G]);if(!E[J]){E[J]=true;F.push(K[G])}}}catch(I){F=K}return F},grep:function(F,J,E){var G=[];for(var H=0,I=F.length;H<I;H++){if(!E!=!J(F[H],H)){G.push(F[H])}}return G},map:function(E,J){var F=[];for(var G=0,H=E.length;G<H;G++){var I=J(E[G],G);if(I!=null){F[F.length]=I}}return F.concat.apply([],F)}});var C=navigator.userAgent.toLowerCase();o.browser={version:(C.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[0,"0"])[1],safari:/webkit/.test(C),opera:/opera/.test(C),msie:/msie/.test(C)&&!/opera/.test(C),mozilla:/mozilla/.test(C)&&!/(compatible|webkit)/.test(C)};o.each({parent:function(E){return E.parentNode},parents:function(E){return o.dir(E,"parentNode")},next:function(E){return o.nth(E,2,"nextSibling")},prev:function(E){return o.nth(E,2,"previousSibling")},nextAll:function(E){return o.dir(E,"nextSibling")},prevAll:function(E){return o.dir(E,"previousSibling")},siblings:function(E){return o.sibling(E.parentNode.firstChild,E)},children:function(E){return o.sibling(E.firstChild)},contents:function(E){return o.nodeName(E,"iframe")?E.contentDocument||E.contentWindow.document:o.makeArray(E.childNodes)}},function(E,F){o.fn[E]=function(G){var H=o.map(this,F);if(G&&typeof G=="string"){H=o.multiFilter(G,H)}return this.pushStack(o.unique(H),E,G)}});o.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(E,F){o.fn[E]=function(G){var J=[],L=o(G);for(var K=0,H=L.length;K<H;K++){var I=(K>0?this.clone(true):this).get();o.fn[F].apply(o(L[K]),I);J=J.concat(I)}return this.pushStack(J,E,G)}});o.each({removeAttr:function(E){o.attr(this,E,"");if(this.nodeType==1){this.removeAttribute(E)}},addClass:function(E){o.className.add(this,E)},removeClass:function(E){o.className.remove(this,E)},toggleClass:function(F,E){if(typeof E!=="boolean"){E=!o.className.has(this,F)}o.className[E?"add":"remove"](this,F)},remove:function(E){if(!E||o.filter(E,[this]).length){o("*",this).add([this]).each(function(){o.event.remove(this);o.removeData(this)});if(this.parentNode){this.parentNode.removeChild(this)}}},empty:function(){o(this).children().remove();while(this.firstChild){this.removeChild(this.firstChild)}}},function(E,F){o.fn[E]=function(){return this.each(F,arguments)}});function j(E,F){return E[0]&&parseInt(o.curCSS(E[0],F,true),10)||0}var h="jQuery"+e(),v=0,A={};o.extend({cache:{},data:function(F,E,G){F=F==l?A:F;var H=F[h];if(!H){H=F[h]=++v}if(E&&!o.cache[H]){o.cache[H]={}}if(G!==g){o.cache[H][E]=G}return E?o.cache[H][E]:H},removeData:function(F,E){F=F==l?A:F;var H=F[h];if(E){if(o.cache[H]){delete o.cache[H][E];E="";for(E in o.cache[H]){break}if(!E){o.removeData(F)}}}else{try{delete F[h]}catch(G){if(F.removeAttribute){F.removeAttribute(h)}}delete o.cache[H]}},queue:function(F,E,H){if(F){E=(E||"fx")+"queue";var G=o.data(F,E);if(!G||o.isArray(H)){G=o.data(F,E,o.makeArray(H))}else{if(H){G.push(H)}}}return G},dequeue:function(H,G){var E=o.queue(H,G),F=E.shift();if(!G||G==="fx"){F=E[0]}if(F!==g){F.call(H)}}});o.fn.extend({data:function(E,G){var H=E.split(".");H[1]=H[1]?"."+H[1]:"";if(G===g){var F=this.triggerHandler("getData"+H[1]+"!",[H[0]]);if(F===g&&this.length){F=o.data(this[0],E)}return F===g&&H[1]?this.data(H[0]):F}else{return this.trigger("setData"+H[1]+"!",[H[0],G]).each(function(){o.data(this,E,G)})}},removeData:function(E){return this.each(function(){o.removeData(this,E)})},queue:function(E,F){if(typeof E!=="string"){F=E;E="fx"}if(F===g){return o.queue(this[0],E)}return this.each(function(){var G=o.queue(this,E,F);if(E=="fx"&&G.length==1){G[0].call(this)}})},dequeue:function(E){return this.each(function(){o.dequeue(this,E)})}});
+/*
+ * Sizzle CSS Selector Engine - v0.9.3
+ * Copyright 2009, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){var R=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?/g,L=0,H=Object.prototype.toString;var F=function(Y,U,ab,ac){ab=ab||[];U=U||document;if(U.nodeType!==1&&U.nodeType!==9){return[]}if(!Y||typeof Y!=="string"){return ab}var Z=[],W,af,ai,T,ad,V,X=true;R.lastIndex=0;while((W=R.exec(Y))!==null){Z.push(W[1]);if(W[2]){V=RegExp.rightContext;break}}if(Z.length>1&&M.exec(Y)){if(Z.length===2&&I.relative[Z[0]]){af=J(Z[0]+Z[1],U)}else{af=I.relative[Z[0]]?[U]:F(Z.shift(),U);while(Z.length){Y=Z.shift();if(I.relative[Y]){Y+=Z.shift()}af=J(Y,af)}}}else{var ae=ac?{expr:Z.pop(),set:E(ac)}:F.find(Z.pop(),Z.length===1&&U.parentNode?U.parentNode:U,Q(U));af=F.filter(ae.expr,ae.set);if(Z.length>0){ai=E(af)}else{X=false}while(Z.length){var ah=Z.pop(),ag=ah;if(!I.relative[ah]){ah=""}else{ag=Z.pop()}if(ag==null){ag=U}I.relative[ah](ai,ag,Q(U))}}if(!ai){ai=af}if(!ai){throw"Syntax error, unrecognized expression: "+(ah||Y)}if(H.call(ai)==="[object Array]"){if(!X){ab.push.apply(ab,ai)}else{if(U.nodeType===1){for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&(ai[aa]===true||ai[aa].nodeType===1&&K(U,ai[aa]))){ab.push(af[aa])}}}else{for(var aa=0;ai[aa]!=null;aa++){if(ai[aa]&&ai[aa].nodeType===1){ab.push(af[aa])}}}}}else{E(ai,ab)}if(V){F(V,U,ab,ac);if(G){hasDuplicate=false;ab.sort(G);if(hasDuplicate){for(var aa=1;aa<ab.length;aa++){if(ab[aa]===ab[aa-1]){ab.splice(aa--,1)}}}}}return ab};F.matches=function(T,U){return F(T,null,null,U)};F.find=function(aa,T,ab){var Z,X;if(!aa){return[]}for(var W=0,V=I.order.length;W<V;W++){var Y=I.order[W],X;if((X=I.match[Y].exec(aa))){var U=RegExp.leftContext;if(U.substr(U.length-1)!=="\\"){X[1]=(X[1]||"").replace(/\\/g,"");Z=I.find[Y](X,T,ab);if(Z!=null){aa=aa.replace(I.match[Y],"");break}}}}if(!Z){Z=T.getElementsByTagName("*")}return{set:Z,expr:aa}};F.filter=function(ad,ac,ag,W){var V=ad,ai=[],aa=ac,Y,T,Z=ac&&ac[0]&&Q(ac[0]);while(ad&&ac.length){for(var ab in I.filter){if((Y=I.match[ab].exec(ad))!=null){var U=I.filter[ab],ah,af;T=false;if(aa==ai){ai=[]}if(I.preFilter[ab]){Y=I.preFilter[ab](Y,aa,ag,ai,W,Z);if(!Y){T=ah=true}else{if(Y===true){continue}}}if(Y){for(var X=0;(af=aa[X])!=null;X++){if(af){ah=U(af,Y,X,aa);var ae=W^!!ah;if(ag&&ah!=null){if(ae){T=true}else{aa[X]=false}}else{if(ae){ai.push(af);T=true}}}}}if(ah!==g){if(!ag){aa=ai}ad=ad.replace(I.match[ab],"");if(!T){return[]}break}}}if(ad==V){if(T==null){throw"Syntax error, unrecognized expression: "+ad}else{break}}V=ad}return aa};var I=F.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(T){return T.getAttribute("href")}},relative:{"+":function(aa,T,Z){var X=typeof T==="string",ab=X&&!/\W/.test(T),Y=X&&!ab;if(ab&&!Z){T=T.toUpperCase()}for(var W=0,V=aa.length,U;W<V;W++){if((U=aa[W])){while((U=U.previousSibling)&&U.nodeType!==1){}aa[W]=Y||U&&U.nodeName===T?U||false:U===T}}if(Y){F.filter(T,aa,true)}},">":function(Z,U,aa){var X=typeof U==="string";if(X&&!/\W/.test(U)){U=aa?U:U.toUpperCase();for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){var W=Y.parentNode;Z[V]=W.nodeName===U?W:false}}}else{for(var V=0,T=Z.length;V<T;V++){var Y=Z[V];if(Y){Z[V]=X?Y.parentNode:Y.parentNode===U}}if(X){F.filter(U,Z,true)}}},"":function(W,U,Y){var V=L++,T=S;if(!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("parentNode",U,V,W,X,Y)},"~":function(W,U,Y){var V=L++,T=S;if(typeof U==="string"&&!U.match(/\W/)){var X=U=Y?U:U.toUpperCase();T=P}T("previousSibling",U,V,W,X,Y)}},find:{ID:function(U,V,W){if(typeof V.getElementById!=="undefined"&&!W){var T=V.getElementById(U[1]);return T?[T]:[]}},NAME:function(V,Y,Z){if(typeof Y.getElementsByName!=="undefined"){var U=[],X=Y.getElementsByName(V[1]);for(var W=0,T=X.length;W<T;W++){if(X[W].getAttribute("name")===V[1]){U.push(X[W])}}return U.length===0?null:U}},TAG:function(T,U){return U.getElementsByTagName(T[1])}},preFilter:{CLASS:function(W,U,V,T,Z,aa){W=" "+W[1].replace(/\\/g,"")+" ";if(aa){return W}for(var X=0,Y;(Y=U[X])!=null;X++){if(Y){if(Z^(Y.className&&(" "+Y.className+" ").indexOf(W)>=0)){if(!V){T.push(Y)}}else{if(V){U[X]=false}}}}return false},ID:function(T){return T[1].replace(/\\/g,"")},TAG:function(U,T){for(var V=0;T[V]===false;V++){}return T[V]&&Q(T[V])?U[1]:U[1].toUpperCase()},CHILD:function(T){if(T[1]=="nth"){var U=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(T[2]=="even"&&"2n"||T[2]=="odd"&&"2n+1"||!/\D/.test(T[2])&&"0n+"+T[2]||T[2]);T[2]=(U[1]+(U[2]||1))-0;T[3]=U[3]-0}T[0]=L++;return T},ATTR:function(X,U,V,T,Y,Z){var W=X[1].replace(/\\/g,"");if(!Z&&I.attrMap[W]){X[1]=I.attrMap[W]}if(X[2]==="~="){X[4]=" "+X[4]+" "}return X},PSEUDO:function(X,U,V,T,Y){if(X[1]==="not"){if(X[3].match(R).length>1||/^\w/.test(X[3])){X[3]=F(X[3],null,null,U)}else{var W=F.filter(X[3],U,V,true^Y);if(!V){T.push.apply(T,W)}return false}}else{if(I.match.POS.test(X[0])||I.match.CHILD.test(X[0])){return true}}return X},POS:function(T){T.unshift(true);return T}},filters:{enabled:function(T){return T.disabled===false&&T.type!=="hidden"},disabled:function(T){return T.disabled===true},checked:function(T){return T.checked===true},selected:function(T){T.parentNode.selectedIndex;return T.selected===true},parent:function(T){return !!T.firstChild},empty:function(T){return !T.firstChild},has:function(V,U,T){return !!F(T[3],V).length},header:function(T){return/h\d/i.test(T.nodeName)},text:function(T){return"text"===T.type},radio:function(T){return"radio"===T.type},checkbox:function(T){return"checkbox"===T.type},file:function(T){return"file"===T.type},password:function(T){return"password"===T.type},submit:function(T){return"submit"===T.type},image:function(T){return"image"===T.type},reset:function(T){return"reset"===T.type},button:function(T){return"button"===T.type||T.nodeName.toUpperCase()==="BUTTON"},input:function(T){return/input|select|textarea|button/i.test(T.nodeName)}},setFilters:{first:function(U,T){return T===0},last:function(V,U,T,W){return U===W.length-1},even:function(U,T){return T%2===0},odd:function(U,T){return T%2===1},lt:function(V,U,T){return U<T[3]-0},gt:function(V,U,T){return U>T[3]-0},nth:function(V,U,T){return T[3]-0==U},eq:function(V,U,T){return T[3]-0==U}},filter:{PSEUDO:function(Z,V,W,aa){var U=V[1],X=I.filters[U];if(X){return X(Z,W,V,aa)}else{if(U==="contains"){return(Z.textContent||Z.innerText||"").indexOf(V[3])>=0}else{if(U==="not"){var Y=V[3];for(var W=0,T=Y.length;W<T;W++){if(Y[W]===Z){return false}}return true}}}},CHILD:function(T,W){var Z=W[1],U=T;switch(Z){case"only":case"first":while(U=U.previousSibling){if(U.nodeType===1){return false}}if(Z=="first"){return true}U=T;case"last":while(U=U.nextSibling){if(U.nodeType===1){return false}}return true;case"nth":var V=W[2],ac=W[3];if(V==1&&ac==0){return true}var Y=W[0],ab=T.parentNode;if(ab&&(ab.sizcache!==Y||!T.nodeIndex)){var X=0;for(U=ab.firstChild;U;U=U.nextSibling){if(U.nodeType===1){U.nodeIndex=++X}}ab.sizcache=Y}var aa=T.nodeIndex-ac;if(V==0){return aa==0}else{return(aa%V==0&&aa/V>=0)}}},ID:function(U,T){return U.nodeType===1&&U.getAttribute("id")===T},TAG:function(U,T){return(T==="*"&&U.nodeType===1)||U.nodeName===T},CLASS:function(U,T){return(" "+(U.className||U.getAttribute("class"))+" ").indexOf(T)>-1},ATTR:function(Y,W){var V=W[1],T=I.attrHandle[V]?I.attrHandle[V](Y):Y[V]!=null?Y[V]:Y.getAttribute(V),Z=T+"",X=W[2],U=W[4];return T==null?X==="!=":X==="="?Z===U:X==="*="?Z.indexOf(U)>=0:X==="~="?(" "+Z+" ").indexOf(U)>=0:!U?Z&&T!==false:X==="!="?Z!=U:X==="^="?Z.indexOf(U)===0:X==="$="?Z.substr(Z.length-U.length)===U:X==="|="?Z===U||Z.substr(0,U.length+1)===U+"-":false},POS:function(X,U,V,Y){var T=U[2],W=I.setFilters[T];if(W){return W(X,V,U,Y)}}}};var M=I.match.POS;for(var O in I.match){I.match[O]=RegExp(I.match[O].source+/(?![^\[]*\])(?![^\(]*\))/.source)}var E=function(U,T){U=Array.prototype.slice.call(U);if(T){T.push.apply(T,U);return T}return U};try{Array.prototype.slice.call(document.documentElement.childNodes)}catch(N){E=function(X,W){var U=W||[];if(H.call(X)==="[object Array]"){Array.prototype.push.apply(U,X)}else{if(typeof X.length==="number"){for(var V=0,T=X.length;V<T;V++){U.push(X[V])}}else{for(var V=0;X[V];V++){U.push(X[V])}}}return U}}var G;if(document.documentElement.compareDocumentPosition){G=function(U,T){var V=U.compareDocumentPosition(T)&4?-1:U===T?0:1;if(V===0){hasDuplicate=true}return V}}else{if("sourceIndex" in document.documentElement){G=function(U,T){var V=U.sourceIndex-T.sourceIndex;if(V===0){hasDuplicate=true}return V}}else{if(document.createRange){G=function(W,U){var V=W.ownerDocument.createRange(),T=U.ownerDocument.createRange();V.selectNode(W);V.collapse(true);T.selectNode(U);T.collapse(true);var X=V.compareBoundaryPoints(Range.START_TO_END,T);if(X===0){hasDuplicate=true}return X}}}}(function(){var U=document.createElement("form"),V="script"+(new Date).getTime();U.innerHTML="<input name='"+V+"'/>";var T=document.documentElement;T.insertBefore(U,T.firstChild);if(!!document.getElementById(V)){I.find.ID=function(X,Y,Z){if(typeof Y.getElementById!=="undefined"&&!Z){var W=Y.getElementById(X[1]);return W?W.id===X[1]||typeof W.getAttributeNode!=="undefined"&&W.getAttributeNode("id").nodeValue===X[1]?[W]:g:[]}};I.filter.ID=function(Y,W){var X=typeof Y.getAttributeNode!=="undefined"&&Y.getAttributeNode("id");return Y.nodeType===1&&X&&X.nodeValue===W}}T.removeChild(U)})();(function(){var T=document.createElement("div");T.appendChild(document.createComment(""));if(T.getElementsByTagName("*").length>0){I.find.TAG=function(U,Y){var X=Y.getElementsByTagName(U[1]);if(U[1]==="*"){var W=[];for(var V=0;X[V];V++){if(X[V].nodeType===1){W.push(X[V])}}X=W}return X}}T.innerHTML="<a href='#'></a>";if(T.firstChild&&typeof T.firstChild.getAttribute!=="undefined"&&T.firstChild.getAttribute("href")!=="#"){I.attrHandle.href=function(U){return U.getAttribute("href",2)}}})();if(document.querySelectorAll){(function(){var T=F,U=document.createElement("div");U.innerHTML="<p class='TEST'></p>";if(U.querySelectorAll&&U.querySelectorAll(".TEST").length===0){return}F=function(Y,X,V,W){X=X||document;if(!W&&X.nodeType===9&&!Q(X)){try{return E(X.querySelectorAll(Y),V)}catch(Z){}}return T(Y,X,V,W)};F.find=T.find;F.filter=T.filter;F.selectors=T.selectors;F.matches=T.matches})()}if(document.getElementsByClassName&&document.documentElement.getElementsByClassName){(function(){var T=document.createElement("div");T.innerHTML="<div class='test e'></div><div class='test'></div>";if(T.getElementsByClassName("e").length===0){return}T.lastChild.className="e";if(T.getElementsByClassName("e").length===1){return}I.order.splice(1,0,"CLASS");I.find.CLASS=function(U,V,W){if(typeof V.getElementsByClassName!=="undefined"&&!W){return V.getElementsByClassName(U[1])}}})()}function P(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1&&!ac){T.sizcache=Y;T.sizset=W}if(T.nodeName===Z){X=T;break}T=T[U]}ad[W]=X}}}function S(U,Z,Y,ad,aa,ac){var ab=U=="previousSibling"&&!ac;for(var W=0,V=ad.length;W<V;W++){var T=ad[W];if(T){if(ab&&T.nodeType===1){T.sizcache=Y;T.sizset=W}T=T[U];var X=false;while(T){if(T.sizcache===Y){X=ad[T.sizset];break}if(T.nodeType===1){if(!ac){T.sizcache=Y;T.sizset=W}if(typeof Z!=="string"){if(T===Z){X=true;break}}else{if(F.filter(Z,[T]).length>0){X=T;break}}}T=T[U]}ad[W]=X}}}var K=document.compareDocumentPosition?function(U,T){return U.compareDocumentPosition(T)&16}:function(U,T){return U!==T&&(U.contains?U.contains(T):true)};var Q=function(T){return T.nodeType===9&&T.documentElement.nodeName!=="HTML"||!!T.ownerDocument&&Q(T.ownerDocument)};var J=function(T,aa){var W=[],X="",Y,V=aa.nodeType?[aa]:aa;while((Y=I.match.PSEUDO.exec(T))){X+=Y[0];T=T.replace(I.match.PSEUDO,"")}T=I.relative[T]?T+"*":T;for(var Z=0,U=V.length;Z<U;Z++){F(T,V[Z],W)}return F.filter(X,W)};o.find=F;o.filter=F.filter;o.expr=F.selectors;o.expr[":"]=o.expr.filters;F.selectors.filters.hidden=function(T){return T.offsetWidth===0||T.offsetHeight===0};F.selectors.filters.visible=function(T){return T.offsetWidth>0||T.offsetHeight>0};F.selectors.filters.animated=function(T){return o.grep(o.timers,function(U){return T===U.elem}).length};o.multiFilter=function(V,T,U){if(U){V=":not("+V+")"}return F.matches(V,T)};o.dir=function(V,U){var T=[],W=V[U];while(W&&W!=document){if(W.nodeType==1){T.push(W)}W=W[U]}return T};o.nth=function(X,T,V,W){T=T||1;var U=0;for(;X;X=X[V]){if(X.nodeType==1&&++U==T){break}}return X};o.sibling=function(V,U){var T=[];for(;V;V=V.nextSibling){if(V.nodeType==1&&V!=U){T.push(V)}}return T};return;l.Sizzle=F})();o.event={add:function(I,F,H,K){if(I.nodeType==3||I.nodeType==8){return}if(I.setInterval&&I!=l){I=l}if(!H.guid){H.guid=this.guid++}if(K!==g){var G=H;H=this.proxy(G);H.data=K}var E=o.data(I,"events")||o.data(I,"events",{}),J=o.data(I,"handle")||o.data(I,"handle",function(){return typeof o!=="undefined"&&!o.event.triggered?o.event.handle.apply(arguments.callee.elem,arguments):g});J.elem=I;o.each(F.split(/\s+/),function(M,N){var O=N.split(".");N=O.shift();H.type=O.slice().sort().join(".");var L=E[N];if(o.event.specialAll[N]){o.event.specialAll[N].setup.call(I,K,O)}if(!L){L=E[N]={};if(!o.event.special[N]||o.event.special[N].setup.call(I,K,O)===false){if(I.addEventListener){I.addEventListener(N,J,false)}else{if(I.attachEvent){I.attachEvent("on"+N,J)}}}}L[H.guid]=H;o.event.global[N]=true});I=null},guid:1,global:{},remove:function(K,H,J){if(K.nodeType==3||K.nodeType==8){return}var G=o.data(K,"events"),F,E;if(G){if(H===g||(typeof H==="string"&&H.charAt(0)==".")){for(var I in G){this.remove(K,I+(H||""))}}else{if(H.type){J=H.handler;H=H.type}o.each(H.split(/\s+/),function(M,O){var Q=O.split(".");O=Q.shift();var N=RegExp("(^|\\.)"+Q.slice().sort().join(".*\\.")+"(\\.|$)");if(G[O]){if(J){delete G[O][J.guid]}else{for(var P in G[O]){if(N.test(G[O][P].type)){delete G[O][P]}}}if(o.event.specialAll[O]){o.event.specialAll[O].teardown.call(K,Q)}for(F in G[O]){break}if(!F){if(!o.event.special[O]||o.event.special[O].teardown.call(K,Q)===false){if(K.removeEventListener){K.removeEventListener(O,o.data(K,"handle"),false)}else{if(K.detachEvent){K.detachEvent("on"+O,o.data(K,"handle"))}}}F=null;delete G[O]}}})}for(F in G){break}if(!F){var L=o.data(K,"handle");if(L){L.elem=null}o.removeData(K,"events");o.removeData(K,"handle")}}},trigger:function(I,K,H,E){var G=I.type||I;if(!E){I=typeof I==="object"?I[h]?I:o.extend(o.Event(G),I):o.Event(G);if(G.indexOf("!")>=0){I.type=G=G.slice(0,-1);I.exclusive=true}if(!H){I.stopPropagation();if(this.global[G]){o.each(o.cache,function(){if(this.events&&this.events[G]){o.event.trigger(I,K,this.handle.elem)}})}}if(!H||H.nodeType==3||H.nodeType==8){return g}I.result=g;I.target=H;K=o.makeArray(K);K.unshift(I)}I.currentTarget=H;var J=o.data(H,"handle");if(J){J.apply(H,K)}if((!H[G]||(o.nodeName(H,"a")&&G=="click"))&&H["on"+G]&&H["on"+G].apply(H,K)===false){I.result=false}if(!E&&H[G]&&!I.isDefaultPrevented()&&!(o.nodeName(H,"a")&&G=="click")){this.triggered=true;try{H[G]()}catch(L){}}this.triggered=false;if(!I.isPropagationStopped()){var F=H.parentNode||H.ownerDocument;if(F){o.event.trigger(I,K,F,true)}}},handle:function(K){var J,E;K=arguments[0]=o.event.fix(K||l.event);K.currentTarget=this;var L=K.type.split(".");K.type=L.shift();J=!L.length&&!K.exclusive;var I=RegExp("(^|\\.)"+L.slice().sort().join(".*\\.")+"(\\.|$)");E=(o.data(this,"events")||{})[K.type];for(var G in E){var H=E[G];if(J||I.test(H.type)){K.handler=H;K.data=H.data;var F=H.apply(this,arguments);if(F!==g){K.result=F;if(F===false){K.preventDefault();K.stopPropagation()}}if(K.isImmediatePropagationStopped()){break}}}},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),fix:function(H){if(H[h]){return H}var F=H;H=o.Event(F);for(var G=this.props.length,J;G;){J=this.props[--G];H[J]=F[J]}if(!H.target){H.target=H.srcElement||document}if(H.target.nodeType==3){H.target=H.target.parentNode}if(!H.relatedTarget&&H.fromElement){H.relatedTarget=H.fromElement==H.target?H.toElement:H.fromElement}if(H.pageX==null&&H.clientX!=null){var I=document.documentElement,E=document.body;H.pageX=H.clientX+(I&&I.scrollLeft||E&&E.scrollLeft||0)-(I.clientLeft||0);H.pageY=H.clientY+(I&&I.scrollTop||E&&E.scrollTop||0)-(I.clientTop||0)}if(!H.which&&((H.charCode||H.charCode===0)?H.charCode:H.keyCode)){H.which=H.charCode||H.keyCode}if(!H.metaKey&&H.ctrlKey){H.metaKey=H.ctrlKey}if(!H.which&&H.button){H.which=(H.button&1?1:(H.button&2?3:(H.button&4?2:0)))}return H},proxy:function(F,E){E=E||function(){return F.apply(this,arguments)};E.guid=F.guid=F.guid||E.guid||this.guid++;return E},special:{ready:{setup:B,teardown:function(){}}},specialAll:{live:{setup:function(E,F){o.event.add(this,F[0],c)},teardown:function(G){if(G.length){var E=0,F=RegExp("(^|\\.)"+G[0]+"(\\.|$)");o.each((o.data(this,"events").live||{}),function(){if(F.test(this.type)){E++}});if(E<1){o.event.remove(this,G[0],c)}}}}}};o.Event=function(E){if(!this.preventDefault){return new o.Event(E)}if(E&&E.type){this.originalEvent=E;this.type=E.type}else{this.type=E}this.timeStamp=e();this[h]=true};function k(){return false}function u(){return true}o.Event.prototype={preventDefault:function(){this.isDefaultPrevented=u;var E=this.originalEvent;if(!E){return}if(E.preventDefault){E.preventDefault()}E.returnValue=false},stopPropagation:function(){this.isPropagationStopped=u;var E=this.originalEvent;if(!E){return}if(E.stopPropagation){E.stopPropagation()}E.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=u;this.stopPropagation()},isDefaultPrevented:k,isPropagationStopped:k,isImmediatePropagationStopped:k};var a=function(F){var E=F.relatedTarget;while(E&&E!=this){try{E=E.parentNode}catch(G){E=this}}if(E!=this){F.type=F.data;o.event.handle.apply(this,arguments)}};o.each({mouseover:"mouseenter",mouseout:"mouseleave"},function(F,E){o.event.special[E]={setup:function(){o.event.add(this,F,a,E)},teardown:function(){o.event.remove(this,F,a)}}});o.fn.extend({bind:function(F,G,E){return F=="unload"?this.one(F,G,E):this.each(function(){o.event.add(this,F,E||G,E&&G)})},one:function(G,H,F){var E=o.event.proxy(F||H,function(I){o(this).unbind(I,E);return(F||H).apply(this,arguments)});return this.each(function(){o.event.add(this,G,E,F&&H)})},unbind:function(F,E){return this.each(function(){o.event.remove(this,F,E)})},trigger:function(E,F){return this.each(function(){o.event.trigger(E,F,this)})},triggerHandler:function(E,G){if(this[0]){var F=o.Event(E);F.preventDefault();F.stopPropagation();o.event.trigger(F,G,this[0]);return F.result}},toggle:function(G){var E=arguments,F=1;while(F<E.length){o.event.proxy(G,E[F++])}return this.click(o.event.proxy(G,function(H){this.lastToggle=(this.lastToggle||0)%F;H.preventDefault();return E[this.lastToggle++].apply(this,arguments)||false}))},hover:function(E,F){return this.mouseenter(E).mouseleave(F)},ready:function(E){B();if(o.isReady){E.call(document,o)}else{o.readyList.push(E)}return this},live:function(G,F){var E=o.event.proxy(F);E.guid+=this.selector+G;o(document).bind(i(G,this.selector),this.selector,E);return this},die:function(F,E){o(document).unbind(i(F,this.selector),E?{guid:E.guid+this.selector+F}:null);return this}});function c(H){var E=RegExp("(^|\\.)"+H.type+"(\\.|$)"),G=true,F=[];o.each(o.data(this,"events").live||[],function(I,J){if(E.test(J.type)){var K=o(H.target).closest(J.data)[0];if(K){F.push({elem:K,fn:J})}}});F.sort(function(J,I){return o.data(J.elem,"closest")-o.data(I.elem,"closest")});o.each(F,function(){if(this.fn.call(this.elem,H,this.fn.data)===false){return(G=false)}});return G}function i(F,E){return["live",F,E.replace(/\./g,"`").replace(/ /g,"|")].join(".")}o.extend({isReady:false,readyList:[],ready:function(){if(!o.isReady){o.isReady=true;if(o.readyList){o.each(o.readyList,function(){this.call(document,o)});o.readyList=null}o(document).triggerHandler("ready")}}});var x=false;function B(){if(x){return}x=true;if(document.addEventListener){document.addEventListener("DOMContentLoaded",function(){document.removeEventListener("DOMContentLoaded",arguments.callee,false);o.ready()},false)}else{if(document.attachEvent){document.attachEvent("onreadystatechange",function(){if(document.readyState==="complete"){document.detachEvent("onreadystatechange",arguments.callee);o.ready()}});if(document.documentElement.doScroll&&l==l.top){(function(){if(o.isReady){return}try{document.documentElement.doScroll("left")}catch(E){setTimeout(arguments.callee,0);return}o.ready()})()}}}o.event.add(l,"load",o.ready)}o.each(("blur,focus,load,resize,scroll,unload,click,dblclick,mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave,change,select,submit,keydown,keypress,keyup,error").split(","),function(F,E){o.fn[E]=function(G){return G?this.bind(E,G):this.trigger(E)}});o(l).bind("unload",function(){for(var E in o.cache){if(E!=1&&o.cache[E].handle){o.event.remove(o.cache[E].handle.elem)}}});(function(){o.support={};var F=document.documentElement,G=document.createElement("script"),K=document.createElement("div"),J="script"+(new Date).getTime();K.style.display="none";K.innerHTML=' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';var H=K.getElementsByTagName("*"),E=K.getElementsByTagName("a")[0];if(!H||!H.length||!E){return}o.support={leadingWhitespace:K.firstChild.nodeType==3,tbody:!K.getElementsByTagName("tbody").length,objectAll:!!K.getElementsByTagName("object")[0].getElementsByTagName("*").length,htmlSerialize:!!K.getElementsByTagName("link").length,style:/red/.test(E.getAttribute("style")),hrefNormalized:E.getAttribute("href")==="/a",opacity:E.style.opacity==="0.5",cssFloat:!!E.style.cssFloat,scriptEval:false,noCloneEvent:true,boxModel:null};G.type="text/javascript";try{G.appendChild(document.createTextNode("window."+J+"=1;"))}catch(I){}F.insertBefore(G,F.firstChild);if(l[J]){o.support.scriptEval=true;delete l[J]}F.removeChild(G);if(K.attachEvent&&K.fireEvent){K.attachEvent("onclick",function(){o.support.noCloneEvent=false;K.detachEvent("onclick",arguments.callee)});K.cloneNode(true).fireEvent("onclick")}o(function(){var L=document.createElement("div");L.style.width=L.style.paddingLeft="1px";document.body.appendChild(L);o.boxModel=o.support.boxModel=L.offsetWidth===2;document.body.removeChild(L).style.display="none"})})();var w=o.support.cssFloat?"cssFloat":"styleFloat";o.props={"for":"htmlFor","class":"className","float":w,cssFloat:w,styleFloat:w,readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",tabindex:"tabIndex"};o.fn.extend({_load:o.fn.load,load:function(G,J,K){if(typeof G!=="string"){return this._load(G)}var I=G.indexOf(" ");if(I>=0){var E=G.slice(I,G.length);G=G.slice(0,I)}var H="GET";if(J){if(o.isFunction(J)){K=J;J=null}else{if(typeof J==="object"){J=o.param(J);H="POST"}}}var F=this;o.ajax({url:G,type:H,dataType:"html",data:J,complete:function(M,L){if(L=="success"||L=="notmodified"){F.html(E?o("<div/>").append(M.responseText.replace(/<script(.|\s)*?\/script>/g,"")).find(E):M.responseText)}if(K){F.each(K,[M.responseText,L,M])}}});return this},serialize:function(){return o.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?o.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password|search/i.test(this.type))}).map(function(E,F){var G=o(this).val();return G==null?null:o.isArray(G)?o.map(G,function(I,H){return{name:F.name,value:I}}):{name:F.name,value:G}}).get()}});o.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(E,F){o.fn[F]=function(G){return this.bind(F,G)}});var r=e();o.extend({get:function(E,G,H,F){if(o.isFunction(G)){H=G;G=null}return o.ajax({type:"GET",url:E,data:G,success:H,dataType:F})},getScript:function(E,F){return o.get(E,null,F,"script")},getJSON:function(E,F,G){return o.get(E,F,G,"json")},post:function(E,G,H,F){if(o.isFunction(G)){H=G;G={}}return o.ajax({type:"POST",url:E,data:G,success:H,dataType:F})},ajaxSetup:function(E){o.extend(o.ajaxSettings,E)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return l.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest()},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(M){M=o.extend(true,M,o.extend(true,{},o.ajaxSettings,M));var W,F=/=\?(&|$)/g,R,V,G=M.type.toUpperCase();if(M.data&&M.processData&&typeof M.data!=="string"){M.data=o.param(M.data)}if(M.dataType=="jsonp"){if(G=="GET"){if(!M.url.match(F)){M.url+=(M.url.match(/\?/)?"&":"?")+(M.jsonp||"callback")+"=?"}}else{if(!M.data||!M.data.match(F)){M.data=(M.data?M.data+"&":"")+(M.jsonp||"callback")+"=?"}}M.dataType="json"}if(M.dataType=="json"&&(M.data&&M.data.match(F)||M.url.match(F))){W="jsonp"+r++;if(M.data){M.data=(M.data+"").replace(F,"="+W+"$1")}M.url=M.url.replace(F,"="+W+"$1");M.dataType="script";l[W]=function(X){V=X;I();L();l[W]=g;try{delete l[W]}catch(Y){}if(H){H.removeChild(T)}}}if(M.dataType=="script"&&M.cache==null){M.cache=false}if(M.cache===false&&G=="GET"){var E=e();var U=M.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+E+"$2");M.url=U+((U==M.url)?(M.url.match(/\?/)?"&":"?")+"_="+E:"")}if(M.data&&G=="GET"){M.url+=(M.url.match(/\?/)?"&":"?")+M.data;M.data=null}if(M.global&&!o.active++){o.event.trigger("ajaxStart")}var Q=/^(\w+:)?\/\/([^\/?#]+)/.exec(M.url);if(M.dataType=="script"&&G=="GET"&&Q&&(Q[1]&&Q[1]!=location.protocol||Q[2]!=location.host)){var H=document.getElementsByTagName("head")[0];var T=document.createElement("script");T.src=M.url;if(M.scriptCharset){T.charset=M.scriptCharset}if(!W){var O=false;T.onload=T.onreadystatechange=function(){if(!O&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){O=true;I();L();T.onload=T.onreadystatechange=null;H.removeChild(T)}}}H.appendChild(T);return g}var K=false;var J=M.xhr();if(M.username){J.open(G,M.url,M.async,M.username,M.password)}else{J.open(G,M.url,M.async)}try{if(M.data){J.setRequestHeader("Content-Type",M.contentType)}if(M.ifModified){J.setRequestHeader("If-Modified-Since",o.lastModified[M.url]||"Thu, 01 Jan 1970 00:00:00 GMT")}J.setRequestHeader("X-Requested-With","XMLHttpRequest");J.setRequestHeader("Accept",M.dataType&&M.accepts[M.dataType]?M.accepts[M.dataType]+", */*":M.accepts._default)}catch(S){}if(M.beforeSend&&M.beforeSend(J,M)===false){if(M.global&&!--o.active){o.event.trigger("ajaxStop")}J.abort();return false}if(M.global){o.event.trigger("ajaxSend",[J,M])}var N=function(X){if(J.readyState==0){if(P){clearInterval(P);P=null;if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}}else{if(!K&&J&&(J.readyState==4||X=="timeout")){K=true;if(P){clearInterval(P);P=null}R=X=="timeout"?"timeout":!o.httpSuccess(J)?"error":M.ifModified&&o.httpNotModified(J,M.url)?"notmodified":"success";if(R=="success"){try{V=o.httpData(J,M.dataType,M)}catch(Z){R="parsererror"}}if(R=="success"){var Y;try{Y=J.getResponseHeader("Last-Modified")}catch(Z){}if(M.ifModified&&Y){o.lastModified[M.url]=Y}if(!W){I()}}else{o.handleError(M,J,R)}L();if(X){J.abort()}if(M.async){J=null}}}};if(M.async){var P=setInterval(N,13);if(M.timeout>0){setTimeout(function(){if(J&&!K){N("timeout")}},M.timeout)}}try{J.send(M.data)}catch(S){o.handleError(M,J,null,S)}if(!M.async){N()}function I(){if(M.success){M.success(V,R)}if(M.global){o.event.trigger("ajaxSuccess",[J,M])}}function L(){if(M.complete){M.complete(J,R)}if(M.global){o.event.trigger("ajaxComplete",[J,M])}if(M.global&&!--o.active){o.event.trigger("ajaxStop")}}return J},handleError:function(F,H,E,G){if(F.error){F.error(H,E,G)}if(F.global){o.event.trigger("ajaxError",[H,F,G])}},active:0,httpSuccess:function(F){try{return !F.status&&location.protocol=="file:"||(F.status>=200&&F.status<300)||F.status==304||F.status==1223}catch(E){}return false},httpNotModified:function(G,E){try{var H=G.getResponseHeader("Last-Modified");return G.status==304||H==o.lastModified[E]}catch(F){}return false},httpData:function(J,H,G){var F=J.getResponseHeader("content-type"),E=H=="xml"||!H&&F&&F.indexOf("xml")>=0,I=E?J.responseXML:J.responseText;if(E&&I.documentElement.tagName=="parsererror"){throw"parsererror"}if(G&&G.dataFilter){I=G.dataFilter(I,H)}if(typeof I==="string"){if(H=="script"){o.globalEval(I)}if(H=="json"){I=l["eval"]("("+I+")")}}return I},param:function(E){var G=[];function H(I,J){G[G.length]=encodeURIComponent(I)+"="+encodeURIComponent(J)}if(o.isArray(E)||E.jquery){o.each(E,function(){H(this.name,this.value)})}else{for(var F in E){if(o.isArray(E[F])){o.each(E[F],function(){H(F,this)})}else{H(F,o.isFunction(E[F])?E[F]():E[F])}}}return G.join("&").replace(/%20/g,"+")}});var m={},n,d=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];function t(F,E){var G={};o.each(d.concat.apply([],d.slice(0,E)),function(){G[this]=F});return G}o.fn.extend({show:function(J,L){if(J){return this.animate(t("show",3),J,L)}else{for(var H=0,F=this.length;H<F;H++){var E=o.data(this[H],"olddisplay");this[H].style.display=E||"";if(o.css(this[H],"display")==="none"){var G=this[H].tagName,K;if(m[G]){K=m[G]}else{var I=o("<"+G+" />").appendTo("body");K=I.css("display");if(K==="none"){K="block"}I.remove();m[G]=K}o.data(this[H],"olddisplay",K)}}for(var H=0,F=this.length;H<F;H++){this[H].style.display=o.data(this[H],"olddisplay")||""}return this}},hide:function(H,I){if(H){return this.animate(t("hide",3),H,I)}else{for(var G=0,F=this.length;G<F;G++){var E=o.data(this[G],"olddisplay");if(!E&&E!=="none"){o.data(this[G],"olddisplay",o.css(this[G],"display"))}}for(var G=0,F=this.length;G<F;G++){this[G].style.display="none"}return this}},_toggle:o.fn.toggle,toggle:function(G,F){var E=typeof G==="boolean";return o.isFunction(G)&&o.isFunction(F)?this._toggle.apply(this,arguments):G==null||E?this.each(function(){var H=E?G:o(this).is(":hidden");o(this)[H?"show":"hide"]()}):this.animate(t("toggle",3),G,F)},fadeTo:function(E,G,F){return this.animate({opacity:G},E,F)},animate:function(I,F,H,G){var E=o.speed(F,H,G);return this[E.queue===false?"each":"queue"](function(){var K=o.extend({},E),M,L=this.nodeType==1&&o(this).is(":hidden"),J=this;for(M in I){if(I[M]=="hide"&&L||I[M]=="show"&&!L){return K.complete.call(this)}if((M=="height"||M=="width")&&this.style){K.display=o.css(this,"display");K.overflow=this.style.overflow}}if(K.overflow!=null){this.style.overflow="hidden"}K.curAnim=o.extend({},I);o.each(I,function(O,S){var R=new o.fx(J,K,O);if(/toggle|show|hide/.test(S)){R[S=="toggle"?L?"show":"hide":S](I)}else{var Q=S.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),T=R.cur(true)||0;if(Q){var N=parseFloat(Q[2]),P=Q[3]||"px";if(P!="px"){J.style[O]=(N||1)+P;T=((N||1)/R.cur(true))*T;J.style[O]=T+P}if(Q[1]){N=((Q[1]=="-="?-1:1)*N)+T}R.custom(T,N,P)}else{R.custom(T,S,"")}}});return true})},stop:function(F,E){var G=o.timers;if(F){this.queue([])}this.each(function(){for(var H=G.length-1;H>=0;H--){if(G[H].elem==this){if(E){G[H](true)}G.splice(H,1)}}});if(!E){this.dequeue()}return this}});o.each({slideDown:t("show",1),slideUp:t("hide",1),slideToggle:t("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(E,F){o.fn[E]=function(G,H){return this.animate(F,G,H)}});o.extend({speed:function(G,H,F){var E=typeof G==="object"?G:{complete:F||!F&&H||o.isFunction(G)&&G,duration:G,easing:F&&H||H&&!o.isFunction(H)&&H};E.duration=o.fx.off?0:typeof E.duration==="number"?E.duration:o.fx.speeds[E.duration]||o.fx.speeds._default;E.old=E.complete;E.complete=function(){if(E.queue!==false){o(this).dequeue()}if(o.isFunction(E.old)){E.old.call(this)}};return E},easing:{linear:function(G,H,E,F){return E+F*G},swing:function(G,H,E,F){return((-Math.cos(G*Math.PI)/2)+0.5)*F+E}},timers:[],fx:function(F,E,G){this.options=E;this.elem=F;this.prop=G;if(!E.orig){E.orig={}}}});o.fx.prototype={update:function(){if(this.options.step){this.options.step.call(this.elem,this.now,this)}(o.fx.step[this.prop]||o.fx.step._default)(this);if((this.prop=="height"||this.prop=="width")&&this.elem.style){this.elem.style.display="block"}},cur:function(F){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null)){return this.elem[this.prop]}var E=parseFloat(o.css(this.elem,this.prop,F));return E&&E>-10000?E:parseFloat(o.curCSS(this.elem,this.prop))||0},custom:function(I,H,G){this.startTime=e();this.start=I;this.end=H;this.unit=G||this.unit||"px";this.now=this.start;this.pos=this.state=0;var E=this;function F(J){return E.step(J)}F.elem=this.elem;if(F()&&o.timers.push(F)&&!n){n=setInterval(function(){var K=o.timers;for(var J=0;J<K.length;J++){if(!K[J]()){K.splice(J--,1)}}if(!K.length){clearInterval(n);n=g}},13)}},show:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.show=true;this.custom(this.prop=="width"||this.prop=="height"?1:0,this.cur());o(this.elem).show()},hide:function(){this.options.orig[this.prop]=o.attr(this.elem.style,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(H){var G=e();if(H||G>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var E=true;for(var F in this.options.curAnim){if(this.options.curAnim[F]!==true){E=false}}if(E){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(o.css(this.elem,"display")=="none"){this.elem.style.display="block"}}if(this.options.hide){o(this.elem).hide()}if(this.options.hide||this.options.show){for(var I in this.options.curAnim){o.attr(this.elem.style,I,this.options.orig[I])}}this.options.complete.call(this.elem)}return false}else{var J=G-this.startTime;this.state=J/this.options.duration;this.pos=o.easing[this.options.easing||(o.easing.swing?"swing":"linear")](this.state,J,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update()}return true}};o.extend(o.fx,{speeds:{slow:600,fast:200,_default:400},step:{opacity:function(E){o.attr(E.elem.style,"opacity",E.now)},_default:function(E){if(E.elem.style&&E.elem.style[E.prop]!=null){E.elem.style[E.prop]=E.now+E.unit}else{E.elem[E.prop]=E.now}}}});if(document.documentElement.getBoundingClientRect){o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}var G=this[0].getBoundingClientRect(),J=this[0].ownerDocument,F=J.body,E=J.documentElement,L=E.clientTop||F.clientTop||0,K=E.clientLeft||F.clientLeft||0,I=G.top+(self.pageYOffset||o.boxModel&&E.scrollTop||F.scrollTop)-L,H=G.left+(self.pageXOffset||o.boxModel&&E.scrollLeft||F.scrollLeft)-K;return{top:I,left:H}}}else{o.fn.offset=function(){if(!this[0]){return{top:0,left:0}}if(this[0]===this[0].ownerDocument.body){return o.offset.bodyOffset(this[0])}o.offset.initialized||o.offset.initialize();var J=this[0],G=J.offsetParent,F=J,O=J.ownerDocument,M,H=O.documentElement,K=O.body,L=O.defaultView,E=L.getComputedStyle(J,null),N=J.offsetTop,I=J.offsetLeft;while((J=J.parentNode)&&J!==K&&J!==H){M=L.getComputedStyle(J,null);N-=J.scrollTop,I-=J.scrollLeft;if(J===G){N+=J.offsetTop,I+=J.offsetLeft;if(o.offset.doesNotAddBorder&&!(o.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(J.tagName))){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}F=G,G=J.offsetParent}if(o.offset.subtractsBorderForOverflowNotVisible&&M.overflow!=="visible"){N+=parseInt(M.borderTopWidth,10)||0,I+=parseInt(M.borderLeftWidth,10)||0}E=M}if(E.position==="relative"||E.position==="static"){N+=K.offsetTop,I+=K.offsetLeft}if(E.position==="fixed"){N+=Math.max(H.scrollTop,K.scrollTop),I+=Math.max(H.scrollLeft,K.scrollLeft)}return{top:N,left:I}}}o.offset={initialize:function(){if(this.initialized){return}var L=document.body,F=document.createElement("div"),H,G,N,I,M,E,J=L.style.marginTop,K='<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';M={position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"};for(E in M){F.style[E]=M[E]}F.innerHTML=K;L.insertBefore(F,L.firstChild);H=F.firstChild,G=H.firstChild,I=H.nextSibling.firstChild.firstChild;this.doesNotAddBorder=(G.offsetTop!==5);this.doesAddBorderForTableAndCells=(I.offsetTop===5);H.style.overflow="hidden",H.style.position="relative";this.subtractsBorderForOverflowNotVisible=(G.offsetTop===-5);L.style.marginTop="1px";this.doesNotIncludeMarginInBodyOffset=(L.offsetTop===0);L.style.marginTop=J;L.removeChild(F);this.initialized=true},bodyOffset:function(E){o.offset.initialized||o.offset.initialize();var G=E.offsetTop,F=E.offsetLeft;if(o.offset.doesNotIncludeMarginInBodyOffset){G+=parseInt(o.curCSS(E,"marginTop",true),10)||0,F+=parseInt(o.curCSS(E,"marginLeft",true),10)||0}return{top:G,left:F}}};o.fn.extend({position:function(){var I=0,H=0,F;if(this[0]){var G=this.offsetParent(),J=this.offset(),E=/^body|html$/i.test(G[0].tagName)?{top:0,left:0}:G.offset();J.top-=j(this,"marginTop");J.left-=j(this,"marginLeft");E.top+=j(G,"borderTopWidth");E.left+=j(G,"borderLeftWidth");F={top:J.top-E.top,left:J.left-E.left}}return F},offsetParent:function(){var E=this[0].offsetParent||document.body;while(E&&(!/^body|html$/i.test(E.tagName)&&o.css(E,"position")=="static")){E=E.offsetParent}return o(E)}});o.each(["Left","Top"],function(F,E){var G="scroll"+E;o.fn[G]=function(H){if(!this[0]){return null}return H!==g?this.each(function(){this==l||this==document?l.scrollTo(!F?H:o(l).scrollLeft(),F?H:o(l).scrollTop()):this[G]=H}):this[0]==l||this[0]==document?self[F?"pageYOffset":"pageXOffset"]||o.boxModel&&document.documentElement[G]||document.body[G]:this[0][G]}});o.each(["Height","Width"],function(I,G){var E=I?"Left":"Top",H=I?"Right":"Bottom",F=G.toLowerCase();o.fn["inner"+G]=function(){return this[0]?o.css(this[0],F,false,"padding"):null};o.fn["outer"+G]=function(K){return this[0]?o.css(this[0],F,false,K?"margin":"border"):null};var J=G.toLowerCase();o.fn[J]=function(K){return this[0]==l?document.compatMode=="CSS1Compat"&&document.documentElement["client"+G]||document.body["client"+G]:this[0]==document?Math.max(document.documentElement["client"+G],document.body["scroll"+G],document.documentElement["scroll"+G],document.body["offset"+G],document.documentElement["offset"+G]):K===g?(this.length?o.css(this[0],J):null):this.css(J,typeof K==="string"?K:K+"px")}})})();
\ No newline at end of file
diff --git a/js/jquery.js b/js/jquery.js
new file mode 100644
index 0000000..d69ee3d
--- /dev/null
+++ b/js/jquery.js
@@ -0,0 +1,4242 @@
+/*!
+ * jQuery JavaScript Library v1.3.1
+ * http://jquery.com/
+ *
+ * Copyright (c) 2009 John Resig
+ * Dual licensed under the MIT and GPL licenses.
+ * http://docs.jquery.com/License
+ *
+ * Date: 2009-01-28 17:38:00 -0500 (Wed, 28 Jan 2009)
+ * Revision: 6170
+ */
+(function(){
+
+var
+ // Will speed up references to window, and allows munging its name.
+ window = this,
+ // Will speed up references to undefined, and allows munging its name.
+ undefined,
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+ // Map over the $ in case of overwrite
+ _$ = window.$,
+
+ jQuery = window.jQuery = window.$ = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ return new jQuery.fn.init( selector, context );
+ },
+
+ // A simple way to check for HTML strings or ID strings
+ // (both of which we optimize for)
+ quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
+ // Is it a simple selector
+ isSimple = /^.[^:#\[\.,]*$/;
+
+jQuery.fn = jQuery.prototype = {
+ init: function( selector, context ) {
+ // Make sure that a selection was provided
+ selector = selector || document;
+
+ // Handle $(DOMElement)
+ if ( selector.nodeType ) {
+ this[0] = selector;
+ this.length = 1;
+ this.context = selector;
+ return this;
+ }
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ // Are we dealing with HTML string or an ID?
+ var match = quickExpr.exec( selector );
+
+ // Verify a match, and that no context was specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] )
+ selector = jQuery.clean( [ match[1] ], context );
+
+ // HANDLE: $("#id")
+ else {
+ var elem = document.getElementById( match[3] );
+
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem && elem.id != match[3] )
+ return jQuery().find( selector );
+
+ // Otherwise, we inject the element directly into the jQuery object
+ var ret = jQuery( elem || [] );
+ ret.context = document;
+ ret.selector = selector;
+ return ret;
+ }
+
+ // HANDLE: $(expr, [context])
+ // (which is just equivalent to: $(content).find(expr)
+ } else
+ return jQuery( context ).find( selector );
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) )
+ return jQuery( document ).ready( selector );
+
+ // Make sure that old selector state is passed along
+ if ( selector.selector && selector.context ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return this.setArray(jQuery.makeArray(selector));
+ },
+
+ // Start with an empty selector
+ selector: "",
+
+ // The current version of jQuery being used
+ jquery: "1.3.1",
+
+ // The number of elements contained in the matched element set
+ size: function() {
+ return this.length;
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num === undefined ?
+
+ // Return a 'clean' array
+ jQuery.makeArray( this ) :
+
+ // Return just the object
+ this[ num ];
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems, name, selector ) {
+ // Build a new jQuery matched element set
+ var ret = jQuery( elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+
+ ret.context = this.context;
+
+ if ( name === "find" )
+ ret.selector = this.selector + (this.selector ? " " : "") + selector;
+ else if ( name )
+ ret.selector = this.selector + "." + name + "(" + selector + ")";
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Force the current matched set of elements to become
+ // the specified array of elements (destroying the stack in the process)
+ // You should use pushStack() in order to do this, but maintain the stack
+ setArray: function( elems ) {
+ // Resetting the length to 0, then using the native Array push
+ // is a super-fast way to populate an object with array-like properties
+ this.length = 0;
+ Array.prototype.push.apply( this, elems );
+
+ return this;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem && elem.jquery ? elem[0] : elem
+ , this );
+ },
+
+ attr: function( name, value, type ) {
+ var options = name;
+
+ // Look for the case where we're accessing a style value
+ if ( typeof name === "string" )
+ if ( value === undefined )
+ return this[0] && jQuery[ type || "attr" ]( this[0], name );
+
+ else {
+ options = {};
+ options[ name ] = value;
+ }
+
+ // Check to see if we're setting style values
+ return this.each(function(i){
+ // Set all the styles
+ for ( name in options )
+ jQuery.attr(
+ type ?
+ this.style :
+ this,
+ name, jQuery.prop( this, options[ name ], type, i, name )
+ );
+ });
+ },
+
+ css: function( key, value ) {
+ // ignore negative width and height values
+ if ( (key == 'width' || key == 'height') && parseFloat(value) < 0 )
+ value = undefined;
+ return this.attr( key, value, "curCSS" );
+ },
+
+ text: function( text ) {
+ if ( typeof text !== "object" && text != null )
+ return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
+
+ var ret = "";
+
+ jQuery.each( text || this, function(){
+ jQuery.each( this.childNodes, function(){
+ if ( this.nodeType != 8 )
+ ret += this.nodeType != 1 ?
+ this.nodeValue :
+ jQuery.fn.text( [ this ] );
+ });
+ });
+
+ return ret;
+ },
+
+ wrapAll: function( html ) {
+ if ( this[0] ) {
+ // The elements to wrap the target around
+ var wrap = jQuery( html, this[0].ownerDocument ).clone();
+
+ if ( this[0].parentNode )
+ wrap.insertBefore( this[0] );
+
+ wrap.map(function(){
+ var elem = this;
+
+ while ( elem.firstChild )
+ elem = elem.firstChild;
+
+ return elem;
+ }).append(this);
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ return this.each(function(){
+ jQuery( this ).contents().wrapAll( html );
+ });
+ },
+
+ wrap: function( html ) {
+ return this.each(function(){
+ jQuery( this ).wrapAll( html );
+ });
+ },
+
+ append: function() {
+ return this.domManip(arguments, true, function(elem){
+ if (this.nodeType == 1)
+ this.appendChild( elem );
+ });
+ },
+
+ prepend: function() {
+ return this.domManip(arguments, true, function(elem){
+ if (this.nodeType == 1)
+ this.insertBefore( elem, this.firstChild );
+ });
+ },
+
+ before: function() {
+ return this.domManip(arguments, false, function(elem){
+ this.parentNode.insertBefore( elem, this );
+ });
+ },
+
+ after: function() {
+ return this.domManip(arguments, false, function(elem){
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ });
+ },
+
+ end: function() {
+ return this.prevObject || jQuery( [] );
+ },
+
+ // For internal use only.
+ // Behaves like an Array's .push method, not like a jQuery method.
+ push: [].push,
+
+ find: function( selector ) {
+ if ( this.length === 1 && !/,/.test(selector) ) {
+ var ret = this.pushStack( [], "find", selector );
+ ret.length = 0;
+ jQuery.find( selector, this[0], ret );
+ return ret;
+ } else {
+ var elems = jQuery.map(this, function(elem){
+ return jQuery.find( selector, elem );
+ });
+
+ return this.pushStack( /[^+>] [^+>]/.test( selector ) ?
+ jQuery.unique( elems ) :
+ elems, "find", selector );
+ }
+ },
+
+ clone: function( events ) {
+ // Do the clone
+ var ret = this.map(function(){
+ if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
+ // IE copies events bound via attachEvent when
+ // using cloneNode. Calling detachEvent on the
+ // clone will also remove the events from the orignal
+ // In order to get around this, we use innerHTML.
+ // Unfortunately, this means some modifications to
+ // attributes in IE that are actually only stored
+ // as properties will not be copied (such as the
+ // the name attribute on an input).
+ var clone = this.cloneNode(true),
+ container = document.createElement("div");
+ container.appendChild(clone);
+ return jQuery.clean([container.innerHTML])[0];
+ } else
+ return this.cloneNode(true);
+ });
+
+ // Need to set the expando to null on the cloned set if it exists
+ // removeData doesn't work here, IE removes it from the original as well
+ // this is primarily for IE but the data expando shouldn't be copied over in any browser
+ var clone = ret.find("*").andSelf().each(function(){
+ if ( this[ expando ] !== undefined )
+ this[ expando ] = null;
+ });
+
+ // Copy the events from the original to the clone
+ if ( events === true )
+ this.find("*").andSelf().each(function(i){
+ if (this.nodeType == 3)
+ return;
+ var events = jQuery.data( this, "events" );
+
+ for ( var type in events )
+ for ( var handler in events[ type ] )
+ jQuery.event.add( clone[ i ], type, events[ type ][ handler ], events[ type ][ handler ].data );
+ });
+
+ // Return the cloned set
+ return ret;
+ },
+
+ filter: function( selector ) {
+ return this.pushStack(
+ jQuery.isFunction( selector ) &&
+ jQuery.grep(this, function(elem, i){
+ return selector.call( elem, i );
+ }) ||
+
+ jQuery.multiFilter( selector, jQuery.grep(this, function(elem){
+ return elem.nodeType === 1;
+ }) ), "filter", selector );
+ },
+
+ closest: function( selector ) {
+ var pos = jQuery.expr.match.POS.test( selector ) ? jQuery(selector) : null;
+
+ return this.map(function(){
+ var cur = this;
+ while ( cur && cur.ownerDocument ) {
+ if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selector) )
+ return cur;
+ cur = cur.parentNode;
+ }
+ });
+ },
+
+ not: function( selector ) {
+ if ( typeof selector === "string" )
+ // test special case where just one selector is passed in
+ if ( isSimple.test( selector ) )
+ return this.pushStack( jQuery.multiFilter( selector, this, true ), "not", selector );
+ else
+ selector = jQuery.multiFilter( selector, this );
+
+ var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
+ return this.filter(function() {
+ return isArrayLike ? jQuery.inArray( this, selector ) < 0 : this != selector;
+ });
+ },
+
+ add: function( selector ) {
+ return this.pushStack( jQuery.unique( jQuery.merge(
+ this.get(),
+ typeof selector === "string" ?
+ jQuery( selector ) :
+ jQuery.makeArray( selector )
+ )));
+ },
+
+ is: function( selector ) {
+ return !!selector && jQuery.multiFilter( selector, this ).length > 0;
+ },
+
+ hasClass: function( selector ) {
+ return !!selector && this.is( "." + selector );
+ },
+
+ val: function( value ) {
+ if ( value === undefined ) {
+ var elem = this[0];
+
+ if ( elem ) {
+ if( jQuery.nodeName( elem, 'option' ) )
+ return (elem.attributes.value || {}).specified ? elem.value : elem.text;
+
+ // We need to handle select boxes special
+ if ( jQuery.nodeName( elem, "select" ) ) {
+ var index = elem.selectedIndex,
+ values = [],
+ options = elem.options,
+ one = elem.type == "select-one";
+
+ // Nothing was selected
+ if ( index < 0 )
+ return null;
+
+ // Loop through all the selected options
+ for ( var i = one ? index : 0, max = one ? index + 1 : options.length; i < max; i++ ) {
+ var option = options[ i ];
+
+ if ( option.selected ) {
+ // Get the specifc value for the option
+ value = jQuery(option).val();
+
+ // We don't need an array for one selects
+ if ( one )
+ return value;
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ }
+
+ // Everything else, we just grab the value
+ return (elem.value || "").replace(/\r/g, "");
+
+ }
+
+ return undefined;
+ }
+
+ if ( typeof value === "number" )
+ value += '';
+
+ return this.each(function(){
+ if ( this.nodeType != 1 )
+ return;
+
+ if ( jQuery.isArray(value) && /radio|checkbox/.test( this.type ) )
+ this.checked = (jQuery.inArray(this.value, value) >= 0 ||
+ jQuery.inArray(this.name, value) >= 0);
+
+ else if ( jQuery.nodeName( this, "select" ) ) {
+ var values = jQuery.makeArray(value);
+
+ jQuery( "option", this ).each(function(){
+ this.selected = (jQuery.inArray( this.value, values ) >= 0 ||
+ jQuery.inArray( this.text, values ) >= 0);
+ });
+
+ if ( !values.length )
+ this.selectedIndex = -1;
+
+ } else
+ this.value = value;
+ });
+ },
+
+ html: function( value ) {
+ return value === undefined ?
+ (this[0] ?
+ this[0].innerHTML :
+ null) :
+ this.empty().append( value );
+ },
+
+ replaceWith: function( value ) {
+ return this.after( value ).remove();
+ },
+
+ eq: function( i ) {
+ return this.slice( i, +i + 1 );
+ },
+
+ slice: function() {
+ return this.pushStack( Array.prototype.slice.apply( this, arguments ),
+ "slice", Array.prototype.slice.call(arguments).join(",") );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function(elem, i){
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ andSelf: function() {
+ return this.add( this.prevObject );
+ },
+
+ domManip: function( args, table, callback ) {
+ if ( this[0] ) {
+ var fragment = (this[0].ownerDocument || this[0]).createDocumentFragment(),
+ scripts = jQuery.clean( args, (this[0].ownerDocument || this[0]), fragment ),
+ first = fragment.firstChild,
+ extra = this.length > 1 ? fragment.cloneNode(true) : fragment;
+
+ if ( first )
+ for ( var i = 0, l = this.length; i < l; i++ )
+ callback.call( root(this[i], first), i > 0 ? extra.cloneNode(true) : fragment );
+
+ if ( scripts )
+ jQuery.each( scripts, evalScript );
+ }
+
+ return this;
+
+ function root( elem, cur ) {
+ return table && jQuery.nodeName(elem, "table") && jQuery.nodeName(cur, "tr") ?
+ (elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
+ elem;
+ }
+ }
+};
+
+// Give the init function the jQuery prototype for later instantiation
+jQuery.fn.init.prototype = jQuery.fn;
+
+function evalScript( i, elem ) {
+ if ( elem.src )
+ jQuery.ajax({
+ url: elem.src,
+ async: false,
+ dataType: "script"
+ });
+
+ else
+ jQuery.globalEval( elem.text || elem.textContent || elem.innerHTML || "" );
+
+ if ( elem.parentNode )
+ elem.parentNode.removeChild( elem );
+}
+
+function now(){
+ return +new Date;
+}
+
+jQuery.extend = jQuery.fn.extend = function() {
+ // copy reference to target object
+ var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+ target = arguments[1] || {};
+ // skip the boolean and the target
+ i = 2;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) )
+ target = {};
+
+ // extend jQuery itself if only one argument is passed
+ if ( length == i ) {
+ target = this;
+ --i;
+ }
+
+ for ( ; i < length; i++ )
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null )
+ // Extend the base object
+ for ( var name in options ) {
+ var src = target[ name ], copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy )
+ continue;
+
+ // Recurse if we're merging object values
+ if ( deep && copy && typeof copy === "object" && !copy.nodeType )
+ target[ name ] = jQuery.extend( deep,
+ // Never move original objects, clone them
+ src || ( copy.length != null ? [ ] : { } )
+ , copy );
+
+ // Don't bring in undefined values
+ else if ( copy !== undefined )
+ target[ name ] = copy;
+
+ }
+
+ // Return the modified object
+ return target;
+};
+
+// exclude the following css properties to add px
+var exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
+ // cache defaultView
+ defaultView = document.defaultView || {},
+ toString = Object.prototype.toString;
+
+jQuery.extend({
+ noConflict: function( deep ) {
+ window.$ = _$;
+
+ if ( deep )
+ window.jQuery = _jQuery;
+
+ return jQuery;
+ },
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return toString.call(obj) === "[object Function]";
+ },
+
+ isArray: function( obj ) {
+ return toString.call(obj) === "[object Array]";
+ },
+
+ // check if an element is in a (or is an) XML document
+ isXMLDoc: function( elem ) {
+ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
+ !!elem.ownerDocument && jQuery.isXMLDoc( elem.ownerDocument );
+ },
+
+ // Evalulates a script in a global context
+ globalEval: function( data ) {
+ data = jQuery.trim( data );
+
+ if ( data ) {
+ // Inspired by code by Andrea Giammarchi
+ // http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
+ var head = document.getElementsByTagName("head")[0] || document.documentElement,
+ script = document.createElement("script");
+
+ script.type = "text/javascript";
+ if ( jQuery.support.scriptEval )
+ script.appendChild( document.createTextNode( data ) );
+ else
+ script.text = data;
+
+ // Use insertBefore instead of appendChild to circumvent an IE6 bug.
+ // This arises when a base node is used (#2709).
+ head.insertBefore( script, head.firstChild );
+ head.removeChild( script );
+ }
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
+ },
+
+ // args is for internal usage only
+ each: function( object, callback, args ) {
+ var name, i = 0, length = object.length;
+
+ if ( args ) {
+ if ( length === undefined ) {
+ for ( name in object )
+ if ( callback.apply( object[ name ], args ) === false )
+ break;
+ } else
+ for ( ; i < length; )
+ if ( callback.apply( object[ i++ ], args ) === false )
+ break;
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( length === undefined ) {
+ for ( name in object )
+ if ( callback.call( object[ name ], name, object[ name ] ) === false )
+ break;
+ } else
+ for ( var value = object[0];
+ i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
+ }
+
+ return object;
+ },
+
+ prop: function( elem, value, type, i, name ) {
+ // Handle executable functions
+ if ( jQuery.isFunction( value ) )
+ value = value.call( elem, i );
+
+ // Handle passing in a number to a CSS property
+ return typeof value === "number" && type == "curCSS" && !exclude.test( name ) ?
+ value + "px" :
+ value;
+ },
+
+ className: {
+ // internal only, use addClass("class")
+ add: function( elem, classNames ) {
+ jQuery.each((classNames || "").split(/\s+/), function(i, className){
+ if ( elem.nodeType == 1 && !jQuery.className.has( elem.className, className ) )
+ elem.className += (elem.className ? " " : "") + className;
+ });
+ },
+
+ // internal only, use removeClass("class")
+ remove: function( elem, classNames ) {
+ if (elem.nodeType == 1)
+ elem.className = classNames !== undefined ?
+ jQuery.grep(elem.className.split(/\s+/), function(className){
+ return !jQuery.className.has( classNames, className );
+ }).join(" ") :
+ "";
+ },
+
+ // internal only, use hasClass("class")
+ has: function( elem, className ) {
+ return elem && jQuery.inArray( className, (elem.className || elem).toString().split(/\s+/) ) > -1;
+ }
+ },
+
+ // A method for quickly swapping in/out CSS properties to get correct calculations
+ swap: function( elem, options, callback ) {
+ var old = {};
+ // Remember the old values, and insert the new ones
+ for ( var name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ callback.call( elem );
+
+ // Revert the old values
+ for ( var name in options )
+ elem.style[ name ] = old[ name ];
+ },
+
+ css: function( elem, name, force ) {
+ if ( name == "width" || name == "height" ) {
+ var val, props = { position: "absolute", visibility: "hidden", display:"block" }, which = name == "width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ];
+
+ function getWH() {
+ val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
+ var padding = 0, border = 0;
+ jQuery.each( which, function() {
+ padding += parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
+ border += parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
+ });
+ val -= Math.round(padding + border);
+ }
+
+ if ( jQuery(elem).is(":visible") )
+ getWH();
+ else
+ jQuery.swap( elem, props, getWH );
+
+ return Math.max(0, val);
+ }
+
+ return jQuery.curCSS( elem, name, force );
+ },
+
+ curCSS: function( elem, name, force ) {
+ var ret, style = elem.style;
+
+ // We need to handle opacity special in IE
+ if ( name == "opacity" && !jQuery.support.opacity ) {
+ ret = jQuery.attr( style, "opacity" );
+
+ return ret == "" ?
+ "1" :
+ ret;
+ }
+
+ // Make sure we're using the right name for getting the float value
+ if ( name.match( /float/i ) )
+ name = styleFloat;
+
+ if ( !force && style && style[ name ] )
+ ret = style[ name ];
+
+ else if ( defaultView.getComputedStyle ) {
+
+ // Only "float" is needed here
+ if ( name.match( /float/i ) )
+ name = "float";
+
+ name = name.replace( /([A-Z])/g, "-$1" ).toLowerCase();
+
+ var computedStyle = defaultView.getComputedStyle( elem, null );
+
+ if ( computedStyle )
+ ret = computedStyle.getPropertyValue( name );
+
+ // We should always get a number back from opacity
+ if ( name == "opacity" && ret == "" )
+ ret = "1";
+
+ } else if ( elem.currentStyle ) {
+ var camelCase = name.replace(/\-(\w)/g, function(all, letter){
+ return letter.toUpperCase();
+ });
+
+ ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
+
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ if ( !/^\d+(px)?$/i.test( ret ) && /^\d/.test( ret ) ) {
+ // Remember the original values
+ var left = style.left, rsLeft = elem.runtimeStyle.left;
+
+ // Put in the new values to get a computed value out
+ elem.runtimeStyle.left = elem.currentStyle.left;
+ style.left = ret || 0;
+ ret = style.pixelLeft + "px";
+
+ // Revert the changed values
+ style.left = left;
+ elem.runtimeStyle.left = rsLeft;
+ }
+ }
+
+ return ret;
+ },
+
+ clean: function( elems, context, fragment ) {
+ context = context || document;
+
+ // !context.createElement fails in IE with an error but returns typeof 'object'
+ if ( typeof context.createElement === "undefined" )
+ context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
+
+ // If a single string is passed in and it's a single tag
+ // just do a createElement and skip the rest
+ if ( !fragment && elems.length === 1 && typeof elems[0] === "string" ) {
+ var match = /^<(\w+)\s*\/?>$/.exec(elems[0]);
+ if ( match )
+ return [ context.createElement( match[1] ) ];
+ }
+
+ var ret = [], scripts = [], div = context.createElement("div");
+
+ jQuery.each(elems, function(i, elem){
+ if ( typeof elem === "number" )
+ elem += '';
+
+ if ( !elem )
+ return;
+
+ // Convert html string into DOM nodes
+ if ( typeof elem === "string" ) {
+ // Fix "XHTML"-style tags in all browsers
+ elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
+ return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
+ all :
+ front + "></" + tag + ">";
+ });
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tags = jQuery.trim( elem ).toLowerCase();
+
+ var wrap =
+ // option or optgroup
+ !tags.indexOf("<opt") &&
+ [ 1, "<select multiple='multiple'>", "</select>" ] ||
+
+ !tags.indexOf("<leg") &&
+ [ 1, "<fieldset>", "</fieldset>" ] ||
+
+ tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
+ [ 1, "<table>", "</table>" ] ||
+
+ !tags.indexOf("<tr") &&
+ [ 2, "<table><tbody>", "</tbody></table>" ] ||
+
+ // <thead> matched above
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) &&
+ [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
+
+ !tags.indexOf("<col") &&
+ [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
+
+ // IE can't serialize <link> and <script> tags normally
+ !jQuery.support.htmlSerialize &&
+ [ 1, "div<div>", "</div>" ] ||
+
+ [ 0, "", "" ];
+
+ // Go to html and back, then peel off extra wrappers
+ div.innerHTML = wrap[1] + elem + wrap[2];
+
+ // Move to the right depth
+ while ( wrap[0]-- )
+ div = div.lastChild;
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( !jQuery.support.tbody ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
+ div.firstChild && div.firstChild.childNodes :
+
+ // String was a bare <thead> or <tfoot>
+ wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
+ div.childNodes :
+ [];
+
+ for ( var j = tbody.length - 1; j >= 0 ; --j )
+ if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
+ tbody[ j ].parentNode.removeChild( tbody[ j ] );
+
+ }
+
+ // IE completely kills leading whitespace when innerHTML is used
+ if ( !jQuery.support.leadingWhitespace && /^\s/.test( elem ) )
+ div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
+
+ elem = jQuery.makeArray( div.childNodes );
+ }
+
+ if ( elem.nodeType )
+ ret.push( elem );
+ else
+ ret = jQuery.merge( ret, elem );
+
+ });
+
+ if ( fragment ) {
+ for ( var i = 0; ret[i]; i++ ) {
+ if ( jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
+ scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
+ } else {
+ if ( ret[i].nodeType === 1 )
+ ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
+ fragment.appendChild( ret[i] );
+ }
+ }
+
+ return scripts;
+ }
+
+ return ret;
+ },
+
+ attr: function( elem, name, value ) {
+ // don't set attributes on text and comment nodes
+ if (!elem || elem.nodeType == 3 || elem.nodeType == 8)
+ return undefined;
+
+ var notxml = !jQuery.isXMLDoc( elem ),
+ // Whether we are setting (or getting)
+ set = value !== undefined;
+
+ // Try to normalize/fix the name
+ name = notxml && jQuery.props[ name ] || name;
+
+ // Only do all the following if this is a node (faster for style)
+ // IE elem.getAttribute passes even for style
+ if ( elem.tagName ) {
+
+ // These attributes require special treatment
+ var special = /href|src|style/.test( name );
+
+ // Safari mis-reports the default selected property of a hidden option
+ // Accessing the parent's selectedIndex property fixes it
+ if ( name == "selected" && elem.parentNode )
+ elem.parentNode.selectedIndex;
+
+ // If applicable, access the attribute via the DOM 0 way
+ if ( name in elem && notxml && !special ) {
+ if ( set ){
+ // We can't allow the type property to be changed (since it causes problems in IE)
+ if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
+ throw "type property can't be changed";
+
+ elem[ name ] = value;
+ }
+
+ // browsers index elements by id/name on forms, give priority to attributes.
+ if( jQuery.nodeName( elem, "form" ) && elem.getAttributeNode(name) )
+ return elem.getAttributeNode( name ).nodeValue;
+
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ if ( name == "tabIndex" ) {
+ var attributeNode = elem.getAttributeNode( "tabIndex" );
+ return attributeNode && attributeNode.specified
+ ? attributeNode.value
+ : elem.nodeName.match(/(button|input|object|select|textarea)/i)
+ ? 0
+ : elem.nodeName.match(/^(a|area)$/i) && elem.href
+ ? 0
+ : undefined;
+ }
+
+ return elem[ name ];
+ }
+
+ if ( !jQuery.support.style && notxml && name == "style" )
+ return jQuery.attr( elem.style, "cssText", value );
+
+ if ( set )
+ // convert the value to a string (all browsers do this but IE) see #1070
+ elem.setAttribute( name, "" + value );
+
+ var attr = !jQuery.support.hrefNormalized && notxml && special
+ // Some attributes require a special call on IE
+ ? elem.getAttribute( name, 2 )
+ : elem.getAttribute( name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return attr === null ? undefined : attr;
+ }
+
+ // elem is actually elem.style ... set the style
+
+ // IE uses filters for opacity
+ if ( !jQuery.support.opacity && name == "opacity" ) {
+ if ( set ) {
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ elem.zoom = 1;
+
+ // Set the alpha filter to set the opacity
+ elem.filter = (elem.filter || "").replace( /alpha\([^)]*\)/, "" ) +
+ (parseInt( value ) + '' == "NaN" ? "" : "alpha(opacity=" + value * 100 + ")");
+ }
+
+ return elem.filter && elem.filter.indexOf("opacity=") >= 0 ?
+ (parseFloat( elem.filter.match(/opacity=([^)]*)/)[1] ) / 100) + '':
+ "";
+ }
+
+ name = name.replace(/-([a-z])/ig, function(all, letter){
+ return letter.toUpperCase();
+ });
+
+ if ( set )
+ elem[ name ] = value;
+
+ return elem[ name ];
+ },
+
+ trim: function( text ) {
+ return (text || "").replace( /^\s+|\s+$/g, "" );
+ },
+
+ makeArray: function( array ) {
+ var ret = [];
+
+ if( array != null ){
+ var i = array.length;
+ // The window, strings (and functions) also have 'length'
+ if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
+ ret[0] = array;
+ else
+ while( i )
+ ret[--i] = array[i];
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, array ) {
+ for ( var i = 0, length = array.length; i < length; i++ )
+ // Use === because on IE, window == document
+ if ( array[ i ] === elem )
+ return i;
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ // We have to loop this way because IE & Opera overwrite the length
+ // expando of getElementsByTagName
+ var i = 0, elem, pos = first.length;
+ // Also, we need to make sure that the correct elements are being returned
+ // (IE returns comment nodes in a '*' query)
+ if ( !jQuery.support.getAll ) {
+ while ( (elem = second[ i++ ]) != null )
+ if ( elem.nodeType != 8 )
+ first[ pos++ ] = elem;
+
+ } else
+ while ( (elem = second[ i++ ]) != null )
+ first[ pos++ ] = elem;
+
+ return first;
+ },
+
+ unique: function( array ) {
+ var ret = [], done = {};
+
+ try {
+
+ for ( var i = 0, length = array.length; i < length; i++ ) {
+ var id = jQuery.data( array[ i ] );
+
+ if ( !done[ id ] ) {
+ done[ id ] = true;
+ ret.push( array[ i ] );
+ }
+ }
+
+ } catch( e ) {
+ ret = array;
+ }
+
+ return ret;
+ },
+
+ grep: function( elems, callback, inv ) {
+ var ret = [];
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( var i = 0, length = elems.length; i < length; i++ )
+ if ( !inv != !callback( elems[ i ], i ) )
+ ret.push( elems[ i ] );
+
+ return ret;
+ },
+
+ map: function( elems, callback ) {
+ var ret = [];
+
+ // Go through the array, translating each of the items to their
+ // new value (or values).
+ for ( var i = 0, length = elems.length; i < length; i++ ) {
+ var value = callback( elems[ i ], i );
+
+ if ( value != null )
+ ret[ ret.length ] = value;
+ }
+
+ return ret.concat.apply( [], ret );
+ }
+});
+
+// Use of jQuery.browser is deprecated.
+// It's included for backwards compatibility and plugins,
+// although they should work to migrate away.
+
+var userAgent = navigator.userAgent.toLowerCase();
+
+// Figure out what browser is being used
+jQuery.browser = {
+ version: (userAgent.match( /.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
+ safari: /webkit/.test( userAgent ),
+ opera: /opera/.test( userAgent ),
+ msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
+ mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
+};
+
+jQuery.each({
+ parent: function(elem){return elem.parentNode;},
+ parents: function(elem){return jQuery.dir(elem,"parentNode");},
+ next: function(elem){return jQuery.nth(elem,2,"nextSibling");},
+ prev: function(elem){return jQuery.nth(elem,2,"previousSibling");},
+ nextAll: function(elem){return jQuery.dir(elem,"nextSibling");},
+ prevAll: function(elem){return jQuery.dir(elem,"previousSibling");},
+ siblings: function(elem){return jQuery.sibling(elem.parentNode.firstChild,elem);},
+ children: function(elem){return jQuery.sibling(elem.firstChild);},
+ contents: function(elem){return jQuery.nodeName(elem,"iframe")?elem.contentDocument||elem.contentWindow.document:jQuery.makeArray(elem.childNodes);}
+}, function(name, fn){
+ jQuery.fn[ name ] = function( selector ) {
+ var ret = jQuery.map( this, fn );
+
+ if ( selector && typeof selector == "string" )
+ ret = jQuery.multiFilter( selector, ret );
+
+ return this.pushStack( jQuery.unique( ret ), name, selector );
+ };
+});
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function(name, original){
+ jQuery.fn[ name ] = function() {
+ var args = arguments;
+
+ return this.each(function(){
+ for ( var i = 0, length = args.length; i < length; i++ )
+ jQuery( args[ i ] )[ original ]( this );
+ });
+ };
+});
+
+jQuery.each({
+ removeAttr: function( name ) {
+ jQuery.attr( this, name, "" );
+ if (this.nodeType == 1)
+ this.removeAttribute( name );
+ },
+
+ addClass: function( classNames ) {
+ jQuery.className.add( this, classNames );
+ },
+
+ removeClass: function( classNames ) {
+ jQuery.className.remove( this, classNames );
+ },
+
+ toggleClass: function( classNames, state ) {
+ if( typeof state !== "boolean" )
+ state = !jQuery.className.has( this, classNames );
+ jQuery.className[ state ? "add" : "remove" ]( this, classNames );
+ },
+
+ remove: function( selector ) {
+ if ( !selector || jQuery.filter( selector, [ this ] ).length ) {
+ // Prevent memory leaks
+ jQuery( "*", this ).add([this]).each(function(){
+ jQuery.event.remove(this);
+ jQuery.removeData(this);
+ });
+ if (this.parentNode)
+ this.parentNode.removeChild( this );
+ }
+ },
+
+ empty: function() {
+ // Remove element nodes and prevent memory leaks
+ jQuery( ">*", this ).remove();
+
+ // Remove any remaining nodes
+ while ( this.firstChild )
+ this.removeChild( this.firstChild );
+ }
+}, function(name, fn){
+ jQuery.fn[ name ] = function(){
+ return this.each( fn, arguments );
+ };
+});
+
+// Helper function used by the dimensions and offset modules
+function num(elem, prop) {
+ return elem[0] && parseInt( jQuery.curCSS(elem[0], prop, true), 10 ) || 0;
+}
+var expando = "jQuery" + now(), uuid = 0, windowData = {};
+
+jQuery.extend({
+ cache: {},
+
+ data: function( elem, name, data ) {
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ];
+
+ // Compute a unique ID for the element
+ if ( !id )
+ id = elem[ expando ] = ++uuid;
+
+ // Only generate the data cache if we're
+ // trying to access or manipulate it
+ if ( name && !jQuery.cache[ id ] )
+ jQuery.cache[ id ] = {};
+
+ // Prevent overriding the named cache with undefined values
+ if ( data !== undefined )
+ jQuery.cache[ id ][ name ] = data;
+
+ // Return the named cache data, or the ID for the element
+ return name ?
+ jQuery.cache[ id ][ name ] :
+ id;
+ },
+
+ removeData: function( elem, name ) {
+ elem = elem == window ?
+ windowData :
+ elem;
+
+ var id = elem[ expando ];
+
+ // If we want to remove a specific section of the element's data
+ if ( name ) {
+ if ( jQuery.cache[ id ] ) {
+ // Remove the section of cache data
+ delete jQuery.cache[ id ][ name ];
+
+ // If we've removed all the data, remove the element's cache
+ name = "";
+
+ for ( name in jQuery.cache[ id ] )
+ break;
+
+ if ( !name )
+ jQuery.removeData( elem );
+ }
+
+ // Otherwise, we want to remove all of the element's data
+ } else {
+ // Clean up the element expando
+ try {
+ delete elem[ expando ];
+ } catch(e){
+ // IE has trouble directly removing the expando
+ // but it's ok with using removeAttribute
+ if ( elem.removeAttribute )
+ elem.removeAttribute( expando );
+ }
+
+ // Completely remove the data cache
+ delete jQuery.cache[ id ];
+ }
+ },
+ queue: function( elem, type, data ) {
+ if ( elem ){
+
+ type = (type || "fx") + "queue";
+
+ var q = jQuery.data( elem, type );
+
+ if ( !q || jQuery.isArray(data) )
+ q = jQuery.data( elem, type, jQuery.makeArray(data) );
+ else if( data )
+ q.push( data );
+
+ }
+ return q;
+ },
+
+ dequeue: function( elem, type ){
+ var queue = jQuery.queue( elem, type ),
+ fn = queue.shift();
+
+ if( !type || type === "fx" )
+ fn = queue[0];
+
+ if( fn !== undefined )
+ fn.call(elem);
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ){
+ var parts = key.split(".");
+ parts[1] = parts[1] ? "." + parts[1] : "";
+
+ if ( value === undefined ) {
+ var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
+
+ if ( data === undefined && this.length )
+ data = jQuery.data( this[0], key );
+
+ return data === undefined && parts[1] ?
+ this.data( parts[0] ) :
+ data;
+ } else
+ return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function(){
+ jQuery.data( this, key, value );
+ });
+ },
+
+ removeData: function( key ){
+ return this.each(function(){
+ jQuery.removeData( this, key );
+ });
+ },
+ queue: function(type, data){
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ }
+
+ if ( data === undefined )
+ return jQuery.queue( this[0], type );
+
+ return this.each(function(){
+ var queue = jQuery.queue( this, type, data );
+
+ if( type == "fx" && queue.length == 1 )
+ queue[0].call(this);
+ });
+ },
+ dequeue: function(type){
+ return this.each(function(){
+ jQuery.dequeue( this, type );
+ });
+ }
+});/*!
+ * Sizzle CSS Selector Engine - v0.9.3
+ * Copyright 2009, The Dojo Foundation
+ * Released under the MIT, BSD, and GPL Licenses.
+ * More information: http://sizzlejs.com/
+ */
+(function(){
+
+var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]+['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[]+)+|[>+~])(\s*,\s*)?/g,
+ done = 0,
+ toString = Object.prototype.toString;
+
+var Sizzle = function(selector, context, results, seed) {
+ results = results || [];
+ context = context || document;
+
+ if ( context.nodeType !== 1 && context.nodeType !== 9 )
+ return [];
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ var parts = [], m, set, checkSet, check, mode, extra, prune = true;
+
+ // Reset the position of the chunker regexp (start from head)
+ chunker.lastIndex = 0;
+
+ while ( (m = chunker.exec(selector)) !== null ) {
+ parts.push( m[1] );
+
+ if ( m[2] ) {
+ extra = RegExp.rightContext;
+ break;
+ }
+ }
+
+ if ( parts.length > 1 && origPOS.exec( selector ) ) {
+ if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
+ set = posProcess( parts[0] + parts[1], context );
+ } else {
+ set = Expr.relative[ parts[0] ] ?
+ [ context ] :
+ Sizzle( parts.shift(), context );
+
+ while ( parts.length ) {
+ selector = parts.shift();
+
+ if ( Expr.relative[ selector ] )
+ selector += parts.shift();
+
+ set = posProcess( selector, set );
+ }
+ }
+ } else {
+ var ret = seed ?
+ { expr: parts.pop(), set: makeArray(seed) } :
+ Sizzle.find( parts.pop(), parts.length === 1 && context.parentNode ? context.parentNode : context, isXML(context) );
+ set = Sizzle.filter( ret.expr, ret.set );
+
+ if ( parts.length > 0 ) {
+ checkSet = makeArray(set);
+ } else {
+ prune = false;
+ }
+
+ while ( parts.length ) {
+ var cur = parts.pop(), pop = cur;
+
+ if ( !Expr.relative[ cur ] ) {
+ cur = "";
+ } else {
+ pop = parts.pop();
+ }
+
+ if ( pop == null ) {
+ pop = context;
+ }
+
+ Expr.relative[ cur ]( checkSet, pop, isXML(context) );
+ }
+ }
+
+ if ( !checkSet ) {
+ checkSet = set;
+ }
+
+ if ( !checkSet ) {
+ throw "Syntax error, unrecognized expression: " + (cur || selector);
+ }
+
+ if ( toString.call(checkSet) === "[object Array]" ) {
+ if ( !prune ) {
+ results.push.apply( results, checkSet );
+ } else if ( context.nodeType === 1 ) {
+ for ( var i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
+ results.push( set[i] );
+ }
+ }
+ } else {
+ for ( var i = 0; checkSet[i] != null; i++ ) {
+ if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
+ results.push( set[i] );
+ }
+ }
+ }
+ } else {
+ makeArray( checkSet, results );
+ }
+
+ if ( extra ) {
+ Sizzle( extra, context, results, seed );
+ }
+
+ return results;
+};
+
+Sizzle.matches = function(expr, set){
+ return Sizzle(expr, null, null, set);
+};
+
+Sizzle.find = function(expr, context, isXML){
+ var set, match;
+
+ if ( !expr ) {
+ return [];
+ }
+
+ for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
+ var type = Expr.order[i], match;
+
+ if ( (match = Expr.match[ type ].exec( expr )) ) {
+ var left = RegExp.leftContext;
+
+ if ( left.substr( left.length - 1 ) !== "\\" ) {
+ match[1] = (match[1] || "").replace(/\\/g, "");
+ set = Expr.find[ type ]( match, context, isXML );
+ if ( set != null ) {
+ expr = expr.replace( Expr.match[ type ], "" );
+ break;
+ }
+ }
+ }
+ }
+
+ if ( !set ) {
+ set = context.getElementsByTagName("*");
+ }
+
+ return {set: set, expr: expr};
+};
+
+Sizzle.filter = function(expr, set, inplace, not){
+ var old = expr, result = [], curLoop = set, match, anyFound;
+
+ while ( expr && set.length ) {
+ for ( var type in Expr.filter ) {
+ if ( (match = Expr.match[ type ].exec( expr )) != null ) {
+ var filter = Expr.filter[ type ], found, item;
+ anyFound = false;
+
+ if ( curLoop == result ) {
+ result = [];
+ }
+
+ if ( Expr.preFilter[ type ] ) {
+ match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not );
+
+ if ( !match ) {
+ anyFound = found = true;
+ } else if ( match === true ) {
+ continue;
+ }
+ }
+
+ if ( match ) {
+ for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
+ if ( item ) {
+ found = filter( item, match, i, curLoop );
+ var pass = not ^ !!found;
+
+ if ( inplace && found != null ) {
+ if ( pass ) {
+ anyFound = true;
+ } else {
+ curLoop[i] = false;
+ }
+ } else if ( pass ) {
+ result.push( item );
+ anyFound = true;
+ }
+ }
+ }
+ }
+
+ if ( found !== undefined ) {
+ if ( !inplace ) {
+ curLoop = result;
+ }
+
+ expr = expr.replace( Expr.match[ type ], "" );
+
+ if ( !anyFound ) {
+ return [];
+ }
+
+ break;
+ }
+ }
+ }
+
+ expr = expr.replace(/\s*,\s*/, "");
+
+ // Improper expression
+ if ( expr == old ) {
+ if ( anyFound == null ) {
+ throw "Syntax error, unrecognized expression: " + expr;
+ } else {
+ break;
+ }
+ }
+
+ old = expr;
+ }
+
+ return curLoop;
+};
+
+var Expr = Sizzle.selectors = {
+ order: [ "ID", "NAME", "TAG" ],
+ match: {
+ ID: /#((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
+ CLASS: /\.((?:[\w\u00c0-\uFFFF_-]|\\.)+)/,
+ NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF_-]|\\.)+)['"]*\]/,
+ ATTR: /\[\s*((?:[\w\u00c0-\uFFFF_-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
+ TAG: /^((?:[\w\u00c0-\uFFFF\*_-]|\\.)+)/,
+ CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
+ POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
+ PSEUDO: /:((?:[\w\u00c0-\uFFFF_-]|\\.)+)(?:\((['"]*)((?:\([^\)]+\)|[^\2\(\)]*)+)\2\))?/
+ },
+ attrMap: {
+ "class": "className",
+ "for": "htmlFor"
+ },
+ attrHandle: {
+ href: function(elem){
+ return elem.getAttribute("href");
+ }
+ },
+ relative: {
+ "+": function(checkSet, part){
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ var cur = elem.previousSibling;
+ while ( cur && cur.nodeType !== 1 ) {
+ cur = cur.previousSibling;
+ }
+ checkSet[i] = typeof part === "string" ?
+ cur || false :
+ cur === part;
+ }
+ }
+
+ if ( typeof part === "string" ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ },
+ ">": function(checkSet, part, isXML){
+ if ( typeof part === "string" && !/\W/.test(part) ) {
+ part = isXML ? part : part.toUpperCase();
+
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ var parent = elem.parentNode;
+ checkSet[i] = parent.nodeName === part ? parent : false;
+ }
+ }
+ } else {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ checkSet[i] = typeof part === "string" ?
+ elem.parentNode :
+ elem.parentNode === part;
+ }
+ }
+
+ if ( typeof part === "string" ) {
+ Sizzle.filter( part, checkSet, true );
+ }
+ }
+ },
+ "": function(checkSet, part, isXML){
+ var doneName = "done" + (done++), checkFn = dirCheck;
+
+ if ( !part.match(/\W/) ) {
+ var nodeCheck = part = isXML ? part : part.toUpperCase();
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
+ },
+ "~": function(checkSet, part, isXML){
+ var doneName = "done" + (done++), checkFn = dirCheck;
+
+ if ( typeof part === "string" && !part.match(/\W/) ) {
+ var nodeCheck = part = isXML ? part : part.toUpperCase();
+ checkFn = dirNodeCheck;
+ }
+
+ checkFn("previousSibling", part, doneName, checkSet, nodeCheck, isXML);
+ }
+ },
+ find: {
+ ID: function(match, context, isXML){
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ return m ? [m] : [];
+ }
+ },
+ NAME: function(match, context, isXML){
+ if ( typeof context.getElementsByName !== "undefined" && !isXML ) {
+ return context.getElementsByName(match[1]);
+ }
+ },
+ TAG: function(match, context){
+ return context.getElementsByTagName(match[1]);
+ }
+ },
+ preFilter: {
+ CLASS: function(match, curLoop, inplace, result, not){
+ match = " " + match[1].replace(/\\/g, "") + " ";
+
+ var elem;
+ for ( var i = 0; (elem = curLoop[i]) != null; i++ ) {
+ if ( elem ) {
+ if ( not ^ (" " + elem.className + " ").indexOf(match) >= 0 ) {
+ if ( !inplace )
+ result.push( elem );
+ } else if ( inplace ) {
+ curLoop[i] = false;
+ }
+ }
+ }
+
+ return false;
+ },
+ ID: function(match){
+ return match[1].replace(/\\/g, "");
+ },
+ TAG: function(match, curLoop){
+ for ( var i = 0; curLoop[i] === false; i++ ){}
+ return curLoop[i] && isXML(curLoop[i]) ? match[1] : match[1].toUpperCase();
+ },
+ CHILD: function(match){
+ if ( match[1] == "nth" ) {
+ // parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
+ var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
+ match[2] == "even" && "2n" || match[2] == "odd" && "2n+1" ||
+ !/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
+
+ // calculate the numbers (first)n+(last) including if they are negative
+ match[2] = (test[1] + (test[2] || 1)) - 0;
+ match[3] = test[3] - 0;
+ }
+
+ // TODO: Move to normal caching system
+ match[0] = "done" + (done++);
+
+ return match;
+ },
+ ATTR: function(match){
+ var name = match[1].replace(/\\/g, "");
+
+ if ( Expr.attrMap[name] ) {
+ match[1] = Expr.attrMap[name];
+ }
+
+ if ( match[2] === "~=" ) {
+ match[4] = " " + match[4] + " ";
+ }
+
+ return match;
+ },
+ PSEUDO: function(match, curLoop, inplace, result, not){
+ if ( match[1] === "not" ) {
+ // If we're dealing with a complex expression, or a simple one
+ if ( match[3].match(chunker).length > 1 ) {
+ match[3] = Sizzle(match[3], null, null, curLoop);
+ } else {
+ var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
+ if ( !inplace ) {
+ result.push.apply( result, ret );
+ }
+ return false;
+ }
+ } else if ( Expr.match.POS.test( match[0] ) ) {
+ return true;
+ }
+
+ return match;
+ },
+ POS: function(match){
+ match.unshift( true );
+ return match;
+ }
+ },
+ filters: {
+ enabled: function(elem){
+ return elem.disabled === false && elem.type !== "hidden";
+ },
+ disabled: function(elem){
+ return elem.disabled === true;
+ },
+ checked: function(elem){
+ return elem.checked === true;
+ },
+ selected: function(elem){
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ elem.parentNode.selectedIndex;
+ return elem.selected === true;
+ },
+ parent: function(elem){
+ return !!elem.firstChild;
+ },
+ empty: function(elem){
+ return !elem.firstChild;
+ },
+ has: function(elem, i, match){
+ return !!Sizzle( match[3], elem ).length;
+ },
+ header: function(elem){
+ return /h\d/i.test( elem.nodeName );
+ },
+ text: function(elem){
+ return "text" === elem.type;
+ },
+ radio: function(elem){
+ return "radio" === elem.type;
+ },
+ checkbox: function(elem){
+ return "checkbox" === elem.type;
+ },
+ file: function(elem){
+ return "file" === elem.type;
+ },
+ password: function(elem){
+ return "password" === elem.type;
+ },
+ submit: function(elem){
+ return "submit" === elem.type;
+ },
+ image: function(elem){
+ return "image" === elem.type;
+ },
+ reset: function(elem){
+ return "reset" === elem.type;
+ },
+ button: function(elem){
+ return "button" === elem.type || elem.nodeName.toUpperCase() === "BUTTON";
+ },
+ input: function(elem){
+ return /input|select|textarea|button/i.test(elem.nodeName);
+ }
+ },
+ setFilters: {
+ first: function(elem, i){
+ return i === 0;
+ },
+ last: function(elem, i, match, array){
+ return i === array.length - 1;
+ },
+ even: function(elem, i){
+ return i % 2 === 0;
+ },
+ odd: function(elem, i){
+ return i % 2 === 1;
+ },
+ lt: function(elem, i, match){
+ return i < match[3] - 0;
+ },
+ gt: function(elem, i, match){
+ return i > match[3] - 0;
+ },
+ nth: function(elem, i, match){
+ return match[3] - 0 == i;
+ },
+ eq: function(elem, i, match){
+ return match[3] - 0 == i;
+ }
+ },
+ filter: {
+ CHILD: function(elem, match){
+ var type = match[1], parent = elem.parentNode;
+
+ var doneName = match[0];
+
+ if ( parent && (!parent[ doneName ] || !elem.nodeIndex) ) {
+ var count = 1;
+
+ for ( var node = parent.firstChild; node; node = node.nextSibling ) {
+ if ( node.nodeType == 1 ) {
+ node.nodeIndex = count++;
+ }
+ }
+
+ parent[ doneName ] = count - 1;
+ }
+
+ if ( type == "first" ) {
+ return elem.nodeIndex == 1;
+ } else if ( type == "last" ) {
+ return elem.nodeIndex == parent[ doneName ];
+ } else if ( type == "only" ) {
+ return parent[ doneName ] == 1;
+ } else if ( type == "nth" ) {
+ var add = false, first = match[2], last = match[3];
+
+ if ( first == 1 && last == 0 ) {
+ return true;
+ }
+
+ if ( first == 0 ) {
+ if ( elem.nodeIndex == last ) {
+ add = true;
+ }
+ } else if ( (elem.nodeIndex - last) % first == 0 && (elem.nodeIndex - last) / first >= 0 ) {
+ add = true;
+ }
+
+ return add;
+ }
+ },
+ PSEUDO: function(elem, match, i, array){
+ var name = match[1], filter = Expr.filters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ } else if ( name === "contains" ) {
+ return (elem.textContent || elem.innerText || "").indexOf(match[3]) >= 0;
+ } else if ( name === "not" ) {
+ var not = match[3];
+
+ for ( var i = 0, l = not.length; i < l; i++ ) {
+ if ( not[i] === elem ) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+ },
+ ID: function(elem, match){
+ return elem.nodeType === 1 && elem.getAttribute("id") === match;
+ },
+ TAG: function(elem, match){
+ return (match === "*" && elem.nodeType === 1) || elem.nodeName === match;
+ },
+ CLASS: function(elem, match){
+ return match.test( elem.className );
+ },
+ ATTR: function(elem, match){
+ var result = Expr.attrHandle[ match[1] ] ? Expr.attrHandle[ match[1] ]( elem ) : elem[ match[1] ] || elem.getAttribute( match[1] ), value = result + "", type = match[2], check = match[4];
+ return result == null ?
+ type === "!=" :
+ type === "=" ?
+ value === check :
+ type === "*=" ?
+ value.indexOf(check) >= 0 :
+ type === "~=" ?
+ (" " + value + " ").indexOf(check) >= 0 :
+ !match[4] ?
+ result :
+ type === "!=" ?
+ value != check :
+ type === "^=" ?
+ value.indexOf(check) === 0 :
+ type === "$=" ?
+ value.substr(value.length - check.length) === check :
+ type === "|=" ?
+ value === check || value.substr(0, check.length + 1) === check + "-" :
+ false;
+ },
+ POS: function(elem, match, i, array){
+ var name = match[2], filter = Expr.setFilters[ name ];
+
+ if ( filter ) {
+ return filter( elem, i, match, array );
+ }
+ }
+ }
+};
+
+var origPOS = Expr.match.POS;
+
+for ( var type in Expr.match ) {
+ Expr.match[ type ] = RegExp( Expr.match[ type ].source + /(?![^\[]*\])(?![^\(]*\))/.source );
+}
+
+var makeArray = function(array, results) {
+ array = Array.prototype.slice.call( array );
+
+ if ( results ) {
+ results.push.apply( results, array );
+ return results;
+ }
+
+ return array;
+};
+
+// Perform a simple check to determine if the browser is capable of
+// converting a NodeList to an array using builtin methods.
+try {
+ Array.prototype.slice.call( document.documentElement.childNodes );
+
+// Provide a fallback method if it does not work
+} catch(e){
+ makeArray = function(array, results) {
+ var ret = results || [];
+
+ if ( toString.call(array) === "[object Array]" ) {
+ Array.prototype.push.apply( ret, array );
+ } else {
+ if ( typeof array.length === "number" ) {
+ for ( var i = 0, l = array.length; i < l; i++ ) {
+ ret.push( array[i] );
+ }
+ } else {
+ for ( var i = 0; array[i]; i++ ) {
+ ret.push( array[i] );
+ }
+ }
+ }
+
+ return ret;
+ };
+}
+
+// Check to see if the browser returns elements by name when
+// querying by getElementById (and provide a workaround)
+(function(){
+ // We're going to inject a fake input element with a specified name
+ var form = document.createElement("form"),
+ id = "script" + (new Date).getTime();
+ form.innerHTML = "<input name='" + id + "'/>";
+
+ // Inject it into the root element, check its status, and remove it quickly
+ var root = document.documentElement;
+ root.insertBefore( form, root.firstChild );
+
+ // The workaround has to do additional checks after a getElementById
+ // Which slows things down for other browsers (hence the branching)
+ if ( !!document.getElementById( id ) ) {
+ Expr.find.ID = function(match, context, isXML){
+ if ( typeof context.getElementById !== "undefined" && !isXML ) {
+ var m = context.getElementById(match[1]);
+ return m ? m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ? [m] : undefined : [];
+ }
+ };
+
+ Expr.filter.ID = function(elem, match){
+ var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
+ return elem.nodeType === 1 && node && node.nodeValue === match;
+ };
+ }
+
+ root.removeChild( form );
+})();
+
+(function(){
+ // Check to see if the browser returns only elements
+ // when doing getElementsByTagName("*")
+
+ // Create a fake element
+ var div = document.createElement("div");
+ div.appendChild( document.createComment("") );
+
+ // Make sure no comments are found
+ if ( div.getElementsByTagName("*").length > 0 ) {
+ Expr.find.TAG = function(match, context){
+ var results = context.getElementsByTagName(match[1]);
+
+ // Filter out possible comments
+ if ( match[1] === "*" ) {
+ var tmp = [];
+
+ for ( var i = 0; results[i]; i++ ) {
+ if ( results[i].nodeType === 1 ) {
+ tmp.push( results[i] );
+ }
+ }
+
+ results = tmp;
+ }
+
+ return results;
+ };
+ }
+
+ // Check to see if an attribute returns normalized href attributes
+ div.innerHTML = "<a href='#'></a>";
+ if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
+ div.firstChild.getAttribute("href") !== "#" ) {
+ Expr.attrHandle.href = function(elem){
+ return elem.getAttribute("href", 2);
+ };
+ }
+})();
+
+if ( document.querySelectorAll ) (function(){
+ var oldSizzle = Sizzle, div = document.createElement("div");
+ div.innerHTML = "<p class='TEST'></p>";
+
+ // Safari can't handle uppercase or unicode characters when
+ // in quirks mode.
+ if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
+ return;
+ }
+
+ Sizzle = function(query, context, extra, seed){
+ context = context || document;
+
+ // Only use querySelectorAll on non-XML documents
+ // (ID selectors don't work in non-HTML documents)
+ if ( !seed && context.nodeType === 9 && !isXML(context) ) {
+ try {
+ return makeArray( context.querySelectorAll(query), extra );
+ } catch(e){}
+ }
+
+ return oldSizzle(query, context, extra, seed);
+ };
+
+ Sizzle.find = oldSizzle.find;
+ Sizzle.filter = oldSizzle.filter;
+ Sizzle.selectors = oldSizzle.selectors;
+ Sizzle.matches = oldSizzle.matches;
+})();
+
+if ( document.getElementsByClassName && document.documentElement.getElementsByClassName ) {
+ Expr.order.splice(1, 0, "CLASS");
+ Expr.find.CLASS = function(match, context) {
+ return context.getElementsByClassName(match[1]);
+ };
+}
+
+function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ elem = elem[dir];
+ var match = false;
+
+ while ( elem && elem.nodeType ) {
+ var done = elem[doneName];
+ if ( done ) {
+ match = checkSet[ done ];
+ break;
+ }
+
+ if ( elem.nodeType === 1 && !isXML )
+ elem[doneName] = i;
+
+ if ( elem.nodeName === cur ) {
+ match = elem;
+ break;
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
+ for ( var i = 0, l = checkSet.length; i < l; i++ ) {
+ var elem = checkSet[i];
+ if ( elem ) {
+ elem = elem[dir];
+ var match = false;
+
+ while ( elem && elem.nodeType ) {
+ if ( elem[doneName] ) {
+ match = checkSet[ elem[doneName] ];
+ break;
+ }
+
+ if ( elem.nodeType === 1 ) {
+ if ( !isXML )
+ elem[doneName] = i;
+
+ if ( typeof cur !== "string" ) {
+ if ( elem === cur ) {
+ match = true;
+ break;
+ }
+
+ } else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
+ match = elem;
+ break;
+ }
+ }
+
+ elem = elem[dir];
+ }
+
+ checkSet[i] = match;
+ }
+ }
+}
+
+var contains = document.compareDocumentPosition ? function(a, b){
+ return a.compareDocumentPosition(b) & 16;
+} : function(a, b){
+ return a !== b && (a.contains ? a.contains(b) : true);
+};
+
+var isXML = function(elem){
+ return elem.nodeType === 9 && elem.documentElement.nodeName !== "HTML" ||
+ !!elem.ownerDocument && isXML( elem.ownerDocument );
+};
+
+var posProcess = function(selector, context){
+ var tmpSet = [], later = "", match,
+ root = context.nodeType ? [context] : context;
+
+ // Position selectors must be done after the filter
+ // And so must :not(positional) so we move all PSEUDOs to the end
+ while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
+ later += match[0];
+ selector = selector.replace( Expr.match.PSEUDO, "" );
+ }
+
+ selector = Expr.relative[selector] ? selector + "*" : selector;
+
+ for ( var i = 0, l = root.length; i < l; i++ ) {
+ Sizzle( selector, root[i], tmpSet );
+ }
+
+ return Sizzle.filter( later, tmpSet );
+};
+
+// EXPOSE
+jQuery.find = Sizzle;
+jQuery.filter = Sizzle.filter;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.filters;
+
+Sizzle.selectors.filters.hidden = function(elem){
+ return "hidden" === elem.type ||
+ jQuery.css(elem, "display") === "none" ||
+ jQuery.css(elem, "visibility") === "hidden";
+};
+
+Sizzle.selectors.filters.visible = function(elem){
+ return "hidden" !== elem.type &&
+ jQuery.css(elem, "display") !== "none" &&
+ jQuery.css(elem, "visibility") !== "hidden";
+};
+
+Sizzle.selectors.filters.animated = function(elem){
+ return jQuery.grep(jQuery.timers, function(fn){
+ return elem === fn.elem;
+ }).length;
+};
+
+jQuery.multiFilter = function( expr, elems, not ) {
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return Sizzle.matches(expr, elems);
+};
+
+jQuery.dir = function( elem, dir ){
+ var matched = [], cur = elem[dir];
+ while ( cur && cur != document ) {
+ if ( cur.nodeType == 1 )
+ matched.push( cur );
+ cur = cur[dir];
+ }
+ return matched;
+};
+
+jQuery.nth = function(cur, result, dir, elem){
+ result = result || 1;
+ var num = 0;
+
+ for ( ; cur; cur = cur[dir] )
+ if ( cur.nodeType == 1 && ++num == result )
+ break;
+
+ return cur;
+};
+
+jQuery.sibling = function(n, elem){
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType == 1 && n != elem )
+ r.push( n );
+ }
+
+ return r;
+};
+
+return;
+
+window.Sizzle = Sizzle;
+
+})();
+/*
+ * A number of helper functions used for managing events.
+ * Many of the ideas behind this code originated from
+ * Dean Edwards' addEvent library.
+ */
+jQuery.event = {
+
+ // Bind an event to an element
+ // Original by Dean Edwards
+ add: function(elem, types, handler, data) {
+ if ( elem.nodeType == 3 || elem.nodeType == 8 )
+ return;
+
+ // For whatever reason, IE has trouble passing the window object
+ // around, causing it to be cloned in the process
+ if ( elem.setInterval && elem != window )
+ elem = window;
+
+ // Make sure that the function being executed has a unique ID
+ if ( !handler.guid )
+ handler.guid = this.guid++;
+
+ // if data is passed, bind to handler
+ if ( data !== undefined ) {
+ // Create temporary function pointer to original handler
+ var fn = handler;
+
+ // Create unique handler function, wrapped around original handler
+ handler = this.proxy( fn );
+
+ // Store data in unique handler
+ handler.data = data;
+ }
+
+ // Init the element's event structure
+ var events = jQuery.data(elem, "events") || jQuery.data(elem, "events", {}),
+ handle = jQuery.data(elem, "handle") || jQuery.data(elem, "handle", function(){
+ // Handle the second event of a trigger and when
+ // an event is called after a page has unloaded
+ return typeof jQuery !== "undefined" && !jQuery.event.triggered ?
+ jQuery.event.handle.apply(arguments.callee.elem, arguments) :
+ undefined;
+ });
+ // Add elem as a property of the handle function
+ // This is to prevent a memory leak with non-native
+ // event in IE.
+ handle.elem = elem;
+
+ // Handle multiple events separated by a space
+ // jQuery(...).bind("mouseover mouseout", fn);
+ jQuery.each(types.split(/\s+/), function(index, type) {
+ // Namespaced event handlers
+ var namespaces = type.split(".");
+ type = namespaces.shift();
+ handler.type = namespaces.slice().sort().join(".");
+
+ // Get the current list of functions bound to this event
+ var handlers = events[type];
+
+ if ( jQuery.event.specialAll[type] )
+ jQuery.event.specialAll[type].setup.call(elem, data, namespaces);
+
+ // Init the event handler queue
+ if (!handlers) {
+ handlers = events[type] = {};
+
+ // Check for a special event handler
+ // Only use addEventListener/attachEvent if the special
+ // events handler returns false
+ if ( !jQuery.event.special[type] || jQuery.event.special[type].setup.call(elem, data, namespaces) === false ) {
+ // Bind the global event handler to the element
+ if (elem.addEventListener)
+ elem.addEventListener(type, handle, false);
+ else if (elem.attachEvent)
+ elem.attachEvent("on" + type, handle);
+ }
+ }
+
+ // Add the function to the element's handler list
+ handlers[handler.guid] = handler;
+
+ // Keep track of which events have been used, for global triggering
+ jQuery.event.global[type] = true;
+ });
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ guid: 1,
+ global: {},
+
+ // Detach an event or set of events from an element
+ remove: function(elem, types, handler) {
+ // don't do events on text and comment nodes
+ if ( elem.nodeType == 3 || elem.nodeType == 8 )
+ return;
+
+ var events = jQuery.data(elem, "events"), ret, index;
+
+ if ( events ) {
+ // Unbind all events for the element
+ if ( types === undefined || (typeof types === "string" && types.charAt(0) == ".") )
+ for ( var type in events )
+ this.remove( elem, type + (types || "") );
+ else {
+ // types is actually an event object here
+ if ( types.type ) {
+ handler = types.handler;
+ types = types.type;
+ }
+
+ // Handle multiple events seperated by a space
+ // jQuery(...).unbind("mouseover mouseout", fn);
+ jQuery.each(types.split(/\s+/), function(index, type){
+ // Namespaced event handlers
+ var namespaces = type.split(".");
+ type = namespaces.shift();
+ var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+
+ if ( events[type] ) {
+ // remove the given handler for the given type
+ if ( handler )
+ delete events[type][handler.guid];
+
+ // remove all handlers for the given type
+ else
+ for ( var handle in events[type] )
+ // Handle the removal of namespaced events
+ if ( namespace.test(events[type][handle].type) )
+ delete events[type][handle];
+
+ if ( jQuery.event.specialAll[type] )
+ jQuery.event.specialAll[type].teardown.call(elem, namespaces);
+
+ // remove generic event handler if no more handlers exist
+ for ( ret in events[type] ) break;
+ if ( !ret ) {
+ if ( !jQuery.event.special[type] || jQuery.event.special[type].teardown.call(elem, namespaces) === false ) {
+ if (elem.removeEventListener)
+ elem.removeEventListener(type, jQuery.data(elem, "handle"), false);
+ else if (elem.detachEvent)
+ elem.detachEvent("on" + type, jQuery.data(elem, "handle"));
+ }
+ ret = null;
+ delete events[type];
+ }
+ }
+ });
+ }
+
+ // Remove the expando if it's no longer used
+ for ( ret in events ) break;
+ if ( !ret ) {
+ var handle = jQuery.data( elem, "handle" );
+ if ( handle ) handle.elem = null;
+ jQuery.removeData( elem, "events" );
+ jQuery.removeData( elem, "handle" );
+ }
+ }
+ },
+
+ // bubbling is internal
+ trigger: function( event, data, elem, bubbling ) {
+ // Event object or event type
+ var type = event.type || event;
+
+ if( !bubbling ){
+ event = typeof event === "object" ?
+ // jQuery.Event object
+ event[expando] ? event :
+ // Object literal
+ jQuery.extend( jQuery.Event(type), event ) :
+ // Just the event type (string)
+ jQuery.Event(type);
+
+ if ( type.indexOf("!") >= 0 ) {
+ event.type = type = type.slice(0, -1);
+ event.exclusive = true;
+ }
+
+ // Handle a global trigger
+ if ( !elem ) {
+ // Don't bubble custom events when global (to avoid too much overhead)
+ event.stopPropagation();
+ // Only trigger if we've ever bound an event for it
+ if ( this.global[type] )
+ jQuery.each( jQuery.cache, function(){
+ if ( this.events && this.events[type] )
+ jQuery.event.trigger( event, data, this.handle.elem );
+ });
+ }
+
+ // Handle triggering a single element
+
+ // don't do events on text and comment nodes
+ if ( !elem || elem.nodeType == 3 || elem.nodeType == 8 )
+ return undefined;
+
+ // Clean up in case it is reused
+ event.result = undefined;
+ event.target = elem;
+
+ // Clone the incoming data, if any
+ data = jQuery.makeArray(data);
+ data.unshift( event );
+ }
+
+ event.currentTarget = elem;
+
+ // Trigger the event, it is assumed that "handle" is a function
+ var handle = jQuery.data(elem, "handle");
+ if ( handle )
+ handle.apply( elem, data );
+
+ // Handle triggering native .onfoo handlers (and on links since we don't call .click() for links)
+ if ( (!elem[type] || (jQuery.nodeName(elem, 'a') && type == "click")) && elem["on"+type] && elem["on"+type].apply( elem, data ) === false )
+ event.result = false;
+
+ // Trigger the native events (except for clicks on links)
+ if ( !bubbling && elem[type] && !event.isDefaultPrevented() && !(jQuery.nodeName(elem, 'a') && type == "click") ) {
+ this.triggered = true;
+ try {
+ elem[ type ]();
+ // prevent IE from throwing an error for some hidden elements
+ } catch (e) {}
+ }
+
+ this.triggered = false;
+
+ if ( !event.isPropagationStopped() ) {
+ var parent = elem.parentNode || elem.ownerDocument;
+ if ( parent )
+ jQuery.event.trigger(event, data, parent, true);
+ }
+ },
+
+ handle: function(event) {
+ // returned undefined or false
+ var all, handlers;
+
+ event = arguments[0] = jQuery.event.fix( event || window.event );
+
+ // Namespaced event handlers
+ var namespaces = event.type.split(".");
+ event.type = namespaces.shift();
+
+ // Cache this now, all = true means, any handler
+ all = !namespaces.length && !event.exclusive;
+
+ var namespace = RegExp("(^|\\.)" + namespaces.slice().sort().join(".*\\.") + "(\\.|$)");
+
+ handlers = ( jQuery.data(this, "events") || {} )[event.type];
+
+ for ( var j in handlers ) {
+ var handler = handlers[j];
+
+ // Filter the functions by class
+ if ( all || namespace.test(handler.type) ) {
+ // Pass in a reference to the handler function itself
+ // So that we can later remove it
+ event.handler = handler;
+ event.data = handler.data;
+
+ var ret = handler.apply(this, arguments);
+
+ if( ret !== undefined ){
+ event.result = ret;
+ if ( ret === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+
+ if( event.isImmediatePropagationStopped() )
+ break;
+
+ }
+ }
+ },
+
+ props: "altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode metaKey newValue originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
+
+ fix: function(event) {
+ if ( event[expando] )
+ return event;
+
+ // store a copy of the original event object
+ // and "clone" to set read-only properties
+ var originalEvent = event;
+ event = jQuery.Event( originalEvent );
+
+ for ( var i = this.props.length, prop; i; ){
+ prop = this.props[ --i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Fix target property, if necessary
+ if ( !event.target )
+ event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
+
+ // check if target is a textnode (safari)
+ if ( event.target.nodeType == 3 )
+ event.target = event.target.parentNode;
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && event.fromElement )
+ event.relatedTarget = event.fromElement == event.target ? event.toElement : event.fromElement;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && event.clientX != null ) {
+ var doc = document.documentElement, body = document.body;
+ event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
+ event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
+ }
+
+ // Add which for key events
+ if ( !event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) )
+ event.which = event.charCode || event.keyCode;
+
+ // Add metaKey to non-Mac browsers (use ctrl for PC's and Meta for Macs)
+ if ( !event.metaKey && event.ctrlKey )
+ event.metaKey = event.ctrlKey;
+
+ // Add which for click: 1 == left; 2 == middle; 3 == right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && event.button )
+ event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
+
+ return event;
+ },
+
+ proxy: function( fn, proxy ){
+ proxy = proxy || function(){ return fn.apply(this, arguments); };
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || proxy.guid || this.guid++;
+ // So proxy can be declared as an argument
+ return proxy;
+ },
+
+ special: {
+ ready: {
+ // Make sure the ready event is setup
+ setup: bindReady,
+ teardown: function() {}
+ }
+ },
+
+ specialAll: {
+ live: {
+ setup: function( selector, namespaces ){
+ jQuery.event.add( this, namespaces[0], liveHandler );
+ },
+ teardown: function( namespaces ){
+ if ( namespaces.length ) {
+ var remove = 0, name = RegExp("(^|\\.)" + namespaces[0] + "(\\.|$)");
+
+ jQuery.each( (jQuery.data(this, "events").live || {}), function(){
+ if ( name.test(this.type) )
+ remove++;
+ });
+
+ if ( remove < 1 )
+ jQuery.event.remove( this, namespaces[0], liveHandler );
+ }
+ }
+ }
+ }
+};
+
+jQuery.Event = function( src ){
+ // Allow instantiation without the 'new' keyword
+ if( !this.preventDefault )
+ return new jQuery.Event(src);
+
+ // Event object
+ if( src && src.type ){
+ this.originalEvent = src;
+ this.type = src.type;
+ // Event type
+ }else
+ this.type = src;
+
+ // timeStamp is buggy for some events on Firefox(#3843)
+ // So we won't rely on the native value
+ this.timeStamp = now();
+
+ // Mark it as fixed
+ this[expando] = true;
+};
+
+function returnFalse(){
+ return false;
+}
+function returnTrue(){
+ return true;
+}
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ preventDefault: function() {
+ this.isDefaultPrevented = returnTrue;
+
+ var e = this.originalEvent;
+ if( !e )
+ return;
+ // if preventDefault exists run it on the original event
+ if (e.preventDefault)
+ e.preventDefault();
+ // otherwise set the returnValue property of the original event to false (IE)
+ e.returnValue = false;
+ },
+ stopPropagation: function() {
+ this.isPropagationStopped = returnTrue;
+
+ var e = this.originalEvent;
+ if( !e )
+ return;
+ // if stopPropagation exists run it on the original event
+ if (e.stopPropagation)
+ e.stopPropagation();
+ // otherwise set the cancelBubble property of the original event to true (IE)
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation:function(){
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ },
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse
+};
+// Checks if an event happened on an element within another element
+// Used in jQuery.event.special.mouseenter and mouseleave handlers
+var withinElement = function(event) {
+ // Check if mouse(over|out) are still within the same parent element
+ var parent = event.relatedTarget;
+ // Traverse up the tree
+ while ( parent && parent != this )
+ try { parent = parent.parentNode; }
+ catch(e) { parent = this; }
+
+ if( parent != this ){
+ // set the correct event type
+ event.type = event.data;
+ // handle event if we actually just moused on to a non sub-element
+ jQuery.event.handle.apply( this, arguments );
+ }
+};
+
+jQuery.each({
+ mouseover: 'mouseenter',
+ mouseout: 'mouseleave'
+}, function( orig, fix ){
+ jQuery.event.special[ fix ] = {
+ setup: function(){
+ jQuery.event.add( this, orig, withinElement, fix );
+ },
+ teardown: function(){
+ jQuery.event.remove( this, orig, withinElement );
+ }
+ };
+});
+
+jQuery.fn.extend({
+ bind: function( type, data, fn ) {
+ return type == "unload" ? this.one(type, data, fn) : this.each(function(){
+ jQuery.event.add( this, type, fn || data, fn && data );
+ });
+ },
+
+ one: function( type, data, fn ) {
+ var one = jQuery.event.proxy( fn || data, function(event) {
+ jQuery(this).unbind(event, one);
+ return (fn || data).apply( this, arguments );
+ });
+ return this.each(function(){
+ jQuery.event.add( this, type, one, fn && data);
+ });
+ },
+
+ unbind: function( type, fn ) {
+ return this.each(function(){
+ jQuery.event.remove( this, type, fn );
+ });
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function(){
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+
+ triggerHandler: function( type, data ) {
+ if( this[0] ){
+ var event = jQuery.Event(type);
+ event.preventDefault();
+ event.stopPropagation();
+ jQuery.event.trigger( event, data, this[0] );
+ return event.result;
+ }
+ },
+
+ toggle: function( fn ) {
+ // Save reference to arguments for access in closure
+ var args = arguments, i = 1;
+
+ // link all the functions, so any of them can unbind this click handler
+ while( i < args.length )
+ jQuery.event.proxy( fn, args[i++] );
+
+ return this.click( jQuery.event.proxy( fn, function(event) {
+ // Figure out which function to execute
+ this.lastToggle = ( this.lastToggle || 0 ) % i;
+
+ // Make sure that clicks stop
+ event.preventDefault();
+
+ // and execute the function
+ return args[ this.lastToggle++ ].apply( this, arguments ) || false;
+ }));
+ },
+
+ hover: function(fnOver, fnOut) {
+ return this.mouseenter(fnOver).mouseleave(fnOut);
+ },
+
+ ready: function(fn) {
+ // Attach the listeners
+ bindReady();
+
+ // If the DOM is already ready
+ if ( jQuery.isReady )
+ // Execute the function immediately
+ fn.call( document, jQuery );
+
+ // Otherwise, remember the function for later
+ else
+ // Add the function to the wait list
+ jQuery.readyList.push( fn );
+
+ return this;
+ },
+
+ live: function( type, fn ){
+ var proxy = jQuery.event.proxy( fn );
+ proxy.guid += this.selector + type;
+
+ jQuery(document).bind( liveConvert(type, this.selector), this.selector, proxy );
+
+ return this;
+ },
+
+ die: function( type, fn ){
+ jQuery(document).unbind( liveConvert(type, this.selector), fn ? { guid: fn.guid + this.selector + type } : null );
+ return this;
+ }
+});
+
+function liveHandler( event ){
+ var check = RegExp("(^|\\.)" + event.type + "(\\.|$)"),
+ stop = true,
+ elems = [];
+
+ jQuery.each(jQuery.data(this, "events").live || [], function(i, fn){
+ if ( check.test(fn.type) ) {
+ var elem = jQuery(event.target).closest(fn.data)[0];
+ if ( elem )
+ elems.push({ elem: elem, fn: fn });
+ }
+ });
+
+ jQuery.each(elems, function(){
+ if ( this.fn.call(this.elem, event, this.fn.data) === false )
+ stop = false;
+ });
+
+ return stop;
+}
+
+function liveConvert(type, selector){
+ return ["live", type, selector.replace(/\./g, "`").replace(/ /g, "|")].join(".");
+}
+
+jQuery.extend({
+ isReady: false,
+ readyList: [],
+ // Handle when the DOM is ready
+ ready: function() {
+ // Make sure that the DOM is not already loaded
+ if ( !jQuery.isReady ) {
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If there are functions bound, to execute
+ if ( jQuery.readyList ) {
+ // Execute all of them
+ jQuery.each( jQuery.readyList, function(){
+ this.call( document, jQuery );
+ });
+
+ // Reset the list of functions
+ jQuery.readyList = null;
+ }
+
+ // Trigger any bound ready events
+ jQuery(document).triggerHandler("ready");
+ }
+ }
+});
+
+var readyBound = false;
+
+function bindReady(){
+ if ( readyBound ) return;
+ readyBound = true;
+
+ // Mozilla, Opera and webkit nightlies currently support this event
+ if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", function(){
+ document.removeEventListener( "DOMContentLoaded", arguments.callee, false );
+ jQuery.ready();
+ }, false );
+
+ // If IE event model is used
+ } else if ( document.attachEvent ) {
+ // ensure firing before onload,
+ // maybe late but safe also for iframes
+ document.attachEvent("onreadystatechange", function(){
+ if ( document.readyState === "complete" ) {
+ document.detachEvent( "onreadystatechange", arguments.callee );
+ jQuery.ready();
+ }
+ });
+
+ // If IE and not an iframe
+ // continually check to see if the document is ready
+ if ( document.documentElement.doScroll && window == window.top ) (function(){
+ if ( jQuery.isReady ) return;
+
+ try {
+ // If IE is used, use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ document.documentElement.doScroll("left");
+ } catch( error ) {
+ setTimeout( arguments.callee, 0 );
+ return;
+ }
+
+ // and execute any waiting functions
+ jQuery.ready();
+ })();
+ }
+
+ // A fallback to window.onload, that will always work
+ jQuery.event.add( window, "load", jQuery.ready );
+}
+
+jQuery.each( ("blur,focus,load,resize,scroll,unload,click,dblclick," +
+ "mousedown,mouseup,mousemove,mouseover,mouseout,mouseenter,mouseleave," +
+ "change,select,submit,keydown,keypress,keyup,error").split(","), function(i, name){
+
+ // Handle event binding
+ jQuery.fn[name] = function(fn){
+ return fn ? this.bind(name, fn) : this.trigger(name);
+ };
+});
+
+// Prevent memory leaks in IE
+// And prevent errors on refresh with events like mouseover in other browsers
+// Window isn't included so as not to unbind existing unload events
+jQuery( window ).bind( 'unload', function(){
+ for ( var id in jQuery.cache )
+ // Skip the window
+ if ( id != 1 && jQuery.cache[ id ].handle )
+ jQuery.event.remove( jQuery.cache[ id ].handle.elem );
+});
+(function(){
+
+ jQuery.support = {};
+
+ var root = document.documentElement,
+ script = document.createElement("script"),
+ div = document.createElement("div"),
+ id = "script" + (new Date).getTime();
+
+ div.style.display = "none";
+ div.innerHTML = ' <link/><table></table><a href="/a" style="color:red;float:left;opacity:.5;">a</a><select><option>text</option></select><object><param/></object>';
+
+ var all = div.getElementsByTagName("*"),
+ a = div.getElementsByTagName("a")[0];
+
+ // Can't get basic test support
+ if ( !all || !all.length || !a ) {
+ return;
+ }
+
+ jQuery.support = {
+ // IE strips leading whitespace when .innerHTML is used
+ leadingWhitespace: div.firstChild.nodeType == 3,
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ tbody: !div.getElementsByTagName("tbody").length,
+
+ // Make sure that you can get all elements in an <object> element
+ // IE 7 always returns no results
+ objectAll: !!div.getElementsByTagName("object")[0]
+ .getElementsByTagName("*").length,
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ htmlSerialize: !!div.getElementsByTagName("link").length,
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText insted)
+ style: /red/.test( a.getAttribute("style") ),
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ hrefNormalized: a.getAttribute("href") === "/a",
+
+ // Make sure that element opacity exists
+ // (IE uses filter instead)
+ opacity: a.style.opacity === "0.5",
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ cssFloat: !!a.style.cssFloat,
+
+ // Will be defined later
+ scriptEval: false,
+ noCloneEvent: true,
+ boxModel: null
+ };
+
+ script.type = "text/javascript";
+ try {
+ script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
+ } catch(e){}
+
+ root.insertBefore( script, root.firstChild );
+
+ // Make sure that the execution of code works by injecting a script
+ // tag with appendChild/createTextNode
+ // (IE doesn't support this, fails, and uses .text instead)
+ if ( window[ id ] ) {
+ jQuery.support.scriptEval = true;
+ delete window[ id ];
+ }
+
+ root.removeChild( script );
+
+ if ( div.attachEvent && div.fireEvent ) {
+ div.attachEvent("onclick", function(){
+ // Cloning a node shouldn't copy over any
+ // bound event handlers (IE does this)
+ jQuery.support.noCloneEvent = false;
+ div.detachEvent("onclick", arguments.callee);
+ });
+ div.cloneNode(true).fireEvent("onclick");
+ }
+
+ // Figure out if the W3C box model works as expected
+ // document.body must exist before we can do this
+ jQuery(function(){
+ var div = document.createElement("div");
+ div.style.width = "1px";
+ div.style.paddingLeft = "1px";
+
+ document.body.appendChild( div );
+ jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
+ document.body.removeChild( div );
+ });
+})();
+
+var styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat";
+
+jQuery.props = {
+ "for": "htmlFor",
+ "class": "className",
+ "float": styleFloat,
+ cssFloat: styleFloat,
+ styleFloat: styleFloat,
+ readonly: "readOnly",
+ maxlength: "maxLength",
+ cellspacing: "cellSpacing",
+ rowspan: "rowSpan",
+ tabindex: "tabIndex"
+};
+jQuery.fn.extend({
+ // Keep a copy of the old load
+ _load: jQuery.fn.load,
+
+ load: function( url, params, callback ) {
+ if ( typeof url !== "string" )
+ return this._load( url );
+
+ var off = url.indexOf(" ");
+ if ( off >= 0 ) {
+ var selector = url.slice(off, url.length);
+ url = url.slice(0, off);
+ }
+
+ // Default to a GET request
+ var type = "GET";
+
+ // If the second parameter was provided
+ if ( params )
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+ // We assume that it's the callback
+ callback = params;
+ params = null;
+
+ // Otherwise, build a param string
+ } else if( typeof params === "object" ) {
+ params = jQuery.param( params );
+ type = "POST";
+ }
+
+ var self = this;
+
+ // Request the remote document
+ jQuery.ajax({
+ url: url,
+ type: type,
+ dataType: "html",
+ data: params,
+ complete: function(res, status){
+ // If successful, inject the HTML into all the matched elements
+ if ( status == "success" || status == "notmodified" )
+ // See if a selector was specified
+ self.html( selector ?
+ // Create a dummy div to hold the results
+ jQuery("<div/>")
+ // inject the contents of the document in, removing the scripts
+ // to avoid any 'Permission Denied' errors in IE
+ .append(res.responseText.replace(/<script(.|\s)*?\/script>/g, ""))
+
+ // Locate the specified elements
+ .find(selector) :
+
+ // If not, just inject the full result
+ res.responseText );
+
+ if( callback )
+ self.each( callback, [res.responseText, status, res] );
+ }
+ });
+ return this;
+ },
+
+ serialize: function() {
+ return jQuery.param(this.serializeArray());
+ },
+ serializeArray: function() {
+ return this.map(function(){
+ return this.elements ? jQuery.makeArray(this.elements) : this;
+ })
+ .filter(function(){
+ return this.name && !this.disabled &&
+ (this.checked || /select|textarea/i.test(this.nodeName) ||
+ /text|hidden|password/i.test(this.type));
+ })
+ .map(function(i, elem){
+ var val = jQuery(this).val();
+ return val == null ? null :
+ jQuery.isArray(val) ?
+ jQuery.map( val, function(val, i){
+ return {name: elem.name, value: val};
+ }) :
+ {name: elem.name, value: val};
+ }).get();
+ }
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( "ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","), function(i,o){
+ jQuery.fn[o] = function(f){
+ return this.bind(o, f);
+ };
+});
+
+var jsc = now();
+
+jQuery.extend({
+
+ get: function( url, data, callback, type ) {
+ // shift arguments if data argument was ommited
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = null;
+ }
+
+ return jQuery.ajax({
+ type: "GET",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get(url, null, callback, "script");
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get(url, data, callback, "json");
+ },
+
+ post: function( url, data, callback, type ) {
+ if ( jQuery.isFunction( data ) ) {
+ callback = data;
+ data = {};
+ }
+
+ return jQuery.ajax({
+ type: "POST",
+ url: url,
+ data: data,
+ success: callback,
+ dataType: type
+ });
+ },
+
+ ajaxSetup: function( settings ) {
+ jQuery.extend( jQuery.ajaxSettings, settings );
+ },
+
+ ajaxSettings: {
+ url: location.href,
+ global: true,
+ type: "GET",
+ contentType: "application/x-www-form-urlencoded",
+ processData: true,
+ async: true,
+ /*
+ timeout: 0,
+ data: null,
+ username: null,
+ password: null,
+ */
+ // Create the request object; Microsoft failed to properly
+ // implement the XMLHttpRequest in IE7, so we use the ActiveXObject when it is available
+ // This function can be overriden by calling jQuery.ajaxSetup
+ xhr:function(){
+ return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
+ },
+ accepts: {
+ xml: "application/xml, text/xml",
+ html: "text/html",
+ script: "text/javascript, application/javascript",
+ json: "application/json, text/javascript",
+ text: "text/plain",
+ _default: "*/*"
+ }
+ },
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+
+ ajax: function( s ) {
+ // Extend the settings, but re-extend 's' so that it can be
+ // checked again later (in the test suite, specifically)
+ s = jQuery.extend(true, s, jQuery.extend(true, {}, jQuery.ajaxSettings, s));
+
+ var jsonp, jsre = /=\?(&|$)/g, status, data,
+ type = s.type.toUpperCase();
+
+ // convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" )
+ s.data = jQuery.param(s.data);
+
+ // Handle JSONP Parameter Callbacks
+ if ( s.dataType == "jsonp" ) {
+ if ( type == "GET" ) {
+ if ( !s.url.match(jsre) )
+ s.url += (s.url.match(/\?/) ? "&" : "?") + (s.jsonp || "callback") + "=?";
+ } else if ( !s.data || !s.data.match(jsre) )
+ s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
+ s.dataType = "json";
+ }
+
+ // Build temporary JSONP function
+ if ( s.dataType == "json" && (s.data && s.data.match(jsre) || s.url.match(jsre)) ) {
+ jsonp = "jsonp" + jsc++;
+
+ // Replace the =? sequence both in the query string and the data
+ if ( s.data )
+ s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
+ s.url = s.url.replace(jsre, "=" + jsonp + "$1");
+
+ // We need to make sure
+ // that a JSONP style response is executed properly
+ s.dataType = "script";
+
+ // Handle JSONP-style loading
+ window[ jsonp ] = function(tmp){
+ data = tmp;
+ success();
+ complete();
+ // Garbage collect
+ window[ jsonp ] = undefined;
+ try{ delete window[ jsonp ]; } catch(e){}
+ if ( head )
+ head.removeChild( script );
+ };
+ }
+
+ if ( s.dataType == "script" && s.cache == null )
+ s.cache = false;
+
+ if ( s.cache === false && type == "GET" ) {
+ var ts = now();
+ // try replacing _= if it is there
+ var ret = s.url.replace(/(\?|&)_=.*?(&|$)/, "$1_=" + ts + "$2");
+ // if nothing was replaced, add timestamp to the end
+ s.url = ret + ((ret == s.url) ? (s.url.match(/\?/) ? "&" : "?") + "_=" + ts : "");
+ }
+
+ // If data is available, append data to url for get requests
+ if ( s.data && type == "GET" ) {
+ s.url += (s.url.match(/\?/) ? "&" : "?") + s.data;
+
+ // IE likes to send both get and post data, prevent this
+ s.data = null;
+ }
+
+ // Watch for a new set of requests
+ if ( s.global && ! jQuery.active++ )
+ jQuery.event.trigger( "ajaxStart" );
+
+ // Matches an absolute URL, and saves the domain
+ var parts = /^(\w+:)?\/\/([^\/?#]+)/.exec( s.url );
+
+ // If we're requesting a remote document
+ // and trying to load JSON or Script with a GET
+ if ( s.dataType == "script" && type == "GET" && parts
+ && ( parts[1] && parts[1] != location.protocol || parts[2] != location.host )){
+
+ var head = document.getElementsByTagName("head")[0];
+ var script = document.createElement("script");
+ script.src = s.url;
+ if (s.scriptCharset)
+ script.charset = s.scriptCharset;
+
+ // Handle Script loading
+ if ( !jsonp ) {
+ var done = false;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function(){
+ if ( !done && (!this.readyState ||
+ this.readyState == "loaded" || this.readyState == "complete") ) {
+ done = true;
+ success();
+ complete();
+ head.removeChild( script );
+ }
+ };
+ }
+
+ head.appendChild(script);
+
+ // We handle everything using the script element injection
+ return undefined;
+ }
+
+ var requestDone = false;
+
+ // Create the request object
+ var xhr = s.xhr();
+
+ // Open the socket
+ // Passing null username, generates a login popup on Opera (#2865)
+ if( s.username )
+ xhr.open(type, s.url, s.async, s.username, s.password);
+ else
+ xhr.open(type, s.url, s.async);
+
+ // Need an extra try/catch for cross domain requests in Firefox 3
+ try {
+ // Set the correct header, if data is being sent
+ if ( s.data )
+ xhr.setRequestHeader("Content-Type", s.contentType);
+
+ // Set the If-Modified-Since header, if ifModified mode.
+ if ( s.ifModified )
+ xhr.setRequestHeader("If-Modified-Since",
+ jQuery.lastModified[s.url] || "Thu, 01 Jan 1970 00:00:00 GMT" );
+
+ // Set header so the called script knows that it's an XMLHttpRequest
+ xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
+
+ // Set the Accepts header for the server, depending on the dataType
+ xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
+ s.accepts[ s.dataType ] + ", */*" :
+ s.accepts._default );
+ } catch(e){}
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && s.beforeSend(xhr, s) === false ) {
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active )
+ jQuery.event.trigger( "ajaxStop" );
+ // close opended socket
+ xhr.abort();
+ return false;
+ }
+
+ if ( s.global )
+ jQuery.event.trigger("ajaxSend", [xhr, s]);
+
+ // Wait for a response to come back
+ var onreadystatechange = function(isTimeout){
+ // The request was aborted, clear the interval and decrement jQuery.active
+ if (xhr.readyState == 0) {
+ if (ival) {
+ // clear poll interval
+ clearInterval(ival);
+ ival = null;
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active )
+ jQuery.event.trigger( "ajaxStop" );
+ }
+ // The transfer is complete and the data is available, or the request timed out
+ } else if ( !requestDone && xhr && (xhr.readyState == 4 || isTimeout == "timeout") ) {
+ requestDone = true;
+
+ // clear poll interval
+ if (ival) {
+ clearInterval(ival);
+ ival = null;
+ }
+
+ status = isTimeout == "timeout" ? "timeout" :
+ !jQuery.httpSuccess( xhr ) ? "error" :
+ s.ifModified && jQuery.httpNotModified( xhr, s.url ) ? "notmodified" :
+ "success";
+
+ if ( status == "success" ) {
+ // Watch for, and catch, XML document parse errors
+ try {
+ // process the data (runs the xml through httpData regardless of callback)
+ data = jQuery.httpData( xhr, s.dataType, s );
+ } catch(e) {
+ status = "parsererror";
+ }
+ }
+
+ // Make sure that the request was successful or notmodified
+ if ( status == "success" ) {
+ // Cache Last-Modified header, if ifModified mode.
+ var modRes;
+ try {
+ modRes = xhr.getResponseHeader("Last-Modified");
+ } catch(e) {} // swallow exception thrown by FF if header is not available
+
+ if ( s.ifModified && modRes )
+ jQuery.lastModified[s.url] = modRes;
+
+ // JSONP handles its own success callback
+ if ( !jsonp )
+ success();
+ } else
+ jQuery.handleError(s, xhr, status);
+
+ // Fire the complete handlers
+ complete();
+
+ if ( isTimeout )
+ xhr.abort();
+
+ // Stop memory leaks
+ if ( s.async )
+ xhr = null;
+ }
+ };
+
+ if ( s.async ) {
+ // don't attach the handler to the request, just poll it instead
+ var ival = setInterval(onreadystatechange, 13);
+
+ // Timeout checker
+ if ( s.timeout > 0 )
+ setTimeout(function(){
+ // Check to see if the request is still happening
+ if ( xhr && !requestDone )
+ onreadystatechange( "timeout" );
+ }, s.timeout);
+ }
+
+ // Send the data
+ try {
+ xhr.send(s.data);
+ } catch(e) {
+ jQuery.handleError(s, xhr, null, e);
+ }
+
+ // firefox 1.5 doesn't fire statechange for sync requests
+ if ( !s.async )
+ onreadystatechange();
+
+ function success(){
+ // If a local callback was specified, fire it and pass it the data
+ if ( s.success )
+ s.success( data, status );
+
+ // Fire the global callback
+ if ( s.global )
+ jQuery.event.trigger( "ajaxSuccess", [xhr, s] );
+ }
+
+ function complete(){
+ // Process result
+ if ( s.complete )
+ s.complete(xhr, status);
+
+ // The request was completed
+ if ( s.global )
+ jQuery.event.trigger( "ajaxComplete", [xhr, s] );
+
+ // Handle the global AJAX counter
+ if ( s.global && ! --jQuery.active )
+ jQuery.event.trigger( "ajaxStop" );
+ }
+
+ // return XMLHttpRequest to allow aborting the request etc.
+ return xhr;
+ },
+
+ handleError: function( s, xhr, status, e ) {
+ // If a local callback was specified, fire it
+ if ( s.error ) s.error( xhr, status, e );
+
+ // Fire the global callback
+ if ( s.global )
+ jQuery.event.trigger( "ajaxError", [xhr, s, e] );
+ },
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Determines if an XMLHttpRequest was successful or not
+ httpSuccess: function( xhr ) {
+ try {
+ // IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
+ return !xhr.status && location.protocol == "file:" ||
+ ( xhr.status >= 200 && xhr.status < 300 ) || xhr.status == 304 || xhr.status == 1223;
+ } catch(e){}
+ return false;
+ },
+
+ // Determines if an XMLHttpRequest returns NotModified
+ httpNotModified: function( xhr, url ) {
+ try {
+ var xhrRes = xhr.getResponseHeader("Last-Modified");
+
+ // Firefox always returns 200. check Last-Modified date
+ return xhr.status == 304 || xhrRes == jQuery.lastModified[url];
+ } catch(e){}
+ return false;
+ },
+
+ httpData: function( xhr, type, s ) {
+ var ct = xhr.getResponseHeader("content-type"),
+ xml = type == "xml" || !type && ct && ct.indexOf("xml") >= 0,
+ data = xml ? xhr.responseXML : xhr.responseText;
+
+ if ( xml && data.documentElement.tagName == "parsererror" )
+ throw "parsererror";
+
+ // Allow a pre-filtering function to sanitize the response
+ // s != null is checked to keep backwards compatibility
+ if( s && s.dataFilter )
+ data = s.dataFilter( data, type );
+
+ // The filter can actually parse the response
+ if( typeof data === "string" ){
+
+ // If the type is "script", eval it in global context
+ if ( type == "script" )
+ jQuery.globalEval( data );
+
+ // Get the JavaScript object, if JSON is used.
+ if ( type == "json" )
+ data = window["eval"]("(" + data + ")");
+ }
+
+ return data;
+ },
+
+ // Serialize an array of form elements or a set of
+ // key/values into a query string
+ param: function( a ) {
+ var s = [ ];
+
+ function add( key, value ){
+ s[ s.length ] = encodeURIComponent(key) + '=' + encodeURIComponent(value);
+ };
+
+ // If an array was passed in, assume that it is an array
+ // of form elements
+ if ( jQuery.isArray(a) || a.jquery )
+ // Serialize the form elements
+ jQuery.each( a, function(){
+ add( this.name, this.value );
+ });
+
+ // Otherwise, assume that it's an object of key/value pairs
+ else
+ // Serialize the key/values
+ for ( var j in a )
+ // If the value is an array then the key names need to be repeated
+ if ( jQuery.isArray(a[j]) )
+ jQuery.each( a[j], function(){
+ add( j, this );
+ });
+ else
+ add( j, jQuery.isFunction(a[j]) ? a[j]() : a[j] );
+
+ // Return the resulting serialization
+ return s.join("&").replace(/%20/g, "+");
+ }
+
+});
+var elemdisplay = {},
+ timerId,
+ fxAttrs = [
+ // height animations
+ [ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
+ // width animations
+ [ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
+ // opacity animations
+ [ "opacity" ]
+ ];
+
+function genFx( type, num ){
+ var obj = {};
+ jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function(){
+ obj[ this ] = type;
+ });
+ return obj;
+}
+
+jQuery.fn.extend({
+ show: function(speed,callback){
+ if ( speed ) {
+ return this.animate( genFx("show", 3), speed, callback);
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ){
+ var old = jQuery.data(this[i], "olddisplay");
+
+ this[i].style.display = old || "";
+
+ if ( jQuery.css(this[i], "display") === "none" ) {
+ var tagName = this[i].tagName, display;
+
+ if ( elemdisplay[ tagName ] ) {
+ display = elemdisplay[ tagName ];
+ } else {
+ var elem = jQuery("<" + tagName + " />").appendTo("body");
+
+ display = elem.css("display");
+ if ( display === "none" )
+ display = "block";
+
+ elem.remove();
+
+ elemdisplay[ tagName ] = display;
+ }
+
+ this[i].style.display = jQuery.data(this[i], "olddisplay", display);
+ }
+ }
+
+ return this;
+ }
+ },
+
+ hide: function(speed,callback){
+ if ( speed ) {
+ return this.animate( genFx("hide", 3), speed, callback);
+ } else {
+ for ( var i = 0, l = this.length; i < l; i++ ){
+ var old = jQuery.data(this[i], "olddisplay");
+ if ( !old && old !== "none" )
+ jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
+ this[i].style.display = "none";
+ }
+ return this;
+ }
+ },
+
+ // Save the old toggle function
+ _toggle: jQuery.fn.toggle,
+
+ toggle: function( fn, fn2 ){
+ var bool = typeof fn === "boolean";
+
+ return jQuery.isFunction(fn) && jQuery.isFunction(fn2) ?
+ this._toggle.apply( this, arguments ) :
+ fn == null || bool ?
+ this.each(function(){
+ var state = bool ? fn : jQuery(this).is(":hidden");
+ jQuery(this)[ state ? "show" : "hide" ]();
+ }) :
+ this.animate(genFx("toggle", 3), fn, fn2);
+ },
+
+ fadeTo: function(speed,to,callback){
+ return this.animate({opacity: to}, speed, callback);
+ },
+
+ animate: function( prop, speed, easing, callback ) {
+ var optall = jQuery.speed(speed, easing, callback);
+
+ return this[ optall.queue === false ? "each" : "queue" ](function(){
+
+ var opt = jQuery.extend({}, optall), p,
+ hidden = this.nodeType == 1 && jQuery(this).is(":hidden"),
+ self = this;
+
+ for ( p in prop ) {
+ if ( prop[p] == "hide" && hidden || prop[p] == "show" && !hidden )
+ return opt.complete.call(this);
+
+ if ( ( p == "height" || p == "width" ) && this.style ) {
+ // Store display property
+ opt.display = jQuery.css(this, "display");
+
+ // Make sure that nothing sneaks out
+ opt.overflow = this.style.overflow;
+ }
+ }
+
+ if ( opt.overflow != null )
+ this.style.overflow = "hidden";
+
+ opt.curAnim = jQuery.extend({}, prop);
+
+ jQuery.each( prop, function(name, val){
+ var e = new jQuery.fx( self, opt, name );
+
+ if ( /toggle|show|hide/.test(val) )
+ e[ val == "toggle" ? hidden ? "show" : "hide" : val ]( prop );
+ else {
+ var parts = val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),
+ start = e.cur(true) || 0;
+
+ if ( parts ) {
+ var end = parseFloat(parts[2]),
+ unit = parts[3] || "px";
+
+ // We need to compute starting value
+ if ( unit != "px" ) {
+ self.style[ name ] = (end || 1) + unit;
+ start = ((end || 1) / e.cur(true)) * start;
+ self.style[ name ] = start + unit;
+ }
+
+ // If a +=/-= token was provided, we're doing a relative animation
+ if ( parts[1] )
+ end = ((parts[1] == "-=" ? -1 : 1) * end) + start;
+
+ e.custom( start, end, unit );
+ } else
+ e.custom( start, val, "" );
+ }
+ });
+
+ // For JS strict compliance
+ return true;
+ });
+ },
+
+ stop: function(clearQueue, gotoEnd){
+ var timers = jQuery.timers;
+
+ if (clearQueue)
+ this.queue([]);
+
+ this.each(function(){
+ // go in reverse order so anything added to the queue during the loop is ignored
+ for ( var i = timers.length - 1; i >= 0; i-- )
+ if ( timers[i].elem == this ) {
+ if (gotoEnd)
+ // force the next step to be the last
+ timers[i](true);
+ timers.splice(i, 1);
+ }
+ });
+
+ // start the next in the queue if the last step wasn't forced
+ if (!gotoEnd)
+ this.dequeue();
+
+ return this;
+ }
+
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show", 1),
+ slideUp: genFx("hide", 1),
+ slideToggle: genFx("toggle", 1),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" }
+}, function( name, props ){
+ jQuery.fn[ name ] = function( speed, callback ){
+ return this.animate( props, speed, callback );
+ };
+});
+
+jQuery.extend({
+
+ speed: function(speed, easing, fn) {
+ var opt = typeof speed === "object" ? speed : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction(easing) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ jQuery.fx.speeds[opt.duration] || jQuery.fx.speeds._default;
+
+ // Queueing
+ opt.old = opt.complete;
+ opt.complete = function(){
+ if ( opt.queue !== false )
+ jQuery(this).dequeue();
+ if ( jQuery.isFunction( opt.old ) )
+ opt.old.call( this );
+ };
+
+ return opt;
+ },
+
+ easing: {
+ linear: function( p, n, firstNum, diff ) {
+ return firstNum + diff * p;
+ },
+ swing: function( p, n, firstNum, diff ) {
+ return ((-Math.cos(p*Math.PI)/2) + 0.5) * diff + firstNum;
+ }
+ },
+
+ timers: [],
+
+ fx: function( elem, options, prop ){
+ this.options = options;
+ this.elem = elem;
+ this.prop = prop;
+
+ if ( !options.orig )
+ options.orig = {};
+ }
+
+});
+
+jQuery.fx.prototype = {
+
+ // Simple function for setting a style value
+ update: function(){
+ if ( this.options.step )
+ this.options.step.call( this.elem, this.now, this );
+
+ (jQuery.fx.step[this.prop] || jQuery.fx.step._default)( this );
+
+ // Set display property to block for height/width animations
+ if ( ( this.prop == "height" || this.prop == "width" ) && this.elem.style )
+ this.elem.style.display = "block";
+ },
+
+ // Get the current size
+ cur: function(force){
+ if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) )
+ return this.elem[ this.prop ];
+
+ var r = parseFloat(jQuery.css(this.elem, this.prop, force));
+ return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
+ },
+
+ // Start an animation from one number to another
+ custom: function(from, to, unit){
+ this.startTime = now();
+ this.start = from;
+ this.end = to;
+ this.unit = unit || this.unit || "px";
+ this.now = this.start;
+ this.pos = this.state = 0;
+
+ var self = this;
+ function t(gotoEnd){
+ return self.step(gotoEnd);
+ }
+
+ t.elem = this.elem;
+
+ if ( t() && jQuery.timers.push(t) == 1 ) {
+ timerId = setInterval(function(){
+ var timers = jQuery.timers;
+
+ for ( var i = 0; i < timers.length; i++ )
+ if ( !timers[i]() )
+ timers.splice(i--, 1);
+
+ if ( !timers.length ) {
+ clearInterval( timerId );
+ }
+ }, 13);
+ }
+ },
+
+ // Simple 'show' function
+ show: function(){
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+ this.options.show = true;
+
+ // Begin the animation
+ // Make sure that we start at a small width/height to avoid any
+ // flash of content
+ this.custom(this.prop == "width" || this.prop == "height" ? 1 : 0, this.cur());
+
+ // Start by showing the element
+ jQuery(this.elem).show();
+ },
+
+ // Simple 'hide' function
+ hide: function(){
+ // Remember where we started, so that we can go back to it later
+ this.options.orig[this.prop] = jQuery.attr( this.elem.style, this.prop );
+ this.options.hide = true;
+
+ // Begin the animation
+ this.custom(this.cur(), 0);
+ },
+
+ // Each step of an animation
+ step: function(gotoEnd){
+ var t = now();
+
+ if ( gotoEnd || t >= this.options.duration + this.startTime ) {
+ this.now = this.end;
+ this.pos = this.state = 1;
+ this.update();
+
+ this.options.curAnim[ this.prop ] = true;
+
+ var done = true;
+ for ( var i in this.options.curAnim )
+ if ( this.options.curAnim[i] !== true )
+ done = false;
+
+ if ( done ) {
+ if ( this.options.display != null ) {
+ // Reset the overflow
+ this.elem.style.overflow = this.options.overflow;
+
+ // Reset the display
+ this.elem.style.display = this.options.display;
+ if ( jQuery.css(this.elem, "display") == "none" )
+ this.elem.style.display = "block";
+ }
+
+ // Hide the element if the "hide" operation was done
+ if ( this.options.hide )
+ jQuery(this.elem).hide();
+
+ // Reset the properties, if the item has been hidden or shown
+ if ( this.options.hide || this.options.show )
+ for ( var p in this.options.curAnim )
+ jQuery.attr(this.elem.style, p, this.options.orig[p]);
+
+ // Execute the complete function
+ this.options.complete.call( this.elem );
+ }
+
+ return false;
+ } else {
+ var n = t - this.startTime;
+ this.state = n / this.options.duration;
+
+ // Perform the easing function, defaults to swing
+ this.pos = jQuery.easing[this.options.easing || (jQuery.easing.swing ? "swing" : "linear")](this.state, n, 0, 1, this.options.duration);
+ this.now = this.start + ((this.end - this.start) * this.pos);
+
+ // Perform the next step of the animation
+ this.update();
+ }
+
+ return true;
+ }
+
+};
+
+jQuery.extend( jQuery.fx, {
+ speeds:{
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+ },
+ step: {
+
+ opacity: function(fx){
+ jQuery.attr(fx.elem.style, "opacity", fx.now);
+ },
+
+ _default: function(fx){
+ if ( fx.elem.style && fx.elem.style[ fx.prop ] != null )
+ fx.elem.style[ fx.prop ] = fx.now + fx.unit;
+ else
+ fx.elem[ fx.prop ] = fx.now;
+ }
+ }
+});
+if ( document.documentElement["getBoundingClientRect"] )
+ jQuery.fn.offset = function() {
+ if ( !this[0] ) return { top: 0, left: 0 };
+ if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
+ var box = this[0].getBoundingClientRect(), doc = this[0].ownerDocument, body = doc.body, docElem = doc.documentElement,
+ clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
+ top = box.top + (self.pageYOffset || jQuery.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
+ left = box.left + (self.pageXOffset || jQuery.boxModel && docElem.scrollLeft || body.scrollLeft) - clientLeft;
+ return { top: top, left: left };
+ };
+else
+ jQuery.fn.offset = function() {
+ if ( !this[0] ) return { top: 0, left: 0 };
+ if ( this[0] === this[0].ownerDocument.body ) return jQuery.offset.bodyOffset( this[0] );
+ jQuery.offset.initialized || jQuery.offset.initialize();
+
+ var elem = this[0], offsetParent = elem.offsetParent, prevOffsetParent = elem,
+ doc = elem.ownerDocument, computedStyle, docElem = doc.documentElement,
+ body = doc.body, defaultView = doc.defaultView,
+ prevComputedStyle = defaultView.getComputedStyle(elem, null),
+ top = elem.offsetTop, left = elem.offsetLeft;
+
+ while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
+ computedStyle = defaultView.getComputedStyle(elem, null);
+ top -= elem.scrollTop, left -= elem.scrollLeft;
+ if ( elem === offsetParent ) {
+ top += elem.offsetTop, left += elem.offsetLeft;
+ if ( jQuery.offset.doesNotAddBorder && !(jQuery.offset.doesAddBorderForTableAndCells && /^t(able|d|h)$/i.test(elem.tagName)) )
+ top += parseInt( computedStyle.borderTopWidth, 10) || 0,
+ left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
+ prevOffsetParent = offsetParent, offsetParent = elem.offsetParent;
+ }
+ if ( jQuery.offset.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" )
+ top += parseInt( computedStyle.borderTopWidth, 10) || 0,
+ left += parseInt( computedStyle.borderLeftWidth, 10) || 0;
+ prevComputedStyle = computedStyle;
+ }
+
+ if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" )
+ top += body.offsetTop,
+ left += body.offsetLeft;
+
+ if ( prevComputedStyle.position === "fixed" )
+ top += Math.max(docElem.scrollTop, body.scrollTop),
+ left += Math.max(docElem.scrollLeft, body.scrollLeft);
+
+ return { top: top, left: left };
+ };
+
+jQuery.offset = {
+ initialize: function() {
+ if ( this.initialized ) return;
+ var body = document.body, container = document.createElement('div'), innerDiv, checkDiv, table, td, rules, prop, bodyMarginTop = body.style.marginTop,
+ html = '<div style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;"><div></div></div><table style="position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;" cellpadding="0" cellspacing="0"><tr><td></td></tr></table>';
+
+ rules = { position: 'absolute', top: 0, left: 0, margin: 0, border: 0, width: '1px', height: '1px', visibility: 'hidden' };
+ for ( prop in rules ) container.style[prop] = rules[prop];
+
+ container.innerHTML = html;
+ body.insertBefore(container, body.firstChild);
+ innerDiv = container.firstChild, checkDiv = innerDiv.firstChild, td = innerDiv.nextSibling.firstChild.firstChild;
+
+ this.doesNotAddBorder = (checkDiv.offsetTop !== 5);
+ this.doesAddBorderForTableAndCells = (td.offsetTop === 5);
+
+ innerDiv.style.overflow = 'hidden', innerDiv.style.position = 'relative';
+ this.subtractsBorderForOverflowNotVisible = (checkDiv.offsetTop === -5);
+
+ body.style.marginTop = '1px';
+ this.doesNotIncludeMarginInBodyOffset = (body.offsetTop === 0);
+ body.style.marginTop = bodyMarginTop;
+
+ body.removeChild(container);
+ this.initialized = true;
+ },
+
+ bodyOffset: function(body) {
+ jQuery.offset.initialized || jQuery.offset.initialize();
+ var top = body.offsetTop, left = body.offsetLeft;
+ if ( jQuery.offset.doesNotIncludeMarginInBodyOffset )
+ top += parseInt( jQuery.curCSS(body, 'marginTop', true), 10 ) || 0,
+ left += parseInt( jQuery.curCSS(body, 'marginLeft', true), 10 ) || 0;
+ return { top: top, left: left };
+ }
+};
+
+
+jQuery.fn.extend({
+ position: function() {
+ var left = 0, top = 0, results;
+
+ if ( this[0] ) {
+ // Get *real* offsetParent
+ var offsetParent = this.offsetParent(),
+
+ // Get correct offsets
+ offset = this.offset(),
+ parentOffset = /^body|html$/i.test(offsetParent[0].tagName) ? { top: 0, left: 0 } : offsetParent.offset();
+
+ // Subtract element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ offset.top -= num( this, 'marginTop' );
+ offset.left -= num( this, 'marginLeft' );
+
+ // Add offsetParent borders
+ parentOffset.top += num( offsetParent, 'borderTopWidth' );
+ parentOffset.left += num( offsetParent, 'borderLeftWidth' );
+
+ // Subtract the two offsets
+ results = {
+ top: offset.top - parentOffset.top,
+ left: offset.left - parentOffset.left
+ };
+ }
+
+ return results;
+ },
+
+ offsetParent: function() {
+ var offsetParent = this[0].offsetParent || document.body;
+ while ( offsetParent && (!/^body|html$/i.test(offsetParent.tagName) && jQuery.css(offsetParent, 'position') == 'static') )
+ offsetParent = offsetParent.offsetParent;
+ return jQuery(offsetParent);
+ }
+});
+
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( ['Left', 'Top'], function(i, name) {
+ var method = 'scroll' + name;
+
+ jQuery.fn[ method ] = function(val) {
+ if (!this[0]) return null;
+
+ return val !== undefined ?
+
+ // Set the scroll offset
+ this.each(function() {
+ this == window || this == document ?
+ window.scrollTo(
+ !i ? val : jQuery(window).scrollLeft(),
+ i ? val : jQuery(window).scrollTop()
+ ) :
+ this[ method ] = val;
+ }) :
+
+ // Return the scroll offset
+ this[0] == window || this[0] == document ?
+ self[ i ? 'pageYOffset' : 'pageXOffset' ] ||
+ jQuery.boxModel && document.documentElement[ method ] ||
+ document.body[ method ] :
+ this[0][ method ];
+ };
+});
+// Create innerHeight, innerWidth, outerHeight and outerWidth methods
+jQuery.each([ "Height", "Width" ], function(i, name){
+
+ var tl = i ? "Left" : "Top", // top or left
+ br = i ? "Right" : "Bottom"; // bottom or right
+
+ // innerHeight and innerWidth
+ jQuery.fn["inner" + name] = function(){
+ return this[ name.toLowerCase() ]() +
+ num(this, "padding" + tl) +
+ num(this, "padding" + br);
+ };
+
+ // outerHeight and outerWidth
+ jQuery.fn["outer" + name] = function(margin) {
+ return this["inner" + name]() +
+ num(this, "border" + tl + "Width") +
+ num(this, "border" + br + "Width") +
+ (margin ?
+ num(this, "margin" + tl) + num(this, "margin" + br) : 0);
+ };
+
+ var type = name.toLowerCase();
+
+ jQuery.fn[ type ] = function( size ) {
+ // Get window width or height
+ return this[0] == window ?
+ // Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
+ document.compatMode == "CSS1Compat" && document.documentElement[ "client" + name ] ||
+ document.body[ "client" + name ] :
+
+ // Get document width or height
+ this[0] == document ?
+ // Either scroll[Width/Height] or offset[Width/Height], whichever is greater
+ Math.max(
+ document.documentElement["client" + name],
+ document.body["scroll" + name], document.documentElement["scroll" + name],
+ document.body["offset" + name], document.documentElement["offset" + name]
+ ) :
+
+ // Get or set width or height on the element
+ size === undefined ?
+ // Get width or height on the element
+ (this.length ? jQuery.css( this[0], type ) : null) :
+
+ // Set the width or height on the element (default to pixels if value is unitless)
+ this.css( type, typeof size === "string" ? size : size + "px" );
+ };
+
+});})();
diff --git a/js/main.js b/js/main.js
new file mode 100644
index 0000000..f7d93ce
--- /dev/null
+++ b/js/main.js
@@ -0,0 +1,256 @@
+$(document).ready(function(){
+
+ // Load Google Map
+ loadGMap();
+
+ // Setup for Google Map
+ $("body").bind("unload", GUnload);
+
+ // Get the groups
+ $.getJSON('json/groups.json', setGroups);
+
+});
+
+/*
+ After get the group data from server, add them to tab area.
+*/
+function setGroups(data){
+ // Remove the loading image
+ $('#tab_menu').empty();
+ // Add the groups
+ $.each(data, function(entryInx, entry){
+ var groupsHtml = '<span id="tab_';
+ groupsHtml += entry['id'];
+ groupsHtml += '"><img class="CameraIcon" src="';
+ groupsHtml += entry['image_url'];
+ groupsHtml += '"/>';
+ groupsHtml += entry['name'];
+ groupsHtml += '</span>';
+ $('#tab_menu').append(groupsHtml);
+ });
+
+ // Init the group tabs
+ initTabs();
+}
+
+/*
+ Init the group tabs.
+*/
+function initTabs(){
+ // Selet first group
+ $(".TabsArea .TabMenu span:first").addClass("selector");
+
+ //Set hover effect for the tabs
+ $(".TabsArea .TabMenu span").mouseover(function(){
+ $(this).addClass("hovering");
+ });
+ $(".TabsArea .TabMenu span").mouseout(function(){
+ $(this).removeClass("hovering");
+ });
+
+ //Add click action to tab menu
+ $(".TabsArea .TabMenu span").click(function(){
+ //Remove the exist selector
+ $(".selector").removeClass("selector");
+ //Add the selector class to the sender
+ $(this).addClass("selector");
+
+ // Get the spots and update the slider
+ $(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
+ $.getJSON("json/group"+this.id.substr(this.id.lastIndexOf("_")+1)+".json", setSpot);
+ });
+
+ // Init loading image for slider
+ $(".ScrollContainer").append('<img src="img/loading.gif" width="220" height="19"/>');
+
+ // Get First group of spots
+ $.getJSON("json/group1.json", setSpot);
+}
+
+/*
+ Set the spots to the slider.
+*/
+function setSpot(data){
+ // Remove the previous group of spots or the loading image
+ $('.ScrollContainer').empty();
+ // Add the spots
+ $.each(data, function(entryIdx, entry){
+ var spotHtml = '<div class="Panel" id="panel_';
+ spotHtml += (entryIdx+1);
+ spotHtml += '"><div class="inside"><img src="';
+ spotHtml += entry['image_url'];
+ spotHtml += '" alt="';
+ spotHtml += entry['description'];
+ spotHtml += '" /><span>';
+ spotHtml += entry['name'];
+ spotHtml += '</span></div></div>';
+ //alert(spotHtml);
+ $('.ScrollContainer').append(spotHtml);
+
+ // Set Lat & Lng info
+ $("#panel_"+(entryIdx+1)).data("lat",entry["latitude"]);
+ $("#panel_"+(entryIdx+1)).data("lng",entry["longitude"]);
+ $("#panel_"+(entryIdx+1)).data("zoom",entry["zoom"]);
+
+ });
+
+ // Init Slider
+ initSlider();
+}
+
+/*
+ Init Slider.
+*/
+function initSlider(){
+ // Caculte the total width of the slider
+ var $panels = $(".Panel");
+ var width = $panels[0].offsetWidth * $panels.length + 100;
+ // The first spot is in the middle at the begining
+ $(".ScrollContainer").css("width", width).css("left", "350px");
+ // The first spot will be bigger at first
+ makeBigger("#panel_1");
+ curPanel = 1;
+ updatePanelEventHandlers();
+ maxPanel = $panels.length;
+ $("#slider").data("currentlyMoving", false);
+
+ // Add event handler for navigate buttons
+ $(".right").click(function(){ navigate(true); });
+ $(".left").click(function(){ navigate(false); });
+
+ moveMap();
+}
+
+/*
+ Make the panel bigger.
+*/
+function makeBigger(element){
+ $(element).animate({ width: biggerWidth })
+ .find("img").animate({width: biggerImgWidth})
+ .end()
+ .find("span").animate({fontSize: biggerFontSize});
+}
+
+/*
+ Make the panel to normal size
+*/
+function makeNormal(element){
+ $(element).animate({ width: normalWidth })
+ .find("img").animate({width: normalImgWidth})
+ .end()
+ .find("span").animate({fontSize: normalFontSize});
+}
+
+/*
+ Navigate.
+*/
+function navigate(moving2left){
+
+ var steps = arguments[1]?arguments[1]:1;
+
+ // Invalid cases
+ if(moving2left && curPanel+steps-1>=maxPanel || !moving2left && curPanel-steps+1 <=1){
+ return false;
+ }
+
+ // If currently the slider is not moving
+ if(($("#slider").data("currentlyMoving") == false)){
+ $("#slider").data("currentlyMoving", true);
+
+ var nextPanel = moving2left?curPanel+steps:curPanel-steps;
+ var curPos = parseFloat($(".ScrollContainer").css("left"), 10);
+ var movement = moving2left?curPos-step*steps:curPos+step*steps;
+ // Move the panels
+ $(".ScrollContainer")
+ .stop()
+ .animate({"left": movement},
+ function() {
+ $("#slider").data("currentlyMoving", false);
+ moveMap();
+ });
+
+ // Make the previous panel to normal size
+ makeNormal("#panel_"+curPanel);
+ // Make current panel bigger
+ makeBigger("#panel_"+nextPanel);
+
+ curPanel = nextPanel;
+
+ updatePanelEventHandlers();
+
+ //moveMap();
+ }
+
+ return true;
+}
+
+/*
+ Bind click event for all the spots.
+*/
+function updatePanelEventHandlers(){
+ var $panels = $(".Panel");
+ $panels.unbind();
+ $panels.click(function(){
+ var inx = parseInt(this.id.substr(this.id.lastIndexOf("_")+1));
+ if(inx!=curPanel){
+ navigate(inx>curPanel?true:false, Math.abs(curPanel-inx));
+ }
+ });
+
+}
+
+/*
+ Load Google Map.
+*/
+function loadGMap(){
+ //alert("Load GMap");
+ map = new GMap2(document.getElementById("hk_map"));
+ //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
+ map.setCenter(new GLatLng(31.943327048210286, 118.78591775894165), 17);
+ map.setUIToDefault();
+}
+
+/*
+ Move Map.
+*/
+function moveMap(){
+ var $curPanel = $("#panel_"+curPanel);
+ var lat = $curPanel.data("lat");
+ var lng = $curPanel.data("lng");
+
+ if(lat == undefined || lat == null ||lat=="" || lng == undefined || lng == null || lng==""){
+ return false;
+ }
+
+ var zoom = $curPanel.data("zoom");
+ if(zoom == undefined || zoom == null || zoom <= 0){
+ zoom = 15;
+ }
+ //console.debug("lat="+lat+",lng="+lng+"zoom="+zoom);
+ if(map){
+ map.setZoom(parseInt(zoom));
+ map.panTo(new GLatLng(lat,lng));
+ }
+
+ return true;
+}
+
+// Constants for bigger panel
+var biggerWidth = "150px";
+var biggerImgWidth = "120px";
+var biggerFontSize = "14px";
+
+// Constants for normal panel
+var normalWidth = "130px";
+var normalImgWidth = "100px";
+var normalFontSize = "12px";
+
+// Moving step
+var step = 150;
+
+// Global Vars
+var curPanel = 0;
+var maxPanel = 0;
+
+// The map
+var map;
\ No newline at end of file
diff --git a/json/group1.json b/json/group1.json
new file mode 100644
index 0000000..c9461c2
--- /dev/null
+++ b/json/group1.json
@@ -0,0 +1,119 @@
+[
+ {
+ "id": "1",
+ "name": "ä¸å鍿±½è½¦ç«",
+ "image_url": "photo/dayone/zhm_bus_station.jpg",
+ "description": "ä¹åæºåºå¤§å·´",
+ "latitude": "32.00882197319293",
+ "longitude": "118.7757682800293",
+ "zoom": "15"
+ },
+ {
+ "id": "2",
+ "name": "ç¦å£æºåº",
+ "image_url": "photo/dayone/lk_airport.jpg",
+ "description": "å飿º",
+ "latitude": "31.78472759839612",
+ "longitude": "118.86876583099365",
+ "zoom": "15"
+ },
+ {
+ "id": "3",
+ "name": "广å·",
+ "image_url": "photo/dayone/guangzhou.jpg",
+ "description": "广å·",
+ "latitude": "23.385591961067536",
+ "longitude": "113.30517768859863",
+ "zoom": "15"
+ },
+ {
+ "id": "4",
+ "name": "éç´«è广åº",
+ "image_url": "photo/dayone/jzj_square.jpg",
+ "description": "éç´«è广åº",
+ "latitude": "22.2843412100226",
+ "longitude": "114.17347848415375",
+ "zoom": "17"
+ },
+ {
+ "id": "5",
+ "name": "ä¼å±ä¸å¿",
+ "image_url": "photo/dayone/meeting_center.jpg",
+ "description": "ä¼å±ä¸å¿",
+ "latitude": "22.28282725263975",
+ "longitude": "114.17293131351471",
+ "zoom": "17"
+ },
+ {
+ "id": "6",
+ "name": "ç«æ³ä¼å¤§æ¥¼",
+ "image_url": "photo/dayone/law.jpg",
+ "description": "ç«æ³ä¼å¤§æ¥¼",
+ "latitude": "22.28107997652926",
+ "longitude": "114.16016399860382",
+ "zoom": "17"
+ },
+ {
+ "id": "7",
+ "name": "ä¸å½é¶è¡",
+ "image_url": "photo/dayone/cob.jpg",
+ "description": "ä¸å½é¶è¡",
+ "latitude": "22.280380067189995",
+ "longitude": "114.16034370660782",
+ "zoom": "17"
+ },
+ {
+ "id": "8",
+ "name": "礼宾åºç¹åº",
+ "image_url": "photo/dayone/libinfu.jpg",
+ "description": "礼宾åºç¹åº",
+ "latitude": "22.27875934169057",
+ "longitude": "114.15763199329376",
+ "zoom": "18"
+ },
+ {
+ "id": "9",
+ "name": "æ¿åºæ»é¨",
+ "image_url": "photo/dayone/gov.jpg",
+ "description": "æ¿åºæ»é¨",
+ "latitude": "22.27888592276567",
+ "longitude": "114.15872633457184",
+ "zoom": "17"
+ },
+ {
+ "id": "10",
+ "name": "æµ·æ´å
Œ",
+ "image_url": "photo/dayone/sea_park.jpg",
+ "description": "æµ·æ´å
Œ",
+ "latitude": "22.24527090215842",
+ "longitude": "114.17679369449615",
+ "zoom": "17"
+ },
+ {
+ "id": "11",
+ "name": "æµ
æ°´æ¹¾",
+ "image_url": "photo/dayone/repulse_bay.jpg",
+ "description": "æµ
æ°´æ¹¾",
+ "latitude": "22.237589598654903",
+ "longitude": "114.19914722442627",
+ "zoom": "17"
+ },
+ {
+ "id": "12",
+ "name": "太平山",
+ "image_url": "photo/dayone/taiping.jpg",
+ "description": "太平山",
+ "latitude": "22.27039232678379",
+ "longitude": "114.15189743041992",
+ "zoom": "17"
+ },
+ {
+ "id": "13",
+ "name": "宾é¦",
+ "image_url": "photo/dayone/hotel.jpg",
+ "description": "宾é¦",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ }
+]
\ No newline at end of file
diff --git a/json/group2.json b/json/group2.json
new file mode 100644
index 0000000..8642c85
--- /dev/null
+++ b/json/group2.json
@@ -0,0 +1,101 @@
+[
+ {
+ "id": "14",
+ "name": "é»å¤§ä»åº",
+ "image_url": "photo/daytwo/hdx.jpg",
+ "description": "é»å¤§ä»åº",
+ "latitude": "22.343268556904317",
+ "longitude": "114.19339656829834",
+ "zoom": "15"
+ },
+ {
+ "id": "15",
+ "name": "ç å®å±ç¤ºä¸å¿",
+ "image_url": "photo/daytwo/jewelry.jpg",
+ "description": "ç å®å±ç¤ºä¸å¿",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "16",
+ "name": "ç¾è´§åº",
+ "image_url": "photo/daytwo/store.jpg",
+ "description": "ç¾è´§åº",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "17",
+ "name": "åé¤",
+ "image_url": "photo/daytwo/lunch.jpg",
+ "description": "åé¤",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "18",
+ "name": "DFS",
+ "image_url": "photo/daytwo/dfs.jpg",
+ "description": "DFS",
+ "latitude": "22.29681708367642",
+ "longitude": "114.16930228471756",
+ "zoom": "18"
+ },
+ {
+ "id": "19",
+ "name": "æå
大é",
+ "image_url": "photo/daytwo/start.jpg",
+ "description": "æå
大é",
+ "latitude": "22.293960661077",
+ "longitude": "114.17190670967102",
+ "zoom": "18"
+ },
+ {
+ "id": "20",
+ "name": "å°æ²åæåä¸å¿",
+ "image_url": "photo/daytwo/jsz.jpg",
+ "description": "å°æ²åæåä¸å¿",
+ "latitude": "22.29335015831739",
+ "longitude": "114.16998624801636",
+ "zoom": "17"
+ },
+ {
+ "id": "21",
+ "name": "大鿥¼",
+ "image_url": "photo/daytwo/tower.jpg",
+ "description": "大鿥¼",
+ "latitude": "22.2933997927877",
+ "longitude": "114.16951149702072",
+ "zoom": "18"
+ },
+ {
+ "id": "22",
+ "name": "æµ·é²å¤§é¤",
+ "image_url": "photo/daytwo/sea_food.jpg",
+ "description": "æµ·é²å¤§é¤",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "23",
+ "name": "ç»´å¤å©äºæ¸¯",
+ "image_url": "photo/daytwo/victoria.jpg",
+ "description": "ç»´å¤å©äºæ¸¯",
+ "latitude": "22.29529085297506",
+ "longitude": "114.16202545166016",
+ "zoom": "13"
+ },
+ {
+ "id": "25",
+ "name": "宾é¦2",
+ "image_url": "photo/daytwo/hotel.jpg",
+ "description": "宾é¦2",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ }
+]
\ No newline at end of file
diff --git a/json/group3.json b/json/group3.json
new file mode 100644
index 0000000..254fb8b
--- /dev/null
+++ b/json/group3.json
@@ -0,0 +1,11 @@
+[
+ {
+ "id": "26",
+ "name": "迪æ¯å°¼",
+ "image_url": "photo/daythree/disney.jpg",
+ "description": "迪æ¯å°¼",
+ "latitude": "22.313743477218047",
+ "longitude": "114.0411114692688",
+ "zoom": "16"
+ }
+]
\ No newline at end of file
diff --git a/json/group4.json b/json/group4.json
new file mode 100644
index 0000000..3410e1a
--- /dev/null
+++ b/json/group4.json
@@ -0,0 +1,92 @@
+[
+ {
+ "id": "27",
+ "name": "大ä¸å·´çå",
+ "image_url": "photo/dayfour/dsb.jpg",
+ "description": "大ä¸å·´çå",
+ "latitude": "22.197420997723434",
+ "longitude": "113.54090631008148",
+ "zoom": "18"
+ },
+ {
+ "id": "28",
+ "name": "å¦éåº",
+ "image_url": "photo/dayfour/mgm.jpg",
+ "description": "å¦éåº",
+ "latitude": "22.18748446661309",
+ "longitude": "113.5330581665039",
+ "zoom": "15"
+ },
+ {
+ "id": "29",
+ "name": "è§é³å",
+ "image_url": "photo/dayfour/gyx.jpg",
+ "description": "è§é³å",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "30",
+ "name": "主æå±±",
+ "image_url": "photo/dayfour/zjs.jpg",
+ "description": "主æå±±",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "31",
+ "name": "è²è±å¹¿åº",
+ "image_url": "photo/dayfour/lotus.jpg",
+ "description": "è²è±å¹¿åº",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "32",
+ "name": "åé¤4",
+ "image_url": "photo/dayfour/lunch.jpg",
+ "description": "åé¤4",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "33",
+ "name": "ç¯å²æ¸¸",
+ "image_url": "photo/dayfour/round.jpg",
+ "description": "ç¯å²æ¸¸",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "34",
+ "name": "éè´æ¾³é¨æä¿¡ç¤¼å",
+ "image_url": "photo/dayfour/sx.jpg",
+ "description": "éè´æ¾³é¨æä¿¡ç¤¼å",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "35",
+ "name": "娱ä¹åº",
+ "image_url": "photo/dayfour/entertain.jpg",
+ "description": "娱ä¹åº",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "36",
+ "name": "宾é¦4",
+ "image_url": "photo/dayfour/hotel.jpg",
+ "description": "宾é¦4",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ }
+]
\ No newline at end of file
diff --git a/json/group5.json b/json/group5.json
new file mode 100644
index 0000000..90c6d2b
--- /dev/null
+++ b/json/group5.json
@@ -0,0 +1,56 @@
+[
+ {
+ "id": "43",
+ "name": "æ±åå
³",
+ "image_url": "photo/dayfive/gbg.jpg",
+ "description": "æ±åå
³",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "44",
+ "name": "æ
侣路",
+ "image_url": "photo/dayfive/lover.jpg",
+ "description": "æ
侣路",
+ "latitude": "22.26129750157242",
+ "longitude": "113.5856294631958",
+ "zoom": "14"
+ },
+ {
+ "id": "45",
+ "name": "æ¸å¥³å",
+ "image_url": "photo/dayfive/fisher.jpg",
+ "description": "æ¸å¥³å",
+ "latitude": "22.261793959247537",
+ "longitude": "113.58962059020996",
+ "zoom": "15"
+ },
+ {
+ "id": "46",
+ "name": "åé¤5",
+ "image_url": "photo/dayfive/lunch.jpg",
+ "description": "åé¤5",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "47",
+ "name": "ç¾è´§åº5",
+ "image_url": "photo/dayfive/store.jpg",
+ "description": "ç¾è´§åº5",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ },
+ {
+ "id": "48",
+ "name": "å¹¿å·æºåº",
+ "image_url": "photo/dayfive/gz_airport.jpg",
+ "description": "å¹¿å·æºåº",
+ "latitude": "",
+ "longitude": "",
+ "zoom": ""
+ }
+]
\ No newline at end of file
diff --git a/json/groups.json b/json/groups.json
new file mode 100644
index 0000000..8d475ed
--- /dev/null
+++ b/json/groups.json
@@ -0,0 +1,27 @@
+[
+ {
+ "id": "1",
+ "name": "第ä¸å¤©",
+ "image_url": "img/camera/camera_1.png"
+ },
+ {
+ "id": "2",
+ "name": "第äºå¤©",
+ "image_url": "img/camera/camera_2.png"
+ },
+ {
+ "id": "3",
+ "name": "第ä¸å¤©",
+ "image_url": "img/camera/camera_3.png"
+ },
+ {
+ "id": "4",
+ "name": "第å天",
+ "image_url": "img/camera/camera_4.png"
+ },
+ {
+ "id": "5",
+ "name": "第äºå¤©",
+ "image_url": "img/camera/camera_5.png"
+ }
+]
\ No newline at end of file
diff --git a/photo/dayfive/Thumbs.db b/photo/dayfive/Thumbs.db
new file mode 100644
index 0000000..9fed34b
Binary files /dev/null and b/photo/dayfive/Thumbs.db differ
diff --git a/photo/dayfive/fisher.jpg b/photo/dayfive/fisher.jpg
new file mode 100644
index 0000000..6524901
Binary files /dev/null and b/photo/dayfive/fisher.jpg differ
diff --git a/photo/dayfive/gbg.jpg b/photo/dayfive/gbg.jpg
new file mode 100644
index 0000000..d9d7e18
Binary files /dev/null and b/photo/dayfive/gbg.jpg differ
diff --git a/photo/dayfive/gz_airport.jpg b/photo/dayfive/gz_airport.jpg
new file mode 100644
index 0000000..2c5ecf9
Binary files /dev/null and b/photo/dayfive/gz_airport.jpg differ
diff --git a/photo/dayfive/lover.jpg b/photo/dayfive/lover.jpg
new file mode 100644
index 0000000..beb5f3e
Binary files /dev/null and b/photo/dayfive/lover.jpg differ
diff --git a/photo/dayfive/lunch.jpg b/photo/dayfive/lunch.jpg
new file mode 100644
index 0000000..afec5b0
Binary files /dev/null and b/photo/dayfive/lunch.jpg differ
diff --git a/photo/dayfive/store.jpg b/photo/dayfive/store.jpg
new file mode 100644
index 0000000..d11cae4
Binary files /dev/null and b/photo/dayfive/store.jpg differ
diff --git a/photo/dayfour/Thumbs.db b/photo/dayfour/Thumbs.db
new file mode 100644
index 0000000..483b8d5
Binary files /dev/null and b/photo/dayfour/Thumbs.db differ
diff --git a/photo/dayfour/dsb.jpg b/photo/dayfour/dsb.jpg
new file mode 100644
index 0000000..0c1a293
Binary files /dev/null and b/photo/dayfour/dsb.jpg differ
diff --git a/photo/dayfour/entertain.jpg b/photo/dayfour/entertain.jpg
new file mode 100644
index 0000000..ec0ce4a
Binary files /dev/null and b/photo/dayfour/entertain.jpg differ
diff --git a/photo/dayfour/gyx.jpg b/photo/dayfour/gyx.jpg
new file mode 100644
index 0000000..d96c96f
Binary files /dev/null and b/photo/dayfour/gyx.jpg differ
diff --git a/photo/dayfour/hotel.jpg b/photo/dayfour/hotel.jpg
new file mode 100644
index 0000000..77828d1
Binary files /dev/null and b/photo/dayfour/hotel.jpg differ
diff --git a/photo/dayfour/lotus.jpg b/photo/dayfour/lotus.jpg
new file mode 100644
index 0000000..fa6c519
Binary files /dev/null and b/photo/dayfour/lotus.jpg differ
diff --git a/photo/dayfour/lunch.jpg b/photo/dayfour/lunch.jpg
new file mode 100644
index 0000000..412555e
Binary files /dev/null and b/photo/dayfour/lunch.jpg differ
diff --git a/photo/dayfour/mgm.jpg b/photo/dayfour/mgm.jpg
new file mode 100644
index 0000000..3b1494d
Binary files /dev/null and b/photo/dayfour/mgm.jpg differ
diff --git a/photo/dayfour/round.jpg b/photo/dayfour/round.jpg
new file mode 100644
index 0000000..be2dd5c
Binary files /dev/null and b/photo/dayfour/round.jpg differ
diff --git a/photo/dayfour/sx.jpg b/photo/dayfour/sx.jpg
new file mode 100644
index 0000000..f8ef6b4
Binary files /dev/null and b/photo/dayfour/sx.jpg differ
diff --git a/photo/dayfour/zjs.jpg b/photo/dayfour/zjs.jpg
new file mode 100644
index 0000000..619cff3
Binary files /dev/null and b/photo/dayfour/zjs.jpg differ
diff --git a/photo/dayone/Thumbs.db b/photo/dayone/Thumbs.db
new file mode 100644
index 0000000..1252393
Binary files /dev/null and b/photo/dayone/Thumbs.db differ
diff --git a/photo/dayone/cob.jpg b/photo/dayone/cob.jpg
new file mode 100644
index 0000000..65a0587
Binary files /dev/null and b/photo/dayone/cob.jpg differ
diff --git a/photo/dayone/gov.jpg b/photo/dayone/gov.jpg
new file mode 100644
index 0000000..8fbec99
Binary files /dev/null and b/photo/dayone/gov.jpg differ
diff --git a/photo/dayone/guangzhou.jpg b/photo/dayone/guangzhou.jpg
new file mode 100644
index 0000000..0214dca
Binary files /dev/null and b/photo/dayone/guangzhou.jpg differ
diff --git a/photo/dayone/hotel.jpg b/photo/dayone/hotel.jpg
new file mode 100644
index 0000000..7a1294c
Binary files /dev/null and b/photo/dayone/hotel.jpg differ
diff --git a/photo/dayone/jzj_square.jpg b/photo/dayone/jzj_square.jpg
new file mode 100644
index 0000000..0214dca
Binary files /dev/null and b/photo/dayone/jzj_square.jpg differ
diff --git a/photo/dayone/law.jpg b/photo/dayone/law.jpg
new file mode 100644
index 0000000..12fa849
Binary files /dev/null and b/photo/dayone/law.jpg differ
diff --git a/photo/dayone/libinfu.jpg b/photo/dayone/libinfu.jpg
new file mode 100644
index 0000000..8f2238d
Binary files /dev/null and b/photo/dayone/libinfu.jpg differ
diff --git a/photo/dayone/lk_airport.jpg b/photo/dayone/lk_airport.jpg
new file mode 100644
index 0000000..0214dca
Binary files /dev/null and b/photo/dayone/lk_airport.jpg differ
diff --git a/photo/dayone/meeting_center.jpg b/photo/dayone/meeting_center.jpg
new file mode 100644
index 0000000..0214dca
Binary files /dev/null and b/photo/dayone/meeting_center.jpg differ
diff --git a/photo/dayone/repulse_bay.jpg b/photo/dayone/repulse_bay.jpg
new file mode 100644
index 0000000..1045bde
Binary files /dev/null and b/photo/dayone/repulse_bay.jpg differ
diff --git a/photo/dayone/sea_park.jpg b/photo/dayone/sea_park.jpg
new file mode 100644
index 0000000..9d411b2
Binary files /dev/null and b/photo/dayone/sea_park.jpg differ
diff --git a/photo/dayone/taiping.jpg b/photo/dayone/taiping.jpg
new file mode 100644
index 0000000..4a5c7fb
Binary files /dev/null and b/photo/dayone/taiping.jpg differ
diff --git a/photo/dayone/zhm_bus_station.jpg b/photo/dayone/zhm_bus_station.jpg
new file mode 100644
index 0000000..3cea46d
Binary files /dev/null and b/photo/dayone/zhm_bus_station.jpg differ
diff --git a/photo/daythree/Thumbs.db b/photo/daythree/Thumbs.db
new file mode 100644
index 0000000..6158d83
Binary files /dev/null and b/photo/daythree/Thumbs.db differ
diff --git a/photo/daythree/disney.jpg b/photo/daythree/disney.jpg
new file mode 100644
index 0000000..c84fd9b
Binary files /dev/null and b/photo/daythree/disney.jpg differ
diff --git a/photo/daytwo/Thumbs.db b/photo/daytwo/Thumbs.db
new file mode 100644
index 0000000..897b0b5
Binary files /dev/null and b/photo/daytwo/Thumbs.db differ
diff --git a/photo/daytwo/dfs.jpg b/photo/daytwo/dfs.jpg
new file mode 100644
index 0000000..90149b1
Binary files /dev/null and b/photo/daytwo/dfs.jpg differ
diff --git a/photo/daytwo/hdx.jpg b/photo/daytwo/hdx.jpg
new file mode 100644
index 0000000..7cf62cc
Binary files /dev/null and b/photo/daytwo/hdx.jpg differ
diff --git a/photo/daytwo/hotel.jpg b/photo/daytwo/hotel.jpg
new file mode 100644
index 0000000..77828d1
Binary files /dev/null and b/photo/daytwo/hotel.jpg differ
diff --git a/photo/daytwo/jewelry.jpg b/photo/daytwo/jewelry.jpg
new file mode 100644
index 0000000..222aed4
Binary files /dev/null and b/photo/daytwo/jewelry.jpg differ
diff --git a/photo/daytwo/jsz.jpg b/photo/daytwo/jsz.jpg
new file mode 100644
index 0000000..af84421
Binary files /dev/null and b/photo/daytwo/jsz.jpg differ
diff --git a/photo/daytwo/lunch.jpg b/photo/daytwo/lunch.jpg
new file mode 100644
index 0000000..4ba6e1e
Binary files /dev/null and b/photo/daytwo/lunch.jpg differ
diff --git a/photo/daytwo/sea_food.jpg b/photo/daytwo/sea_food.jpg
new file mode 100644
index 0000000..ec7dbdc
Binary files /dev/null and b/photo/daytwo/sea_food.jpg differ
diff --git a/photo/daytwo/start.jpg b/photo/daytwo/start.jpg
new file mode 100644
index 0000000..9f6f205
Binary files /dev/null and b/photo/daytwo/start.jpg differ
diff --git a/photo/daytwo/store.jpg b/photo/daytwo/store.jpg
new file mode 100644
index 0000000..573c78e
Binary files /dev/null and b/photo/daytwo/store.jpg differ
diff --git a/photo/daytwo/tower.jpg b/photo/daytwo/tower.jpg
new file mode 100644
index 0000000..5fdade4
Binary files /dev/null and b/photo/daytwo/tower.jpg differ
diff --git a/photo/daytwo/victoria.jpg b/photo/daytwo/victoria.jpg
new file mode 100644
index 0000000..523ae5a
Binary files /dev/null and b/photo/daytwo/victoria.jpg differ
|
viirya/image-quantization-server
|
c2b8ed93ece79d9eeebc90f84d6eccd49d53f029
|
modified web interface to add cbir service query.
|
diff --git a/src/main/web/inc/xml_parser.inc b/src/main/web/inc/xml_parser.inc
new file mode 100644
index 0000000..5a3a454
--- /dev/null
+++ b/src/main/web/inc/xml_parser.inc
@@ -0,0 +1,119 @@
+<?php
+//phpinfo();
+
+//xxxsample();
+
+function xxxsample() {
+
+ $xmlstg =<<<EOF
+<?xml version="1.0" encoding="UTF-8"?>
+<config>
+<filetype>xls</filetype>
+</config>
+EOF;
+
+ $parser = new xml_parser();
+ $ret = $parser->parse($xmlstg);
+ print_r($ret);
+
+ echo "encoding: ".$parser->get_encoding()."\n";
+
+}
+
+class xml_parser {
+
+ var $dom;
+ var $root;
+ var $ret;
+ var $encoding;
+
+ function convert_attrs($att) {
+
+ $ret = array();
+
+ foreach($att as $i)
+ $ret[$i->name] = $i->value;
+
+ return $ret;
+
+ }
+ function parse_node($node) {
+ $ret = '';
+ $node_name = $node->nodeName;
+ if ($node->hasChildNodes()) {
+ foreach($node->childNodes as $n) {
+ if ($n->nodeName == '#text' || $n->nodeName == '#cdata-section') {
+ if (!is_array($ret)) {
+ $ret = $n->nodeValue;
+ }
+ $node_value = $n->nodeValue;
+ }
+ else {
+ if (isset($ret) && !is_array($ret))
+ $ret = array();
+ $tmp = $this->parse_node($n);
+ $attrs = $n->attributes;
+ //if (is_array($attrs) && !empty($attrs)) {
+ if ($attrs != NULL) {
+ $attrs = $this->convert_attrs($attrs);
+ if (!empty($attrs)) {
+ $tmp2 = $tmp;
+ $tmp = array();
+ $tmp['value'] = $tmp2;
+ $tmp['_attrs'] = $attrs;
+ }
+ }
+ if (!isset($ret[$n->nodeName])) {
+ $ret[$n->nodeName] = $tmp;
+ }
+ else {
+ if (is_array($ret[$n->nodeName]) && !isset($ret[$n->nodeName][0])) {
+ $switch = $ret[$n->nodeName];
+ $ret[$n->nodeName] = array();
+ $ret[$n->nodeName][0] = $switch;
+ }
+ else if (!is_array($ret[$n->nodeName]) && isset($ret[$n->nodeName])) {
+ $switch = $ret[$n->nodeName];
+ $ret[$n->nodeName] = array();
+ $ret[$n->nodeName][0] = $switch;
+ }
+ $ret[$n->nodeName][] = $tmp;
+ }
+ }
+ }
+ }
+ return $ret;
+ }
+
+ function parse($xml) {
+
+ //$this->dom = domxml_open_mem($xml, DOMXML_LOAD_RECOVERING);
+ $this->dom = new DOMDocument();
+ $this->dom->loadXML($xml);
+ $this->ret = array();
+
+ if (!isset($this->dom) || $this->dom == false)
+ return $this->ret;
+
+ //$this->root = $this->dom->document_element();
+ $this->root = $this->dom->documentElement;
+ $this->ret[$this->root->nodeName] = $this->parse_node($this->root);
+
+ $this->encoding = '';
+ $matches = array();
+ if (preg_match('/<\?xml.*encoding="(.*?)"\?>/', $xml, $matches))
+ $this->encoding = $matches[1];
+
+
+ return $this->ret;
+ }
+
+ function get_encoding() {
+ return $this->encoding;
+ }
+
+
+}
+
+?>
+
diff --git a/src/main/web/query.php b/src/main/web/query.php
index 90a6216..2773f6f 100644
--- a/src/main/web/query.php
+++ b/src/main/web/query.php
@@ -1,65 +1,111 @@
<?php
include_once("inc/cbir.inc");
+include_once("inc/xml_parser.inc");
$filename = get_convert_upload_image();
extract_features($filename);
$quantized_ret = quantize($filename);
+$retrieved_ret = image_retrieval($quantized_ret, 100);
+display_image($retrieved_ret);
+print_r($retrieved_ret);
+
+
+function display_image($images) {
+
+ $base_url = "/~itv/thumbnails/";
+
+ $image_urls = array();
+
+ foreach ($images['results']['image'] as $image) {
+ $image_id = $image['id'];
+ $image_url = $base_url . $image_id . '_t.jpg';
+ $image_urls[] = $image_url;
+ }
+
+ foreach ($image_urls as $image_url) {
+ print "<img width=\"100\" height=\"100\" src=\"$image_url\" />";
+ }
+
+}
+
+function image_retrieval($features, $max = 100) {
+
+ $ret = '';
+
+ $query_args = array(
+ "url" => "http://cml10.csie.ntu.edu.tw:5000/",
+ "post" => true,
+ "params" => array(
+ "feature" => $features,
+ "max" => $max
+ )
+ );
+
+
+ $xml_ret = query_cbir_service($query_args);
+ if (!empty($xml_ret)) {
+ $parser = new xml_parser();
+ $ret = $parser->parse($xml_ret);
+ }
+
+ return $ret;
+}
function quantize($filename) {
$features = implode('', file($filename . '.hes'));
$query_args = array(
"url" => "http://cml11.csie.ntu.edu.tw:5001/",
"post" => true,
"params" => array(
"feature" => $features
)
);
$quantized_ret = query_cbir_service($query_args);
- print_r($quantized_ret);
+ #print_r($quantized_ret);
return $quantized_ret;
}
function get_convert_upload_image() {
$query_file = '';
if ($_FILES["userfile"]["size"] != 0) {
$query_file = $_FILES["userfile"]["tmp_name"];
$tmp = explode( '/', $query_file );
move_uploaded_file($query_file, 'upload/' . $tmp[count($tmp) - 1]);
$query_file = 'upload/' . $tmp[count($tmp) - 1];
}
$queryimage_size = getimagesize($query_file);
if ($queryimage_size[0] * $queryimage_size[1] > 360000 ) {
$ratio = sqrt( 360000 / ($queryimage_size[0] * $queryimage_size[1]) );
$scaled_width = $queryimage_size[0] * $ratio;
$scaled_height = $queryimage_size[1] * $ratio;
exec('convert -resize ' . $scaled_width . 'x' . $scaled_height . ' ' . $query_file . $query_file);
}
$query_filename = explode(".", $query_file);
if (count($query_filename) >= 2)
unset($query_filename[count($query_filename) - 1]);
$pgm_file = join(".", $query_filename);
$convert_pgm = 'convert ' . $query_file . ' ' . $pgm_file . '.pgm';
$ret = shell_exec($convert_pgm);
return $pgm_file;
}
function extract_features($filename) {
exec('./bin/extract_features_64bit.ln -hesaff -sift -i ' . $filename . '.pgm -o1 ' . $filename . '.hes');
}
?>
|
viirya/image-quantization-server
|
62ef38354ad253de9730eb8a1f1b2be82af5cf02
|
skiped more 1 float value in extracted features.
|
diff --git a/src/main/scala/quantizer.scala b/src/main/scala/quantizer.scala
index aa64129..2e90893 100644
--- a/src/main/scala/quantizer.scala
+++ b/src/main/scala/quantizer.scala
@@ -1,330 +1,329 @@
package org.viirya.quantizer
import scala.io.Source
import scala.actors.Actor
import scala.actors.Actor._
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.HttpConnection;
import org.mortbay.jetty.Request;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.AbstractHandler;
case class MTree(id: Int, value: Array[Float], var children: List[MTree]) {
def this(id: Int, value: Array[Float]) = this(id, value, List())
def isLeaf(): Boolean = {
if (children.length == 0)
true
else
false
}
def calculateDistance(vector: Array[Float]): Float = {
var distance: Float = 0.0f
for (i <- 0.to(value.length - 1)) {
distance = distance + Math.pow(value(i) - vector(i), 2).toFloat
}
distance
}
def findClosetNode(vector: Array[Float]): MTree = {
var minDistance = Math.MAX_FLOAT
var closetNode: MTree = null
children.foreach { child_node =>
var distance = child_node.calculateDistance(vector)
if (distance < minDistance) {
minDistance = distance
closetNode = child_node
}
}
closetNode
}
override def toString = "M(" + value.toString + " {" + children.map(_.toString).mkString(",") + "})"
}
/*
object MTree {
def apply[T](id: Int, value: Array[T]) = new MTree(id, value, List())
def apply[T](id: Int, value: Array[T], children: List[MTree[T]]) = new MTree(id, value, children)
}
*/
class TreeDataLoader(filepath: String) {
var line_counter = 0
var tree_degree_per_node = 0
var tree_height = 0
var num_all_tree_nodes = 0
var num_not_leaf_nodes = 0
var feature_dimension = 128
var tree: List[MTree] = List()
var root = new MTree(0, new Array[Float](128))
tree = tree ::: List(root)
var current_pos_in_tree = 0
var current_parent_node_in_tree = 0
Source.fromFile(filepath)
.getLines
.foreach { read_line =>
var line = read_line.stripLineEnd
var split_line: List[String] = List.fromString(line, ' ')
line_counter match {
case 0 =>
try {
tree_degree_per_node = split_line(0).toInt
tree_height = split_line(1).toInt
num_all_tree_nodes = ((Math.pow(tree_degree_per_node, tree_height + 1) - 1) / (tree_degree_per_node - 1)).toInt - 1
num_not_leaf_nodes = num_all_tree_nodes - Math.pow(tree_degree_per_node, tree_height).toInt
} catch {
case _: java.lang.NumberFormatException => println("Error file format.")
}
case t =>
var node_value: Array[Float] = split_line.map( (s) => s.toFloat ).toArray
var new_node: MTree = null
if (line_counter <= num_not_leaf_nodes)
new_node = new MTree(-line_counter, node_value)
else
new_node = new MTree(line_counter - num_not_leaf_nodes, node_value)
tree(current_parent_node_in_tree).children = tree(current_parent_node_in_tree).children ::: List(new_node)
tree = tree ::: List(new_node)
current_pos_in_tree = current_pos_in_tree + 1
if (line_counter % tree_degree_per_node == 0) {
current_parent_node_in_tree = current_parent_node_in_tree + 1
//println("current parent: " + current_parent_node_in_tree + " line: " + line_counter)
}
-
//println(tree(current_parent_node_in_tree))
}
if (line_counter % 100 == 0)
println("Processing line " + line_counter)
line_counter += 1
}
}
object MetaDataLoader {
var mean_values: Array[Float] = null
var std_values: Array[Float] = null
def load(filepath: String) = {
var line_counter = 0
Source.fromFile(filepath)
.getLines
.foreach { read_line =>
var line = read_line.stripLineEnd
var split_line: List[String] = List.fromString(line, ' ')
line_counter match {
case 0 => mean_values = split_line.map( (s) => s.toFloat ).toArray
case 1 => std_values = split_line.map( (s) => s.toFloat ).toArray
case _ =>
}
line_counter = line_counter + 1
}
}
}
class Query(var values: List[Array[Float]]) {
var feature_dimension = 128
var num_features = 0
var line_counter = 0
def this() = this(List())
def parse(read_line: String) = {
var line = read_line.stripLineEnd
var split_line: List[String] = List.fromString(line, ' ')
line_counter match {
case 0 => feature_dimension = split_line(0).toInt
case 1 => num_features = split_line(0).toInt
case _ =>
- var features: Array[Float] = split_line.drop(4).map( (s) => s.toFloat ).toArray
+ var features: Array[Float] = split_line.drop(5).map( (s) => s.toFloat ).toArray
var normalized_features: Array[Float] = new Array[Float](features.length)
var dimension = 0
features.foreach { feature =>
normalized_features(dimension) = (feature - MetaDataLoader.mean_values(dimension)) / MetaDataLoader.std_values(dimension)
dimension = dimension + 1
}
values = values ::: List(normalized_features)
}
println("line " + line_counter + " loaded.")
line_counter = line_counter + 1
}
def loadFromString(data: String) = {
num_features = 0
line_counter = 0
values = List()
List.fromString(data, '\n').foreach( parse(_) )
}
def loadFromFile(filepath: String) = {
num_features = 0
line_counter = 0
values = List()
Source.fromFile(filepath)
.getLines
.foreach( parse(_) )
/*
read_line =>
var line = read_line.stripLineEnd
var split_line: List[String] = List.fromString(line, ' ')
line_counter match {
case 0 => feature_dimension = split_line(0).toInt
case 1 => num_features = split_line(0).toInt
case _ =>
var feature: Array[Float] = split_line.map( (s) => s.toFloat ).toArray
values = feature :: values
}
println("line " + line_counter + " loaded.")
line_counter = line_counter + 1
}
*/
}
}
abstract class cService {
def run()
}
class HttpService(val port: Int, val tree: MTree) extends cService {
class ServiceHandler extends AbstractHandler {
def handle(target: String, request: HttpServletRequest, response: HttpServletResponse, dispatch: Int) = {
var base_request: Request = null
if (request.isInstanceOf[Request])
base_request = request.asInstanceOf[Request]
else
base_request = HttpConnection.getCurrentConnection().getRequest()
val feature_filename: String = base_request.getParameter("filename")
val feature: String = base_request.getParameter("feature")
var query: Query = new Query()
var quantized_ret: String = ""
if (feature_filename != null) {
println("To quantize features in " + feature_filename)
query.loadFromFile(feature_filename)
quantized_ret = Quantizer.quantize(query, tree)
} else if (feature != null) {
println("To quantize features.....")
query.loadFromString(feature)
quantized_ret = Quantizer.quantize(query, tree)
}
println(quantized_ret)
base_request.setHandled(true)
response.setContentType("text/plain")
response.setStatus(HttpServletResponse.SC_OK)
response.getWriter().println(quantized_ret)
}
}
def run() = {
println("Service started.....")
val server: Server = new Server()
val connector: Connector = new SocketConnector()
connector.setPort(port)
server.setConnectors(Array(connector))
val handler: Handler = new ServiceHandler()
server.setHandler(handler)
server.start()
server.join()
}
}
class ServiceRunner extends Actor {
def act() = {
loop {
react {
case s: cService => println("Starting service....."); s.run()
}
}
}
}
object Quantizer {
def quantize(query: Query, tree: MTree): String = {
var quantized_result: String = ""
for (feature_point <- query.values) {
var trace_tree = tree
while (!trace_tree.isLeaf()) {
trace_tree = trace_tree.findClosetNode(feature_point)
}
quantized_result = quantized_result + " vec" + trace_tree.id
}
quantized_result
}
def main(args: Array[String]) = {
var tree_data: TreeDataLoader = null
if (args.length == 0)
println("Usage: scala Quantizer <port> <filepath to tree data> <filepath to tree meta data> [SIFT feature file]")
else {
println("Starting service...")
tree_data = new TreeDataLoader(args(1))
println("Tree data loaded.")
MetaDataLoader.load(args(2))
println("Tree meta data loaded.")
var query: Query = null
if (args.length == 4) {
query = new Query()
query.loadFromFile(args(3))
println(quantize(query, tree_data.root))
} else {
println("Running in service mode.....")
val service_runner = new ServiceRunner
service_runner.start
service_runner ! new HttpService(args(0).toInt, tree_data.root)
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.