NIHVIVO-3772 Incorporate the most recent changes from Eric (2012-06-20)

This commit is contained in:
j2blake 2012-06-24 17:51:08 +00:00
parent b3c09797b0
commit c4ae8af529
13 changed files with 880 additions and 951 deletions

View file

@ -89,25 +89,13 @@ deploy - Configure the application and deploy directly into the Tomcat webapps
<!-- the Shindig WAR --> <!-- the Shindig WAR -->
<property name="shindig.war.original.file" location="./shindigorng.war" /> <property name="shindig.war.original.file" location="./shindigorng.war" />
<property name="shindig.war.unpacked.dir" location="${build.shindig.dir}/war" />
<property name="shindig.war.modified.file" location="${build.shindig.dir}/shindigorng.war" />
<property name="shindig.war.deployed.file" location="${tomcat.webapps.dir}/shindigorng.war" /> <property name="shindig.war.deployed.file" location="${tomcat.webapps.dir}/shindigorng.war" />
<property name="shindig.war.deployed.dir" location="${tomcat.webapps.dir}/shindigorng" />
<!-- the Shindig-ORNG connector JAR -->
<property name="shindig.connector.prefix" value="/WEB-INF/lib" />
<property name="shindig.connector.original.file" location="${shindig.war.unpacked.dir}/${shindig.connector.prefix}/shindig-orng-connector-2.0.2.jar" />
<property name="shindig.connector.unpacked.dir" location="${build.shindig.dir}/connector" />
<property name="shindig.connector.modified.file" location="${build.shindig.dir}/shindig-orng-connector-2.0.2.jar" />
<!-- the Shindig-ORNG connector configuration file -->
<property name="shindig.js.original.file" location="${shindig.connector.unpacked.dir}/orng-container.js" />
<property name="shindig.js.modified.file" location="${build.shindig.dir}/orng-container.js" />
<property name="shindig.js.deployed.file" location="${shindig.config.dir}/orng-container.js" />
<!-- Shindig properties file --> <!-- Shindig properties file -->
<property name="shindig.properties.template.file" location="${basedir}/shindig.orng.properties.template" /> <property name="shindig.properties.template.file" location="${basedir}/shindigorng.properties.template" />
<property name="shindig.properties.modified.file" location="${build.shindig.dir}/shindig.orng.properties" /> <property name="shindig.properties.modified.file" location="${build.shindig.dir}/shindigorng.properties" />
<property name="shindig.properties.deployed.file" location="${shindig.config.dir}/shindig.orng.properties" /> <property name="shindig.properties.deployed.file" location="${shindig.config.dir}/shindigorng.properties" />
</target> </target>
@ -118,6 +106,9 @@ deploy - Configure the application and deploy directly into the Tomcat webapps
<delete includeemptydirs="true" failonerror="false"> <delete includeemptydirs="true" failonerror="false">
<fileset dir="${build.shindig.dir}" /> <fileset dir="${build.shindig.dir}" />
</delete> </delete>
<delete includeemptydirs="true" failonerror="false">
<fileset dir="${shindig.war.deployed.dir}" />
</delete>
</target> </target>
<!-- - - - - - - - - - - - - - - - - - <!-- - - - - - - - - - - - - - - - - -
@ -127,49 +118,10 @@ deploy - Configure the application and deploy directly into the Tomcat webapps
<mkdir dir="${build.dir}" /> <mkdir dir="${build.dir}" />
<mkdir dir="${build.shindig.dir}" /> <mkdir dir="${build.shindig.dir}" />
<mkdir dir="${shindig.war.unpacked.dir}" />
<mkdir dir="${shindig.connector.unpacked.dir}" />
<mkdir dir="${shindig.home.dir}" /> <mkdir dir="${shindig.home.dir}" />
<mkdir dir="${shindig.config.dir}" /> <mkdir dir="${shindig.config.dir}" />
</target> </target>
<!-- - - - - - - - - - - - - - - - - -
target: removeConnectorConfigFromWar
Unpack the war.
Unpack the JAR.
Create a new JAR that doesn't include the config file
Create a new WAR that includes the modified JAR.
- - - - - - - - - - - - - - - - - -->
<target name="removeConnectorConfigFromWar" depends="properties, prepare">
<unwar src="${shindig.war.original.file}" dest="${shindig.war.unpacked.dir}" />
<unwar src="${shindig.connector.original.file}" dest="${shindig.connector.unpacked.dir}" />
<zip destfile="${shindig.connector.modified.file}">
<zipfileset src="${shindig.connector.original.file}" excludes="orng-container.js" />
</zip>
<zip destfile="${shindig.war.modified.file}">
<fileset dir="${shindig.war.unpacked.dir}" excludes="**/shindig-orng-connector-2.0.2.jar" />
<zipfileset fullpath="WEB-INF/lib/shindig-orng-connector-2.0.2.jar" dir="${build.shindig.dir}" includes="shindig-orng-connector-2.0.2.jar" />
</zip>
</target>
<!-- - - - - - - - - - - - - - - - - -
target: modifyConnectorConfig
Get the config file from the unpacked connector WAR and JAR, and make a modified copy.
- - - - - - - - - - - - - - - - - -->
<target name="modifyConnectorConfig" depends="removeConnectorConfigFromWar">
<copy file="${shindig.js.original.file}" tofile="${shindig.js.modified.file}">
<filterchain>
<tokenfilter>
<replacestring from="/shindig/openssl/securitytokenkey.txt" to="${OpenSocial.tokenKeyFile}" />
</tokenfilter>
</filterchain>
</copy>
</target>
<!-- - - - - - - - - - - - - - - - - - <!-- - - - - - - - - - - - - - - - - -
target: modifyPropertiesFile target: modifyPropertiesFile
- - - - - - - - - - - - - - - - - --> - - - - - - - - - - - - - - - - - -->
@ -188,10 +140,9 @@ deploy - Configure the application and deploy directly into the Tomcat webapps
<!-- ================================= <!-- =================================
target: deploy target: deploy
================================= --> ================================= -->
<target name="deploy" depends="modifyPropertiesFile, removeConnectorConfigFromWar, modifyConnectorConfig" description="--> Deploy the application directly into the Tomcat webapps directory."> <target name="deploy" depends="modifyPropertiesFile" description="--> Deploy the application directly into the Tomcat webapps directory.">
<copy file="${shindig.js.modified.file}" tofile="${shindig.js.deployed.file}" />
<copy file="${shindig.properties.modified.file}" tofile="${shindig.properties.deployed.file}" /> <copy file="${shindig.properties.modified.file}" tofile="${shindig.properties.deployed.file}" />
<copy file="${shindig.war.modified.file}" tofile="${shindig.war.deployed.file}" /> <copy file="${shindig.war.original.file}" tofile="${shindig.war.deployed.file}" overwrite="true" />
</target> </target>

View file

@ -1,17 +1,19 @@
-- Add some gadgets to play with ------------------------ -- Add some gadgets to play with ------------------------
-- --
INSERT INTO `shindig_apps` (`appid`, `name`, `url`, `PersonFilterID`, `enabled`, `channels`) VALUES DELETE FROM `orng_apps`;
(100, 'Google Search', 'http://dev-profiles.ucsf.edu/apps/GoogleSearch.xml', NULL, 1, NULL),
(101, 'Featured Presentations', 'http://dev-profiles.ucsf.edu/apps/SlideShare.xml', NULL, 1, NULL),
(102, 'Faculty Mentor', 'http://dev-profiles.ucsf.edu/apps/Mentor.xml', NULL, 1, NULL),
(103, 'Websites', 'http://dev-profiles.ucsf.edu/apps/Links.xml', NULL, 1, NULL),
(104, 'Profile List', 'http://dev-profiles.ucsf.edu/apps/ProfileListTool.xml', NULL, 1, 'JSONPersonIds'),
(105, 'Publication Export', 'http://dev-profiles.ucsf.edu/apps/PubExportTool.xml', NULL, 1, 'JSONPubMedIds'),
(106, 'RDF Test Gadget', 'http://dev-profiles.ucsf.edu/gadgets/RDFTest.xml', NULL, 1, NULL);
INSERT INTO `shindig_app_views` (`appid`, `viewer_req`, `owner_req`, `page`, `view`, `closed_width`, `open_width`, `start_closed`, `chromeId`, `display_order`) VALUES INSERT INTO `orng_apps` (`appid`, `name`, `url`, `PersonFilterID`, `enabled`, `channels`) VALUES
(100, 'Google Search', 'http://dev-profiles.ucsf.edu/orng/GoogleSearch.xml', NULL, 1, NULL),
(101, 'Featured Presentations', 'http://dev-profiles.ucsf.edu/orng/SlideShare.xml', NULL, 1, NULL),
(102, 'Faculty Mentor', 'http://dev-profiles.ucsf.edu/orng/Mentor.xml', NULL, 1, NULL),
(103, 'Websites', 'http://dev-profiles.ucsf.edu/orng/Links.xml', NULL, 1, NULL),
(104, 'Profile List', 'http://dev-profiles.ucsf.edu/orng/ProfileListTool.xml', NULL, 1, 'JSONPersonIds'),
(106, 'RDF Test Gadget', 'http://dev-profiles.ucsf.edu/orng/RDFTest.xml', NULL, 0, NULL);
DELETE FROM `orng_app_views`;
INSERT INTO `orng_app_views` (`appid`, `viewer_req`, `owner_req`, `page`, `view`, `closed_width`, `open_width`, `start_closed`, `chromeId`, `display_order`) VALUES
(100, NULL, NULL, 'search', NULL, 600, 600, 1, 'gadgets-search', NULL), (100, NULL, NULL, 'search', NULL, 600, 600, 1, 'gadgets-search', NULL),
(101, NULL, 'R', 'individual', 'profile', 290, 600, 1, 'gadgets-view', 3), (101, NULL, 'R', 'individual', 'profile', 290, 600, 1, 'gadgets-view', 3),
(101, NULL, NULL, 'individual-EDIT-MODE', 'home', 700, 700, 1, 'gadgets-edit', NULL), (101, NULL, NULL, 'individual-EDIT-MODE', 'home', 700, 700, 1, 'gadgets-edit', NULL),
@ -23,6 +25,4 @@ INSERT INTO `shindig_app_views` (`appid`, `viewer_req`, `owner_req`, `page`, `vi
(104, 'U', NULL, 'gadgetDetails', 'canvas', 700, 700, 0, 'gadgets-detail', NULL), (104, 'U', NULL, 'gadgetDetails', 'canvas', 700, 700, 0, 'gadgets-detail', NULL),
(104, 'U', NULL, 'SimilarPeople.aspx', 'small', 160, 160, 0, 'gadgets-tools', NULL), (104, 'U', NULL, 'SimilarPeople.aspx', 'small', 160, 160, 0, 'gadgets-tools', NULL),
(104, 'U', NULL, 'individual', 'small', 290, 290, 0, 'gadgets-view', NULL), (104, 'U', NULL, 'individual', 'small', 290, 290, 0, 'gadgets-view', NULL),
(104, 'U', NULL, 'CoAuthors.aspx', 'small', 160, 160, 0, 'gadgets-tools', NULL), (104, 'U', NULL, 'CoAuthors.aspx', 'small', 160, 160, 0, 'gadgets-tools', NULL);
(105, 'U', NULL, 'individual', 'small', 290, 290, 0, 'gadgets-view', NULL),
(105, 'U', NULL, 'gadgetDetails', 'canvas', 700, 700, 0, 'gadgets-detail', NULL);

View file

@ -1,9 +1,9 @@
-- --
-- Table structure for table `shindig_activity` -- Table structure for table `orng_activity`
-- --
CREATE TABLE IF NOT EXISTS `shindig_activity` ( CREATE TABLE IF NOT EXISTS `orng_activity` (
`activityId` int(11) NOT NULL AUTO_INCREMENT, `activityId` int(11) NOT NULL AUTO_INCREMENT,
`userId` varchar(255) default NULL, `userId` varchar(255) default NULL,
`appId` int(11) default NULL, `appId` int(11) default NULL,
@ -15,10 +15,10 @@ CREATE TABLE IF NOT EXISTS `shindig_activity` (
-- -------------------------------------------------------- -- --------------------------------------------------------
-- --
-- Table structure for table `shindig_appdata` -- Table structure for table `orng_appdata`
-- --
CREATE TABLE IF NOT EXISTS `shindig_appdata` ( CREATE TABLE IF NOT EXISTS `orng_appdata` (
`userId` varchar(255) NOT NULL, `userId` varchar(255) NOT NULL,
`appId` int(11) NOT NULL, `appId` int(11) NOT NULL,
`keyname` varchar(255) NOT NULL, `keyname` varchar(255) NOT NULL,
@ -31,10 +31,10 @@ CREATE TABLE IF NOT EXISTS `shindig_appdata` (
-- -------------------------------------------------------- -- --------------------------------------------------------
-- --
-- Table structure for table `shindig_apps` -- Table structure for table `orng_apps`
-- --
CREATE TABLE IF NOT EXISTS `shindig_apps` ( CREATE TABLE IF NOT EXISTS `orng_apps` (
`appid` int(11) NOT NULL, `appid` int(11) NOT NULL,
`name` varchar(255) NOT NULL, `name` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL, `url` varchar(255) NOT NULL,
@ -47,10 +47,10 @@ CREATE TABLE IF NOT EXISTS `shindig_apps` (
-- -------------------------------------------------------- -- --------------------------------------------------------
-- --
-- Table structure for table `shindig_app_registry` -- Table structure for table `orng_app_registry`
-- --
CREATE TABLE IF NOT EXISTS `shindig_app_registry` ( CREATE TABLE IF NOT EXISTS `orng_app_registry` (
`appid` int(11) NOT NULL, `appid` int(11) NOT NULL,
`personId` varchar(255) NOT NULL, `personId` varchar(255) NOT NULL,
`createdDT` datetime NOT NULL, `createdDT` datetime NOT NULL,
@ -60,10 +60,10 @@ CREATE TABLE IF NOT EXISTS `shindig_app_registry` (
-- -------------------------------------------------------- -- --------------------------------------------------------
-- --
-- Table structure for table `shindig_app_views` -- Table structure for table `orng_app_views`
-- --
CREATE TABLE IF NOT EXISTS `shindig_app_views` ( CREATE TABLE IF NOT EXISTS `orng_app_views` (
`appid` int(11) NOT NULL, `appid` int(11) NOT NULL,
`viewer_req` char(1) default NULL, `viewer_req` char(1) default NULL,
`owner_req` char(1) default NULL, `owner_req` char(1) default NULL,
@ -79,10 +79,10 @@ CREATE TABLE IF NOT EXISTS `shindig_app_views` (
-- -------------------------------------------------------- -- --------------------------------------------------------
-- --
-- Table structure for table `shindig_messages` -- Table structure for table `orng_messages`
-- --
CREATE TABLE IF NOT EXISTS `shindig_messages` ( CREATE TABLE IF NOT EXISTS `orng_messages` (
`msgId` varchar(255) NOT NULL, `msgId` varchar(255) NOT NULL,
`senderId` varchar(255) default NULL, `senderId` varchar(255) default NULL,
`recipientId` varchar(255) default NULL, `recipientId` varchar(255) default NULL,
@ -97,47 +97,47 @@ CREATE TABLE IF NOT EXISTS `shindig_messages` (
DELIMITER // DELIMITER //
CREATE PROCEDURE shindig_registerAppPerson (uid varchar(255), aid INT, v BOOL) CREATE PROCEDURE orng_registerAppPerson (uid varchar(255), aid INT, v BOOL)
BEGIN BEGIN
IF (v) IF (v)
THEN THEN
INSERT INTO shindig_app_registry (appId, personId, createdDT) values (aid, uid, now()); INSERT INTO orng_app_registry (appId, personId, createdDT) values (aid, uid, now());
ELSE ELSE
DELETE FROM shindig_app_registry where appId = aid AND personId = uid; DELETE FROM orng_app_registry where appId = aid AND personId = uid;
END IF; END IF;
END // END //
DELIMITER ; DELIMITER ;
DELIMITER // DELIMITER //
CREATE PROCEDURE shindig_upsertAppData(uid varchar(255), aid INT, kn varchar(255),v varchar(4000)) CREATE PROCEDURE orng_upsertAppData(uid varchar(255), aid INT, kn varchar(255),v varchar(4000))
BEGIN BEGIN
DECLARE cnt int; DECLARE cnt int;
SELECT count(*) FROM shindig_appdata WHERE userId = uid AND appId = aid and keyname = kn INTO cnt; SELECT count(*) FROM orng_appdata WHERE userId = uid AND appId = aid and keyname = kn INTO cnt;
IF (cnt > 0) IF (cnt > 0)
THEN THEN
UPDATE shindig_appdata set `value` = v, updatedDT = NOW() WHERE userId = uid AND appId = aid and keyname = kn; UPDATE orng_appdata set `value` = v, updatedDT = NOW() WHERE userId = uid AND appId = aid and keyname = kn;
ELSE ELSE
INSERT INTO shindig_appdata (userId, appId, keyname, `value`) values (uid, aid, kn, v); INSERT INTO orng_appdata (userId, appId, keyname, `value`) values (uid, aid, kn, v);
END IF; END IF;
-- if keyname is VISIBLE, do more -- if keyname is VISIBLE, do more
IF (kn = 'VISIBLE' AND v = 'Y') IF (kn = 'VISIBLE' AND v = 'Y')
THEN THEN
CALL shindig_registerAppPerson(uid, aid, 1); CALL orng_registerAppPerson(uid, aid, 1);
ELSEIF (kn = 'VISIBLE' ) ELSEIF (kn = 'VISIBLE' )
THEN THEN
CALL shindig_registerAppPerson(uid, aid, 0); CALL orng_registerAppPerson(uid, aid, 0);
END IF; END IF;
END // END //
DELIMITER ; DELIMITER ;
DELIMITER // DELIMITER //
CREATE PROCEDURE shindig_deleteAppData(uid varchar(255),aid INT, kn varchar(255)) CREATE PROCEDURE orng_deleteAppData(uid varchar(255),aid INT, kn varchar(255))
BEGIN BEGIN
DELETE FROM shindig_appdata WHERE userId = uid AND appId = aid and keyname = kn; DELETE FROM orng_appdata WHERE userId = uid AND appId = aid and keyname = kn;
-- if keyname is VISIBLE, do more -- if keyname is VISIBLE, do more
IF (kn = 'VISIBLE' ) IF (kn = 'VISIBLE' )
THEN THEN
CALL shindig_registerAppPerson(uid, aid, 0); CALL orng_registerAppPerson(uid, aid, 0);
END IF; END IF;
END // END //
DELIMITER ; DELIMITER ;

View file

@ -1,190 +1,191 @@
# Licensed to the Apache Software Foundation (ASF) under one # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file # or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information # distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file # regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the # to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance # "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at # with the License. You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0 # http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, # Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an # software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the # KIND, either express or implied. See the License for the
# specific language governing permissions and limitations # specific language governing permissions and limitations
# under the License. # under the License.
################################################################## ##################################################################
# #
# Note from UCSF. Compare this to the latest in shindig-common/conf/shindig.properties # Note from UCSF. Compare this to the latest in shindig-common/conf/shindig.properties
# whenever you download a new version of shindig # whenever you download a new version of shindig
# #
################################################################## ##################################################################
# Location of feature manifests (comma separated) # Location of feature manifests (comma separated)
shindig.features.default=res://features/features.txt shindig.features.default=res://features/features.txt
# Location of container configurations (comma separated) # Location of container configurations (comma separated)
#shindig.containers.default=res://containers/default/container.js # In shindigorng this is set automatically to either res://vivo-container.js or res://profiles-container.js based on your orng.system value below!
shindig.containers.default=res://orng-container.js # Leave this commented out !!!!
#shindig.containers.default=res://containers/default/container.js
# A file containing blacklisted gadgets.
shindig.blacklist.file=
# A file containing blacklisted gadgets.
### Inbound OAuth support shindig.blacklist.file=
# The URL base to use for full OAuth support (three-legged)
shindig.oauth.base-url=/oauth/ ### Inbound OAuth support
shindig.oauth.authorize-action=/WEB-INF/authorize.jsp # The URL base to use for full OAuth support (three-legged)
shindig.oauth.base-url=/oauth/
### Outbound OAuth support shindig.oauth.authorize-action=/WEB-INF/authorize.jsp
shindig.signing.state-key=
shindig.signing.key-name= ### Outbound OAuth support
shindig.signing.key-file= shindig.signing.state-key=
shindig.signing.global-callback-url=http://localhost:8080/shindigorng/gadgets/oauthcallback shindig.signing.key-name=
shindig.signing.enable-signed-callbacks=true shindig.signing.key-file=
shindig.signing.global-callback-url=http://localhost:8080/shindigorng/gadgets/oauthcallback
# Set to true if you want to allow the use of 3-legged OAuth tokens when viewer != owner. shindig.signing.enable-signed-callbacks=true
# This setting is not recommeneded for pages that allow user-controlled javascript, since
# that javascript could be used to make unauthorized requests on behalf of the viewer of the page # Set to true if you want to allow the use of 3-legged OAuth tokens when viewer != owner.
shindig.signing.viewer-access-tokens-enabled=false # This setting is not recommeneded for pages that allow user-controlled javascript, since
# that javascript could be used to make unauthorized requests on behalf of the viewer of the page
# If enabled here, configuration values can be found in container configuration files. shindig.signing.viewer-access-tokens-enabled=false
shindig.locked-domain.enabled=false
# If enabled here, configuration values can be found in container configuration files.
# TODO: This needs to be moved to container configuration. shindig.locked-domain.enabled=false
# Note by Eric. This is set up to now exclude everything and include nothing
shindig.content-rewrite.only-allow-excludes=false # TODO: This needs to be moved to container configuration.
shindig.content-rewrite.include-urls=.* # Note by Eric. This is set up to now exclude everything and include nothing
shindig.content-rewrite.exclude-urls= shindig.content-rewrite.only-allow-excludes=false
shindig.content-rewrite.include-tags=body,embed,img,input,link,script,style shindig.content-rewrite.include-urls=.*
shindig.content-rewrite.expires=86400 shindig.content-rewrite.exclude-urls=
shindig.content-rewrite.proxy-url=/shindigorng/gadgets/proxy?container=default&url= shindig.content-rewrite.include-tags=body,embed,img,input,link,script,style
shindig.content-rewrite.concat-url=/shindigorng/gadgets/concat?container=default& shindig.content-rewrite.expires=86400
shindig.content-rewrite.enable-split-js-concat=false shindig.content-rewrite.proxy-url=/shindigorng/gadgets/proxy?container=default&url=
shindig.content-rewrite.concat-url=/shindigorng/gadgets/concat?container=default&
# shindig.content-rewrite.enable-split-js-concat=false
# Default set of forced libs to allow for better caching
# #
# NOTE: setting this causes the EndToEnd test to fail the opensocial-templates test # Default set of forced libs to allow for better caching
shindig.gadget-rewrite.default-forced-libs=core:rpc #
shindig.gadget-rewrite.default-forced-libs= # NOTE: setting this causes the EndToEnd test to fail the opensocial-templates test
shindig.gadget-rewrite.default-forced-libs=core:rpc
# shindig.gadget-rewrite.default-forced-libs=
# Allow supported JavaScript features required by a gadget to be externalized on demand
shindig.gadget-rewrite.externalize-feature-libs=true #
# Allow supported JavaScript features required by a gadget to be externalized on demand
# Configuration for image rewriter shindig.gadget-rewrite.externalize-feature-libs=true
shindig.image-rewrite.max-inmem-bytes = 1048576
shindig.image-rewrite.max-palette-size = 256 # Configuration for image rewriter
shindig.image-rewrite.allow-jpeg-conversion = true shindig.image-rewrite.max-inmem-bytes = 1048576
shindig.image-rewrite.jpeg-compression = 0.75 shindig.image-rewrite.max-palette-size = 256
shindig.image-rewrite.min-threshold-bytes = 200 shindig.image-rewrite.allow-jpeg-conversion = true
shindig.image-rewrite.jpeg-compression = 0.75
# Configuration for the os:Flash tag shindig.image-rewrite.min-threshold-bytes = 200
shindig.flash.min-version = 9.0.115
# Configuration for the os:Flash tag
# Configuration for template rewriter shindig.flash.min-version = 9.0.115
shindig.template-rewrite.extension-tag-namespace=http://ns.opensocial.org/2009/extensions
# Configuration for template rewriter
# These values provide default TTLs for HTTP responses that don't use caching headers. shindig.template-rewrite.extension-tag-namespace=http://ns.opensocial.org/2009/extensions
shindig.cache.http.defaultTtl=3600000
shindig.cache.http.negativeCacheTtl=60000 # These values provide default TTLs for HTTP responses that don't use caching headers.
shindig.cache.http.defaultTtl=3600000
# A default refresh interval for XML files, since there is no natural way for developers to shindig.cache.http.negativeCacheTtl=60000
# specify this value, and most HTTP responses don't include good cache control headers.
shindig.cache.xml.refreshInterval=300000 # A default refresh interval for XML files, since there is no natural way for developers to
# specify this value, and most HTTP responses don't include good cache control headers.
# Add entries in the form shindig.cache.lru.<name>.capacity to specify capacities for different shindig.cache.xml.refreshInterval=300000
# caches when using the LruCacheProvider.
# It is highly recommended that the EhCache implementation be used instead of the LRU cache. # Add entries in the form shindig.cache.lru.<name>.capacity to specify capacities for different
shindig.cache.lru.default.capacity=1000 # caches when using the LruCacheProvider.
shindig.cache.lru.expressions.capacity=1000 # It is highly recommended that the EhCache implementation be used instead of the LRU cache.
shindig.cache.lru.gadgetSpecs.capacity=1000 shindig.cache.lru.default.capacity=1000
shindig.cache.lru.messageBundles.capacity=1000 shindig.cache.lru.expressions.capacity=1000
shindig.cache.lru.httpResponses.capacity=10000 shindig.cache.lru.gadgetSpecs.capacity=1000
shindig.cache.lru.messageBundles.capacity=1000
# The location of the EhCache configuration file. shindig.cache.lru.httpResponses.capacity=10000
shindig.cache.ehcache.config=res://org/apache/shindig/common/cache/ehcache/ehcacheConfig.xml
# The location of the EhCache configuration file.
# True to enable JMX integration with cache stats shindig.cache.ehcache.config=res://org/apache/shindig/common/cache/ehcache/ehcacheConfig.xml
shindig.cache.ehcache.jmx.enabled=true
# True to enable JMX integration with cache stats
# true to enable JMX stats. shindig.cache.ehcache.jmx.enabled=true
shindig.cache.ehcache.jmx.stats=true
# true to enable JMX stats.
# true to skip expensive encoding detection. shindig.cache.ehcache.jmx.stats=true
# if true, will only attempt to validate utf-8. Assumes all other encodings are ISO-8859-1.
shindig.http.fast-encoding-detection=true # true to skip expensive encoding detection.
# if true, will only attempt to validate utf-8. Assumes all other encodings are ISO-8859-1.
# Configuration for the HttpFetcher shindig.http.fast-encoding-detection=true
# Connection timeout, in milliseconds, for requests.
shindig.http.client.connection-timeout-ms=5000 # Configuration for the HttpFetcher
# Connection timeout, in milliseconds, for requests.
# Maximum size, in bytes, of the object we fetched, 0 == no limit shindig.http.client.connection-timeout-ms=5000
shindig.http.client.max-object-size-bytes=0
# Maximum size, in bytes, of the object we fetched, 0 == no limit
# Strict-mode parsing for proxy and concat URIs ensures that the authority/host and path shindig.http.client.max-object-size-bytes=0
# for the URIs match precisely what is found in the container config for it. This is
# useful where statistics and traffic routing patterns, typically in large installations, # Strict-mode parsing for proxy and concat URIs ensures that the authority/host and path
# key on hostname (and occasionally path). Enforcing this does come at the cost that # for the URIs match precisely what is found in the container config for it. This is
# mismatches break, which in turn mandates that URI generation always happen in consistent # useful where statistics and traffic routing patterns, typically in large installations,
# fashion, ie. by the class itself or tightly controlled code. # key on hostname (and occasionally path). Enforcing this does come at the cost that
shindig.uri.proxy.use-strict-parsing=false # mismatches break, which in turn mandates that URI generation always happen in consistent
shindig.uri.concat.use-strict-parsing=false # fashion, ie. by the class itself or tightly controlled code.
shindig.uri.proxy.use-strict-parsing=false
# Host:port of the proxy to use while fetching urls. Leave blank if proxy is shindig.uri.concat.use-strict-parsing=false
# not to be used.
org.apache.shindig.gadgets.http.basicHttpFetcherProxy= # Host:port of the proxy to use while fetching urls. Leave blank if proxy is
# not to be used.
org.apache.shindig.serviceExpirationDurationMinutes=60 org.apache.shindig.gadgets.http.basicHttpFetcherProxy=
# org.apache.shindig.serviceExpirationDurationMinutes=60
# Older versions of shindig used 'data' in the json-rpc response format
# The spec calls for using 'result' instead, however to avoid breakage we #
# allow you to set it back to the old way here # Older versions of shindig used 'data' in the json-rpc response format
# # The spec calls for using 'result' instead, however to avoid breakage we
# valid values are # allow you to set it back to the old way here
# result - new form #
# data - old broken form # valid values are
# both - return both fields for full compatibility # result - new form
# # data - old broken form
shindig.json-rpc.result-field=result # both - return both fields for full compatibility
#
# Remap "Internal server error"s received from the basicHttpFetcherProxy server to shindig.json-rpc.result-field=result
# "Bad Gateway error"s, so that it is clear to the user that the proxy server is
# the one that threw the exception. # Remap "Internal server error"s received from the basicHttpFetcherProxy server to
shindig.accelerate.remapInternalServerError=true # "Bad Gateway error"s, so that it is clear to the user that the proxy server is
shindig.proxy.remapInternalServerError=true # the one that threw the exception.
shindig.accelerate.remapInternalServerError=true
shindig.signing.key-file=@TOKEN_KEY_FILE@ shindig.proxy.remapInternalServerError=true
shindig.signing.key-name=
shindig.signing.key-file=@TOKEN_KEY_FILE@
#################################################################################### shindig.signing.key-name=mykey
#
# Open Research Networking Gadgets Items #####################################################################################
# #
##################################################################################### # Open Research Networking Gadgets Items
#
# orng.system must be set to Profiles or VIVO #####################################################################################
#orng.system = Profiles
orng.system = VIVO # orng.RDFConverter should be elda. We also currently support babel but it is only being used for test and comparison purposes
# and babel will be phased out
# orng.dbDriver is likely com.microsoft.sqlserver.jdbc.SQLServerDriver for Profiles and com.mysql.jdbc.Driver for VIVO orng.RDFConverter = elda
#orng.dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver orng.tokenservice.port = 8777
orng.dbDriver = @DATA_SOURCE_DRIVER@ orng.securityTokenKeyFile = @TOKEN_KEY_FILE@
orng.dbURL = @DATA_SOURCE_URL@
orng.dbUser = @DATA_SOURCE_USERNAME@ # orng.system must be set to Profiles or VIVO
orng.dbPassword = @DATA_SOURCE_PASSWORD@ #orng.system = Profiles
orng.tokenservice.port = 8777 #orng.dbDriver = com.microsoft.sqlserver.jdbc.SQLServerDriver
# orng.RDFConverter = elda | babel #orng.dbURL = jdbc:sqlserver://dev-sql-ctsi.ucsf.edu;instanceName=default;portNumber=1433;databaseName=profiles_100
orng.RDFConverter = elda #orng.dbUser = App_Profiles10
#orng.RDFConverter = babel #orng.dbPassword = Password1234
# until Profiles has RDF orng.system = VIVO
orng.profilesXMLService = http://dev-profiles.ucsf.edu/api_100810/ProfileService.svc/ProfileSearch orng.dbDriver = @DATA_SOURCE_DRIVER@
orng.profilesRDF = true; orng.dbURL = @DATA_SOURCE_URL@
orng.dbUser = @DATA_SOURCE_USERNAME@
orng.dbPassword = @DATA_SOURCE_PASSWORD@

Binary file not shown.

View file

@ -273,10 +273,15 @@ public class PagedSearchController extends FreemarkerHttpServlet {
// VIVO OpenSocial Extension by UCSF // VIVO OpenSocial Extension by UCSF
try { try {
OpenSocialManager openSocialManager = new OpenSocialManager(vreq, "search"); OpenSocialManager openSocialManager = new OpenSocialManager(vreq, "search");
// put list of people found onto pubsub channel // put list of people found onto pubsub channel
List<String> ids = OpenSocialManager.getOpenSocialId(individuals); // only turn this on for a people only search
openSocialManager.setPubsubData(OpenSocialManager.JSON_PERSONID_CHANNEL, if ("http://vivoweb.org/ontology#vitroClassGrouppeople".equals(vreq.getParameter(PARAM_CLASSGROUP))) {
OpenSocialManager.buildJSONPersonIds(ids, "" + ids.size() + " people found")); List<String> ids = OpenSocialManager.getOpenSocialId(individuals);
openSocialManager.setPubsubData(OpenSocialManager.JSON_PERSONID_CHANNEL,
OpenSocialManager.buildJSONPersonIds(ids, "" + ids.size() + " people found"));
}
// TODO put this in a better place to guarantee that it gets called at the proper time!
openSocialManager.removePubsubGadgetsWithoutData();
body.put("openSocial", openSocialManager); body.put("openSocial", openSocialManager);
if (openSocialManager.isVisible()) { if (openSocialManager.isVisible()) {
body.put("bodyOnload", "my.init();"); body.put("bodyOnload", "my.init();");
@ -285,7 +290,7 @@ public class PagedSearchController extends FreemarkerHttpServlet {
log.error("IOException in doTemplate()", e); log.error("IOException in doTemplate()", e);
} catch (SQLException e) { } catch (SQLException e) {
log.error("SQLException in doTemplate()", e); log.error("SQLException in doTemplate()", e);
} }
String template = templateTable.get(format).get(Result.PAGED); String template = templateTable.get(format).get(Result.PAGED);

View file

@ -23,7 +23,11 @@ public class GadgetController extends FreemarkerHttpServlet {
@Override @Override
protected ResponseValues processRequest(VitroRequest vreq) { protected ResponseValues processRequest(VitroRequest vreq) {
if (vreq.getServletPath().endsWith("/sandbox")) { if ("/clearcache".equalsIgnoreCase(vreq.getPathInfo())) {
OpenSocialManager.clearCache();
return new RedirectResponseValues("/");
}
else if ("/sandbox".equalsIgnoreCase(vreq.getPathInfo())) {
boolean sandbox = "True".equalsIgnoreCase(ConfigurationProperties.getBean(vreq.getSession() boolean sandbox = "True".equalsIgnoreCase(ConfigurationProperties.getBean(vreq.getSession()
.getServletContext()).getProperty("OpenSocial.sandbox")); .getServletContext()).getProperty("OpenSocial.sandbox"));
if (!sandbox) { if (!sandbox) {
@ -81,7 +85,7 @@ public class GadgetController extends FreemarkerHttpServlet {
try { try {
OpenSocialManager openSocialManager = new OpenSocialManager(vreq, "gadgetSandbox"); OpenSocialManager openSocialManager = new OpenSocialManager(vreq, "gadgetSandbox");
String gadgetURLS = ""; String gadgetURLS = "";
for (PreparedGadget gadget : openSocialManager.getVisibleGadgets()) for (GadgetSpec gadget : openSocialManager.getAllDBGadgets(false).values())
{ {
gadgetURLS += gadget.getGadgetURL() + System.getProperty("line.separator"); gadgetURLS += gadget.getGadgetURL() + System.getProperty("line.separator");
} }

View file

@ -5,7 +5,6 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -13,33 +12,24 @@ import java.util.Map;
import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSource;
public class GadgetSpec { public class GadgetSpec {
private String openSocialGadgetURL;
private String name;
private int appId = 0; private int appId = 0;
private String name;
private String openSocialGadgetURL;
private List<String> channels = new ArrayList<String>(); private List<String> channels = new ArrayList<String>();
private boolean unknownGadget = false;
private Map<String, GadgetViewRequirements> viewRequirements = new HashMap<String, GadgetViewRequirements>(); private Map<String, GadgetViewRequirements> viewRequirements = new HashMap<String, GadgetViewRequirements>();
boolean enabled;
private boolean unknownGadget = false;
// For preloading
public GadgetSpec(int appId, String name, String openSocialGadgetURL, public GadgetSpec(int appId, String name, String openSocialGadgetURL,
List<String> channels) { List<String> channels, BasicDataSource ds, boolean enabled, boolean unknownGadget)
throws SQLException {
this.appId = appId; this.appId = appId;
this.name = name; this.name = name;
this.openSocialGadgetURL = openSocialGadgetURL; this.openSocialGadgetURL = openSocialGadgetURL;
this.channels.addAll(channels); this.channels.addAll(channels);
} this.enabled = enabled;
public GadgetSpec(int appId, String name, String openSocialGadgetURL,
String channelsStr) {
this(appId, name, openSocialGadgetURL, Arrays.asList(channelsStr != null
&& channelsStr.length() > 0 ? channelsStr.split(" ") : new String[0]));
}
public GadgetSpec(int appId, String name, String openSocialGadgetURL,
List<String> channels, boolean unknownGadget, BasicDataSource ds)
throws SQLException {
this(appId, name, openSocialGadgetURL, channels);
this.unknownGadget = unknownGadget; this.unknownGadget = unknownGadget;
// Load gadgets from the DB first // Load gadgets from the DB first
if (!unknownGadget) { if (!unknownGadget) {
Connection conn = null; Connection conn = null;
@ -47,7 +37,7 @@ public class GadgetSpec {
ResultSet rset = null; ResultSet rset = null;
try { try {
String sqlCommand = "select page, viewer_req, owner_req, view, closed_width, open_width, start_closed, chromeId, display_order from shindig_app_views where appId = " String sqlCommand = "select page, viewer_req, owner_req, view, closed_width, open_width, start_closed, chromeId, display_order from orng_app_views where appId = "
+ appId; + appId;
conn = ds.getConnection(); conn = ds.getConnection();
stmt = conn.createStatement(); stmt = conn.createStatement();
@ -63,25 +53,16 @@ public class GadgetSpec {
} }
} finally { } finally {
try { try {
if (rset != null) { rset.close();
rset.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
try { try {
if (stmt != null) { stmt.close();
stmt.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
try { try {
if (conn != null) { conn.close();
conn.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
} }
} }
@ -103,7 +84,7 @@ public class GadgetSpec {
return channels; return channels;
} }
public boolean listensTo(String channel) { // if an unknown gadget just say yes, public boolean listensTo(String channel) { // if an unknownd gadget just say yes,
// we don't care about // we don't care about
// performance in this situation // performance in this situation
return unknownGadget || channels.contains(channel); return unknownGadget || channels.contains(channel);
@ -129,7 +110,7 @@ public class GadgetSpec {
if (viewRequirements.containsKey(page)) { if (viewRequirements.containsKey(page)) {
show = true; show = true;
GadgetViewRequirements req = getGadgetViewRequirements(page); GadgetViewRequirements req = getGadgetViewRequirements(page);
if ('U' == req.getViewerReq() && viewerId != null) { if ('U' == req.getViewerReq() && viewerId == null) {
show = false; show = false;
} else if ('R' == req.getViewerReq()) { } else if ('R' == req.getViewerReq()) {
show &= isRegisteredTo(viewerId, ds); show &= isRegisteredTo(viewerId, ds);
@ -152,7 +133,7 @@ public class GadgetSpec {
ResultSet rset = null; ResultSet rset = null;
try { try {
String sqlCommand = "select count(*) from shindig_app_registry where appId = " String sqlCommand = "select count(*) from orng_app_registry where appId = "
+ getAppId() + " and personId = '" + personId + "';"; + getAppId() + " and personId = '" + personId + "';";
conn = ds.getConnection(); conn = ds.getConnection();
stmt = conn.createStatement(); stmt = conn.createStatement();
@ -162,25 +143,16 @@ public class GadgetSpec {
} }
} finally { } finally {
try { try {
if (rset != null) { rset.close();
rset.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
try { try {
if (stmt != null) { stmt.close();
stmt.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
try { try {
if (conn != null) { conn.close();
conn.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
} }
@ -191,6 +163,10 @@ public class GadgetSpec {
return unknownGadget; return unknownGadget;
} }
public boolean isEnabled() {
return enabled;
}
// who sees it? Return the viewerReq for the ProfileDetails page // who sees it? Return the viewerReq for the ProfileDetails page
public char getVisibleScope() { public char getVisibleScope() {
GadgetViewRequirements req = getGadgetViewRequirements("/display"); GadgetViewRequirements req = getGadgetViewRequirements("/display");

View file

@ -1,7 +1,6 @@
package edu.ucsf.vitro.opensocial; package edu.ucsf.vitro.opensocial;
public class GadgetViewRequirements { public class GadgetViewRequirements {
private String page;
private char viewerReq; // U for User or null for no requirement private char viewerReq; // U for User or null for no requirement
private char ownerReq; // R for Registered or null for no requirement private char ownerReq; // R for Registered or null for no requirement
private String view; private String view;
@ -11,10 +10,9 @@ public class GadgetViewRequirements {
private String chromeId; private String chromeId;
private int display_order; private int display_order;
public GadgetViewRequirements(String page, char viewerReq, char ownerReq, public GadgetViewRequirements(char viewerReq, char ownerReq,
String view, int closedWidth, int openWidth, boolean startClosed, String view, int closedWidth, int openWidth, boolean startClosed,
String chromeId, int display_order) { String chromeId, int display_order) {
this.page = page;
this.viewerReq = viewerReq; this.viewerReq = viewerReq;
this.ownerReq = ownerReq; this.ownerReq = ownerReq;
this.view = view; this.view = view;
@ -28,7 +26,7 @@ public class GadgetViewRequirements {
public GadgetViewRequirements(String page, String viewerReq, public GadgetViewRequirements(String page, String viewerReq,
String ownerReq, String view, int closedWidth, int openWidth, String ownerReq, String view, int closedWidth, int openWidth,
boolean startClosed, String chromeId, int display_order) { boolean startClosed, String chromeId, int display_order) {
this(page, viewerReq != null ? viewerReq.charAt(0) : ' ', this(viewerReq != null ? viewerReq.charAt(0) : ' ',
ownerReq != null ? ownerReq.charAt(0) : ' ', view, closedWidth, ownerReq != null ? ownerReq.charAt(0) : ' ', view, closedWidth,
openWidth, startClosed, chromeId, display_order); openWidth, startClosed, chromeId, display_order);
} }

View file

@ -8,6 +8,7 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -39,6 +40,9 @@ public class OpenSocialManager {
private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver"; private static final String DEFAULT_DRIVER = "com.mysql.jdbc.Driver";
// for performance
private static Map<String, GadgetSpec> gadgetCache;
private List<PreparedGadget> gadgets = new ArrayList<PreparedGadget>(); private List<PreparedGadget> gadgets = new ArrayList<PreparedGadget>();
private Map<String, String> pubsubdata = new HashMap<String, String>(); private Map<String, String> pubsubdata = new HashMap<String, String>();
private String viewerId = null; private String viewerId = null;
@ -79,15 +83,13 @@ public class OpenSocialManager {
} }
else { else {
UserAccount viewer = LoginStatusBean.getCurrentUser(vreq); UserAccount viewer = LoginStatusBean.getCurrentUser(vreq);
this.viewerId = viewer != null ? viewer.getUri() : null; // attempt to use profile URI if present, otherwise user user oriented URI
this.viewerId = viewer != null && viewer.getProxiedIndividualUris().size() == 1 ?
viewer.getProxiedIndividualUris().toArray()[0].toString() : (viewer != null ? viewer.getUri() : null);
} }
boolean gadgetSandbox = "gadgetSandbox".equals(pageName);
String requestAppId = vreq.getParameter("appId"); String requestAppId = vreq.getParameter("appId");
Map<String, GadgetSpec> dbApps = new HashMap<String, GadgetSpec>();
Map<String, GadgetSpec> officialApps = new HashMap<String, GadgetSpec>();
dataSource = new BasicDataSource(); dataSource = new BasicDataSource();
dataSource.setDriverClassName(DEFAULT_DRIVER); dataSource.setDriverClassName(DEFAULT_DRIVER);
dataSource.setUsername(configuration dataSource.setUsername(configuration
@ -98,116 +100,26 @@ public class OpenSocialManager {
.getProperty("VitroConnection.DataSource.url")); .getProperty("VitroConnection.DataSource.url"));
// Load gadgets from the DB first // Load gadgets from the DB first
Connection conn = null; Map<String, GadgetSpec> allDBGadgets = getAllDBGadgets(!noCache);
Statement stmt = null;
ResultSet rset = null;
try {
String sqlCommand = "select appId, name, url, channels, enabled from shindig_apps"; // Add sandbox gadgets if they are present
// if a specific app is requested, only grab it if (vreq.getSession() != null && vreq.getSession().getAttribute(OPENSOCIAL_GADGETS) != null) {
if (requestAppId != null) { gadgets = getSandboxGadgets(vreq, allDBGadgets, requestAppId);
sqlCommand += " where appId = " + requestAppId;
}
conn = dataSource.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery(sqlCommand);
while (rset.next()) {
GadgetSpec spec = new GadgetSpec(rset.getInt(1),
rset.getString(2), rset.getString(3), rset.getString(4));
String gadgetFileName = getGadgetFileNameFromURL(rset
.getString(3));
dbApps.put(gadgetFileName, spec);
if (requestAppId != null || rset.getBoolean(5)) {
officialApps.put(gadgetFileName, spec);
}
}
} finally {
try {
if (rset != null) {
rset.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (stmt != null) {
stmt.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
} }
else {
// Add manual gadgets if there are any // if no manual one were added, use the ones from the DB
// Note that this block of code only gets executed after someone fills in the for (GadgetSpec gadgetSpec : allDBGadgets.values()) {
// gadget/sandbox form!
int moduleId = 0;
if (vreq.getSession() != null
&& vreq.getSession().getAttribute(OPENSOCIAL_GADGETS) != null) {
String openSocialGadgetURLS = (String) vreq.getSession()
.getAttribute(OPENSOCIAL_GADGETS);
String[] urls = openSocialGadgetURLS.split(System.getProperty("line.separator"));
for (String openSocialGadgetURL : urls) {
if (openSocialGadgetURL.length() == 0)
continue;
int appId = 0; // if URL matches one in the DB, use DB provided
// appId, otherwise generate one
String gadgetFileName = getGadgetFileNameFromURL(openSocialGadgetURL);
String name = gadgetFileName;
List<String> channels = new ArrayList<String>();
boolean unknownGadget = true;
if (dbApps.containsKey(gadgetFileName)) {
appId = dbApps.get(gadgetFileName).getAppId();
name = dbApps.get(gadgetFileName).getName();
channels = dbApps.get(gadgetFileName).getChannels();
unknownGadget = false;
} else {
appId = openSocialGadgetURL.hashCode();
}
// if they asked for a specific one, only let it in
if (requestAppId != null
&& Integer.getInteger(requestAppId) != appId) {
continue;
}
GadgetSpec gadget = new GadgetSpec(appId, name,
openSocialGadgetURL, channels, unknownGadget, dataSource);
// only add ones that are visible in this context! // only add ones that are visible in this context!
if (unknownGadget int moduleId = 0;
|| gadget.show(viewerId, ownerId, pageName, dataSource)) { if (
String securityToken = socketSendReceive(viewerId, ownerId, (
"" + gadget.getAppId()); (requestAppId == null && gadgetSpec.isEnabled()) ||
gadgets.add(new PreparedGadget(gadget, this, moduleId++, (requestAppId != null && gadgetSpec.getAppId() == Integer.parseInt(requestAppId))
securityToken)); ) &&
} gadgetSpec.show(viewerId, ownerId, pageName, dataSource)
} ) {
} String securityToken = socketSendReceive(viewerId, ownerId, "" + gadgetSpec.getAppId());
gadgets.add(new PreparedGadget(gadgetSpec, this, moduleId++, securityToken));
// if no manual one were added, use the ones from the DB
if (gadgets.size() == 0) {
// Load DB gadgets
if (gadgetSandbox) {
officialApps = dbApps;
}
for (GadgetSpec spec : officialApps.values()) {
GadgetSpec gadget = new GadgetSpec(spec.getAppId(),
spec.getName(), spec.getGadgetURL(),
spec.getChannels(), false, dataSource);
// only add ones that are visible in this context!
if (gadgetSandbox
|| gadget.show(viewerId, ownerId, pageName, dataSource)) {
String securityToken = socketSendReceive(viewerId, ownerId,
"" + gadget.getAppId());
gadgets.add(new PreparedGadget(gadget, this, moduleId++,
securityToken));
} }
} }
} }
@ -215,6 +127,10 @@ public class OpenSocialManager {
// sort the gadgets // sort the gadgets
Collections.sort(gadgets); Collections.sort(gadgets);
} }
public static void clearCache() {
gadgetCache = null;
}
private String figureOwnerId(VitroRequest vreq) { private String figureOwnerId(VitroRequest vreq) {
IndividualRequestAnalyzer requestAnalyzer = new IndividualRequestAnalyzer(vreq, IndividualRequestAnalyzer requestAnalyzer = new IndividualRequestAnalyzer(vreq,
@ -278,17 +194,6 @@ public class OpenSocialManager {
personIds.add(ind.getURI()); personIds.add(ind.getURI());
return buildJSONPersonIds(personIds, message); return buildJSONPersonIds(personIds, message);
} }
/****
* public static String BuildJSONPubMedIds(Person person) { List<Int32>
* pubIds = new List<Int32>(); foreach (Publication pub in
* person.PublicationList) { foreach (PublicationSource pubSource in
* pub.PublicationSourceList) { if ("PubMed".Equals(pubSource.Name)) {
* pubIds.Add(Int32.Parse(pubSource.ID)); } } } Dictionary<string, Object>
* foundPubs = new Dictionary<string, object>(); foundPubs.Add("pubIds",
* pubIds); foundPubs.Add("message", "PubMedIDs for " +
* person.Name.FullName); JavaScriptSerializer serializer = new
* JavaScriptSerializer(); return serializer.Serialize(foundPubs); }
***/
public void setPubsubData(String key, String value) { public void setPubsubData(String key, String value) {
if (pubsubdata.containsKey(key)) { if (pubsubdata.containsKey(key)) {
@ -374,7 +279,7 @@ public class OpenSocialManager {
String xtraId1Type, String xtraId1Value) throws SQLException { String xtraId1Type, String xtraId1Value) throws SQLException {
Connection conn = null; Connection conn = null;
Statement stmt = null; Statement stmt = null;
String sqlCommand = "INSERT INTO shindig_activity (userId, activity, xtraId1Type, xtraId1Value) VALUES ('" String sqlCommand = "INSERT INTO orng_activity (userId, activity, xtraId1Type, xtraId1Value) VALUES ('"
+ userId + "','<activity xmlns=\"http://ns.opensocial.org/2008/opensocial\"><postedTime>" + userId + "','<activity xmlns=\"http://ns.opensocial.org/2008/opensocial\"><postedTime>"
+ System.currentTimeMillis() + "</postedTime><title>" + title + "</title>" + System.currentTimeMillis() + "</postedTime><title>" + title + "</title>"
+ (body != null ? "<body>" + body + "</body>" : "") + "</activity>','" + (body != null ? "<body>" + body + "</body>" : "") + "</activity>','"
@ -385,18 +290,12 @@ public class OpenSocialManager {
stmt.executeUpdate(sqlCommand); stmt.executeUpdate(sqlCommand);
} finally { } finally {
try { try {
if (stmt != null) { stmt.close();
stmt.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
try { try {
if (conn != null) { conn.close();
conn.close();
}
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace();
} }
} }
@ -427,22 +326,20 @@ public class OpenSocialManager {
// The following will block until the page is transmitted. // The following will block until the page is transmitted.
while ((bytes = s.getInputStream().read(bytesReceived)) > 0) { while ((bytes = s.getInputStream().read(bytesReceived)) > 0) {
page += new String(bytesReceived, 0, bytes); page += new String(bytesReceived, 0, bytes);
} };
return page; return page;
} }
public String getContainerJavascriptSrc() { public String getContainerJavascriptSrc() {
return configuration.getProperty(SHINDIG_URL_PROP) return configuration.getProperty(SHINDIG_URL_PROP)
+ "/gadgets/js/core:dynamic-height:osapi:pubsub:rpc:views:shindig-container.js?c=1" + "/gadgets/js/core:dynamic-height:osapi:pubsub:rpc:views:rdf:shindig-container.js?c=1"
+ (isDebug ? "&debug=1" : ""); + (isDebug ? "&debug=1" : "");
} }
public String getGadgetJavascript() { public String getGadgetJavascript() {
String lineSeparator = System.getProperty("line.separator"); String lineSeparator = System.getProperty("line.separator");
String gadgetScriptText = lineSeparator String gadgetScriptText = "var my = {};" + lineSeparator
+ "var my = {};"
+ lineSeparator
+ "my.gadgetSpec = function(appId, name, url, secureToken, view, closed_width, open_width, start_closed, chrome_id, visible_scope) {" + "my.gadgetSpec = function(appId, name, url, secureToken, view, closed_width, open_width, start_closed, chrome_id, visible_scope) {"
+ lineSeparator + "this.appId = appId;" + lineSeparator + lineSeparator + "this.appId = appId;" + lineSeparator
+ "this.name = name;" + lineSeparator + "this.url = url;" + "this.name = name;" + lineSeparator + "this.url = url;"
@ -480,4 +377,98 @@ public class OpenSocialManager {
return gadgetScriptText; return gadgetScriptText;
} }
Map<String, GadgetSpec> getAllDBGadgets(boolean useCache) throws SQLException
{
// great place to add cache
// check cache first
Map<String, GadgetSpec> allDBGadgets = useCache ? gadgetCache : null;
if (allDBGadgets == null) {
allDBGadgets = new HashMap<String, GadgetSpec>();
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try {
String sqlCommand = "select appId, name, url, channels, enabled from orng_apps";
conn = dataSource.getConnection();
stmt = conn.createStatement();
rset = stmt.executeQuery(sqlCommand);
while (rset.next()) {
String channelsStr = rset.getString(4);
List<String> channels = Arrays.asList(channelsStr != null && channelsStr.length() > 0 ? channelsStr.split(" ") : new String[0]);
GadgetSpec spec = new GadgetSpec(rset.getInt(1),
rset.getString(2), rset.getString(3), channels, dataSource, rset.getBoolean(5), false);
String gadgetFileName = getGadgetFileNameFromURL(rset.getString(3));
allDBGadgets.put(gadgetFileName, spec);
}
}
finally {
try {
rset.close();
} catch (Exception e) {
}
try {
stmt.close();
} catch (Exception e) {
}
try {
conn.close();
} catch (Exception e) {
}
}
if (useCache) {
gadgetCache = allDBGadgets;
}
}
return allDBGadgets;
}
private List<PreparedGadget> getSandboxGadgets(VitroRequest vreq, Map<String, GadgetSpec> allDBGadgets, String requestAppId) throws SQLException, IOException {
List<PreparedGadget> sandboxGadgets = new ArrayList<PreparedGadget>();
// Note that this block of code only gets executed after someone fills in the
// gadget/sandbox form!
String openSocialGadgetURLS = (String) vreq.getSession()
.getAttribute(OPENSOCIAL_GADGETS);
String[] urls = openSocialGadgetURLS.split(System.getProperty("line.separator"));
for (String openSocialGadgetURL : urls) {
if (openSocialGadgetURL.length() == 0)
continue;
int appId = 0; // if URL matches one in the DB, use DB provided
// appId, otherwise generate one
String gadgetFileName = getGadgetFileNameFromURL(openSocialGadgetURL);
String name = gadgetFileName;
List<String> channels = new ArrayList<String>();
boolean unknownGadget = true;
if (allDBGadgets.containsKey(gadgetFileName)) {
appId = allDBGadgets.get(gadgetFileName).getAppId();
name = allDBGadgets.get(gadgetFileName).getName();
channels = allDBGadgets.get(gadgetFileName).getChannels();
unknownGadget = false;
} else {
appId = openSocialGadgetURL.hashCode();
}
// if they asked for a specific one, only let it in
if (requestAppId != null && Integer.parseInt(requestAppId) != appId) {
continue;
}
GadgetSpec gadget = new GadgetSpec(appId, name,
openSocialGadgetURL, channels, dataSource, true, unknownGadget);
// only add ones that are visible in this context!
int moduleId = 0;
if (unknownGadget
|| gadget.show(viewerId, ownerId, pageName, dataSource)) {
String securityToken = socketSendReceive(viewerId, ownerId,
"" + gadget.getAppId());
sandboxGadgets.add(new PreparedGadget(gadget, this, moduleId++,
securityToken));
}
}
return sandboxGadgets;
}
} }

View file

@ -44,7 +44,7 @@ public class OpenSocialSmokeTests implements ServletContextListener {
private static final String PROPERTY_DB_USERNAME = "VitroConnection.DataSource.username"; private static final String PROPERTY_DB_USERNAME = "VitroConnection.DataSource.username";
private static final String PROPERTY_DB_PASSWORD = "VitroConnection.DataSource.password"; private static final String PROPERTY_DB_PASSWORD = "VitroConnection.DataSource.password";
private static final String FILENAME_SHINDIG_PROPERTIES = "shindig.orng.properties"; private static final String FILENAME_SHINDIG_PROPERTIES = "shindigorng.properties";
/* /*
* If a connection fails in the tester thread, how long do we wait before * If a connection fails in the tester thread, how long do we wait before
@ -133,7 +133,7 @@ public class OpenSocialSmokeTests implements ServletContextListener {
conn = dataSource.getConnection(); conn = dataSource.getConnection();
stmt = conn.createStatement(); stmt = conn.createStatement();
rset = stmt.executeQuery("select * from shindig_apps"); rset = stmt.executeQuery("select * from orng_apps");
} catch (NoSuchPropertyException e) { } catch (NoSuchPropertyException e) {
warnings.add(new Warning(e.getMessage())); warnings.add(new Warning(e.getMessage()));
} catch (SQLException e) { } catch (SQLException e) {
@ -182,8 +182,7 @@ public class OpenSocialSmokeTests implements ServletContextListener {
message += "Has the Tomcat classpath been set to include the " message += "Has the Tomcat classpath been set to include the "
+ "Shindig config directory? " + "Shindig config directory? "
+ "(inside the Vitro home directory) "; + "(inside the Vitro home directory) ";
message += "Was the openSocial build script run? " message += "Was the openSocial build script run? ('ant orng')";
+ "('ant -file openSocialBuild.xml')";
warnings.add(new Warning(message)); warnings.add(new Warning(message));
} }
} }
@ -346,12 +345,14 @@ public class OpenSocialSmokeTests implements ServletContextListener {
private static final int SOCKET_TIMEOUT_STATUS = -500; private static final int SOCKET_TIMEOUT_STATUS = -500;
private final String shindigBaseUrl; private final String shindigBaseUrl;
private final String shindigTestUrl;
private final HttpClient httpClient = new HttpClient(); private final HttpClient httpClient = new HttpClient();
private int statusCode = Integer.MIN_VALUE; private int statusCode = Integer.MIN_VALUE;
public ShindigTester(String shindigBaseUrl) { public ShindigTester(String shindigBaseUrl) {
this.shindigBaseUrl = shindigBaseUrl; this.shindigBaseUrl = shindigBaseUrl;
this.shindigTestUrl = shindigBaseUrl + "/rest/appdata";
} }
public void connect() throws ShindigTesterException { public void connect() throws ShindigTesterException {
@ -368,12 +369,12 @@ public class OpenSocialSmokeTests implements ServletContextListener {
} }
if (statusCode != HttpStatus.SC_OK) { if (statusCode != HttpStatus.SC_OK) {
throw new ShindigTesterException(statusCode); throw new ShindigTesterException(statusCode, shindigBaseUrl,
shindigTestUrl);
} }
} }
private void testConnection() throws ShindigTesterException { private void testConnection() throws ShindigTesterException {
String shindigTestUrl = shindigBaseUrl + "/rest/activities";
GetMethod method = new GetMethod(shindigTestUrl); GetMethod method = new GetMethod(shindigTestUrl);
try { try {
log.debug("Trying to connect to Shindig"); log.debug("Trying to connect to Shindig");
@ -388,7 +389,8 @@ public class OpenSocialSmokeTests implements ServletContextListener {
// Save the status so we know why we failed. // Save the status so we know why we failed.
statusCode = SOCKET_TIMEOUT_STATUS; statusCode = SOCKET_TIMEOUT_STATUS;
} catch (Exception e) { } catch (Exception e) {
throw new ShindigTesterException(e); throw new ShindigTesterException(e, shindigBaseUrl,
shindigTestUrl);
} finally { } finally {
method.releaseConnection(); method.releaseConnection();
} }
@ -415,14 +417,18 @@ public class OpenSocialSmokeTests implements ServletContextListener {
protected static class ShindigTesterException extends Exception { protected static class ShindigTesterException extends Exception {
private final int httpStatusCode; private final int httpStatusCode;
protected ShindigTesterException(Integer httpStatusCode) { protected ShindigTesterException(Integer httpStatusCode,
super("Failed to connect to the Shindig service. " String baseUrl, String testUrl) {
super("Failed to connect to the Shindig service at '" + baseUrl
+ "' (tried for a response at '" + testUrl + "'). "
+ "status code was " + httpStatusCode); + "status code was " + httpStatusCode);
this.httpStatusCode = httpStatusCode; this.httpStatusCode = httpStatusCode;
} }
protected ShindigTesterException(Throwable cause) { protected ShindigTesterException(Throwable cause, String baseUrl,
super("Failed to connect to the Shindig service.", cause); String testUrl) {
super("Failed to connect to the Shindig service at '" + baseUrl
+ "' (tried for a response at '" + testUrl + "').", cause);
this.httpStatusCode = Integer.MIN_VALUE; this.httpStatusCode = Integer.MIN_VALUE;
} }

View file

@ -1327,13 +1327,10 @@
</servlet> </servlet>
<servlet-mapping> <servlet-mapping>
<servlet-name>GadgetController</servlet-name> <servlet-name>GadgetController</servlet-name>
<url-pattern>/gadget</url-pattern> <url-pattern>/orng/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>GadgetController</servlet-name>
<url-pattern>/gadget/sandbox</url-pattern>
</servlet-mapping> </servlet-mapping>
<!-- ==================== tag libraries ============================== --> <!-- ==================== tag libraries ============================== -->
<jsp-config> <jsp-config>
<taglib> <taglib>

View file

@ -1,457 +1,457 @@
/* /*
Profiles Shindig Helper functions for gadget-to-container commands ORNG Shindig Helper functions for gadget-to-container commands
*/ */
// dummy function so google analytics does not break for institutions who do not use it // dummy function so google analytics does not break for institutions who do not use it
_gaq = {}; _gaq = {};
_gaq.push = function(data) { // _gaq.push = function(data) { //
}; };
// pubsub // pubsub
gadgets.pubsubrouter.init(function(id) { gadgets.pubsubrouter.init(function(id) {
return my.gadgets[shindig.container.gadgetService.getGadgetIdFromModuleId(id)].url; return my.gadgets[shindig.container.gadgetService.getGadgetIdFromModuleId(id)].url;
}, { }, {
onSubscribe: function(sender, channel) { onSubscribe: function(sender, channel) {
setTimeout("my.onSubscribe('" + sender + "', '" + channel + "')", 3000); setTimeout("my.onSubscribe('" + sender + "', '" + channel + "')", 3000);
// return true to reject the request. // return true to reject the request.
return false; return false;
}, },
onUnsubscribe: function(sender, channel) { onUnsubscribe: function(sender, channel) {
//alert(sender + " unsubscribes from channel '" + channel + "'"); //alert(sender + " unsubscribes from channel '" + channel + "'");
// return true to reject the request. // return true to reject the request.
return false; return false;
}, },
onPublish: function(sender, channel, message) { onPublish: function(sender, channel, message) {
// return true to reject the request. // return true to reject the request.
// track with google analytics // track with google analytics
if (sender != '..' ) { if (sender != '..' ) {
var moduleId = shindig.container.gadgetService.getGadgetIdFromModuleId(sender); var moduleId = shindig.container.gadgetService.getGadgetIdFromModuleId(sender);
} }
if (channel == 'VISIBLE') { if (channel == 'VISIBLE') {
var statusId = document.getElementById(sender + '_status'); var statusId = document.getElementById(sender + '_status');
if (statusId) { if (statusId) {
// only act on these in HOME view since they are only meant to be seen when viewer=owner // only act on these in HOME view since they are only meant to be seen when viewer=owner
if (my.gadgets[moduleId].view != 'home') { if (my.gadgets[moduleId].view != 'home') {
return true; return true;
} }
if (message == 'Y') { if (message == 'Y') {
/* statusId.style.color = 'GREEN'; /* statusId.style.color = 'GREEN';
statusId.innerHTML = 'This section is VISIBLE'; statusId.innerHTML = 'This section is VISIBLE';
if (my.gadgets[moduleId].visible_scope == 'U') { if (my.gadgets[moduleId].visible_scope == 'U') {
statusId.innerHTML += ' to UCSF'; statusId.innerHTML += ' to UCSF';
} }
else { else {
statusId.innerHTML += ' to the public'; statusId.innerHTML += ' to the public';
} }
*/ */
/* changed the gui here -- tlw72 */ /* changed the gui here -- tlw72 */
statusId.style.color = '#5e6363'; statusId.style.color = '#5e6363';
statusId.innerHTML = 'public'; statusId.innerHTML = 'public';
} }
else { else {
/* statusId.style.color = '#CC0000'; /* statusId.style.color = '#CC0000';
statusId.innerHTML = 'This section is HIDDEN'; statusId.innerHTML = 'This section is HIDDEN';
if (my.gadgets[moduleId].visible_scope == 'U') { if (my.gadgets[moduleId].visible_scope == 'U') {
statusId.innerHTML += ' from UCSF'; statusId.innerHTML += ' from UCSF';
} }
else { else {
statusId.innerHTML += ' from the public'; statusId.innerHTML += ' from the public';
} }
*/ */
/* changed the gui here -- tlw72 */ /* changed the gui here -- tlw72 */
statusId.style.color = '#5e6363'; statusId.style.color = '#5e6363';
statusId.innerHTML = 'private'; statusId.innerHTML = 'private';
} }
} }
} }
else if (channel == 'added' && my.gadgets[moduleId].view == 'home') { else if (channel == 'added' && my.gadgets[moduleId].view == 'home') {
if (message == 'Y') { if (message == 'Y') {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'SHOW', 'profile_edit_view']); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'SHOW', 'profile_edit_view']);
osapi.activities.create( osapi.activities.create(
{ 'userId': gadgets.util.getUrlParameters()['Person'], { 'userId': gadgets.util.getUrlParameters()['Person'],
'appId': my.gadgets[moduleId].appId, 'appId': my.gadgets[moduleId].appId,
'activity': {'postedTime': new Date().getTime(), 'title': 'added a gadget', 'body': 'added the ' + my.gadgets[moduleId].name + ' gadget to their profile' } 'activity': {'postedTime': new Date().getTime(), 'title': 'added a gadget', 'body': 'added the ' + my.gadgets[moduleId].name + ' gadget to their profile' }
}).execute(function(response){}); }).execute(function(response){});
} }
else { else {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'HIDE', 'profile_edit_view']); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'HIDE', 'profile_edit_view']);
} }
} }
else if (channel == 'status') { else if (channel == 'status') {
// message should be of the form 'COLOR:Message Content' // message should be of the form 'COLOR:Message Content'
var statusId = document.getElementById(sender + '_status'); var statusId = document.getElementById(sender + '_status');
if (statusId) { if (statusId) {
var messageSplit = message.split(':'); var messageSplit = message.split(':');
if (messageSplit.length == 2) { if (messageSplit.length == 2) {
statusId.style.color = messageSplit[0]; statusId.style.color = messageSplit[0];
statusId.innerHTML = messageSplit[1]; statusId.innerHTML = messageSplit[1];
} }
else { else {
statusId.innerHTML = message; statusId.innerHTML = message;
} }
} }
} }
else if (channel == 'analytics') { else if (channel == 'analytics') {
// publish to google analytics // publish to google analytics
// message should be JSON encoding object with required action and optional label and value // message should be JSON encoding object with required action and optional label and value
// as documented here: http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html // as documented here: http://code.google.com/apis/analytics/docs/tracking/eventTrackerGuide.html
// note that event category will be set to the gadget name automatically by this code // note that event category will be set to the gadget name automatically by this code
// Note: message will be already converted to an object // Note: message will be already converted to an object
if (message.hasOwnProperty('value')) { if (message.hasOwnProperty('value')) {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action, message.label, message.value]); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action, message.label, message.value]);
} }
else if (message.hasOwnProperty('label')) { else if (message.hasOwnProperty('label')) {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action, message.label]); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action, message.label]);
} }
else { else {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action]); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, message.action]);
} }
} }
else if (channel == 'profile') { else if (channel == 'profile') {
_gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'go_to_profile', message]); _gaq.push(['_trackEvent', my.gadgets[moduleId].name, 'go_to_profile', message]);
document.location.href = '/' + location.pathname.split('/')[1] + '/display/n' + message; document.location.href = '/' + location.pathname.split('/')[1] + '/display/n' + message;
} }
else if (channel == 'JSONPersonIds' || channel == 'JSONPubMedIds') { else if (channel == 'JSONPersonIds' || channel == 'JSONPubMedIds') {
// do nothing, no need to alert // do nothing, no need to alert
} }
else { else {
alert(sender + " publishes '" + message + "' to channel '" + channel + "'"); alert(sender + " publishes '" + message + "' to channel '" + channel + "'");
} }
return false; return false;
} }
}); });
// helper functions // helper functions
my.findGadgetsAttachingTo = function(chromeId) { my.findGadgetsAttachingTo = function(chromeId) {
var retval = []; var retval = [];
for (var i = 0; i < my.gadgets.length; i++) { for (var i = 0; i < my.gadgets.length; i++) {
if (my.gadgets[i].chrome_id == chromeId) { if (my.gadgets[i].chrome_id == chromeId) {
retval[retval.length] = my.gadgets[i]; retval[retval.length] = my.gadgets[i];
} }
} }
return retval; return retval;
}; };
my.removeGadgets = function(gadgetsToRemove) { my.removeGadgets = function(gadgetsToRemove) {
for (var i = 0; i < gadgetsToRemove.length; i++) { for (var i = 0; i < gadgetsToRemove.length; i++) {
for (var j = 0; j < my.gadgets.length; j++) { for (var j = 0; j < my.gadgets.length; j++) {
if (gadgetsToRemove[i].url == my.gadgets[j].url) { if (gadgetsToRemove[i].url == my.gadgets[j].url) {
my.gadgets.splice(j, 1); my.gadgets.splice(j, 1);
break; break;
} }
} }
} }
}; };
my.onSubscribe = function(sender, channel) { my.onSubscribe = function(sender, channel) {
// lookup pubsub data based on channel and if a match is found, publish the data to that channel after a delay // lookup pubsub data based on channel and if a match is found, publish the data to that channel after a delay
if (my.pubsubData[channel]) { if (my.pubsubData[channel]) {
gadgets.pubsubrouter.publish(channel, my.pubsubData[channel]); gadgets.pubsubrouter.publish(channel, my.pubsubData[channel]);
} }
else { else {
alert(sender + " subscribes to channel '" + channel + "'"); alert(sender + " subscribes to channel '" + channel + "'");
} }
//PageMethods.onSubscribe(sender, channel, my.pubsubHint, my.CallSuccess, my.CallFailed); //PageMethods.onSubscribe(sender, channel, my.pubsubHint, my.CallSuccess, my.CallFailed);
}; };
my.removeParameterFromURL = function(url, parameter) { my.removeParameterFromURL = function(url, parameter) {
var urlparts= url.split('?'); // prefer to use l.search if you have a location/link object var urlparts= url.split('?'); // prefer to use l.search if you have a location/link object
if (urlparts.length>=2) { if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'='; var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g); var pars= urlparts[1].split(/[&;]/g);
for (var i= pars.length; i-->0;) //reverse iteration as may be destructive for (var i= pars.length; i-->0;) //reverse iteration as may be destructive
if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith if (pars[i].lastIndexOf(prefix, 0)!==-1) //idiom for string.startsWith
pars.splice(i, 1); pars.splice(i, 1);
url= urlparts[0]+'?'+pars.join('&'); url= urlparts[0]+'?'+pars.join('&');
} }
return url; return url;
}; };
// publish the people // publish the people
my.CallSuccess = function(result) { my.CallSuccess = function(result) {
gadgets.pubsubrouter.publish('person', result); gadgets.pubsubrouter.publish('person', result);
}; };
// alert message on some failure // alert message on some failure
my.CallFailed = function(error) { my.CallFailed = function(error) {
alert(error.get_message()); alert(error.get_message());
}; };
my.requestGadgetMetaData = function(view, opt_callback) { my.requestGadgetMetaData = function(view, opt_callback) {
var request = { var request = {
context: { context: {
country: "default", country: "default",
language: "default", language: "default",
view: view, view: view,
ignoreCache : my.noCache, ignoreCache : my.noCache,
container: "default" container: "default"
}, },
gadgets: [] gadgets: []
}; };
for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) { for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) {
// only add those with matching views // only add those with matching views
if (my.gadgets[moduleId].view == view) { if (my.gadgets[moduleId].view == view) {
request.gadgets[request.gadgets.length] = {'url': my.gadgets[moduleId].url, 'moduleId': moduleId}; request.gadgets[request.gadgets.length] = {'url': my.gadgets[moduleId].url, 'moduleId': moduleId};
} }
} }
var makeRequestParams = { var makeRequestParams = {
"CONTENT_TYPE" : "JSON", "CONTENT_TYPE" : "JSON",
"METHOD" : "POST", "METHOD" : "POST",
"POST_DATA" : gadgets.json.stringify(request)}; "POST_DATA" : gadgets.json.stringify(request)};
gadgets.io.makeNonProxiedRequest(my.openSocialURL + "/gadgets/metadata", gadgets.io.makeNonProxiedRequest(my.openSocialURL + "/gadgets/metadata",
function(data) { function(data) {
data = data.data; data = data.data;
if (opt_callback) { if (opt_callback) {
opt_callback(data); opt_callback(data);
} }
}, },
makeRequestParams, makeRequestParams,
"application/javascript" "application/javascript"
); );
}; };
my.renderableGadgets = []; my.renderableGadgets = [];
my.generateGadgets = function(metadata) { my.generateGadgets = function(metadata) {
// put them in moduleId order // put them in moduleId order
for (var i = 0; i < metadata.gadgets.length; i++) { for (var i = 0; i < metadata.gadgets.length; i++) {
var moduleId = metadata.gadgets[i].moduleId; var moduleId = metadata.gadgets[i].moduleId;
// Notes by Eric. Not sure if I should have to calculate this myself, but I will. // Notes by Eric. Not sure if I should have to calculate this myself, but I will.
var height = metadata.gadgets[i].height; var height = metadata.gadgets[i].height;
var width = metadata.gadgets[i].width; var width = metadata.gadgets[i].width;
var viewPrefs = metadata.gadgets[i].views[my.gadgets[moduleId].view]; var viewPrefs = metadata.gadgets[i].views[my.gadgets[moduleId].view];
if (viewPrefs) { if (viewPrefs) {
height = viewPrefs.preferredHeight || height; height = viewPrefs.preferredHeight || height;
width = viewPrefs.preferredWidth || width; width = viewPrefs.preferredWidth || width;
} }
my.renderableGadgets[moduleId] = shindig.container.createGadget({'specUrl': metadata.gadgets[i].url, 'secureToken': my.gadgets[moduleId].secureToken, my.renderableGadgets[moduleId] = shindig.container.createGadget({'specUrl': metadata.gadgets[i].url, 'secureToken': my.gadgets[moduleId].secureToken,
'title': metadata.gadgets[i].title, 'userPrefs': metadata.gadgets[i].userPrefs, 'title': metadata.gadgets[i].title, 'userPrefs': metadata.gadgets[i].userPrefs,
'height': height, 'width': width, 'debug': my.debug}); 'height': height, 'width': width, 'debug': my.debug});
// set the metadata for easy access // set the metadata for easy access
my.renderableGadgets[moduleId].setMetadata(metadata.gadgets[i]); my.renderableGadgets[moduleId].setMetadata(metadata.gadgets[i]);
} }
// this will be called multiple times, only render when all gadgets have been processed // this will be called multiple times, only render when all gadgets have been processed
var ready = my.renderableGadgets.length == my.gadgets.length; var ready = my.renderableGadgets.length == my.gadgets.length;
for (var i = 0; ready && i < my.renderableGadgets.length; i++) { for (var i = 0; ready && i < my.renderableGadgets.length; i++) {
if (!my.renderableGadgets[i]) { if (!my.renderableGadgets[i]) {
ready = false; ready = false;
} }
} }
if (ready) { if (ready) {
shindig.container.addGadgets(my.renderableGadgets ); shindig.container.addGadgets(my.renderableGadgets );
shindig.container.renderGadgets(); shindig.container.renderGadgets();
} }
}; };
my.init = function() { my.init = function() {
// overwrite this RPC function. Do it at this level so that rpc.f (this.f) is accessible for getting module ID // overwrite this RPC function. Do it at this level so that rpc.f (this.f) is accessible for getting module ID
// gadgets.rpc.register('requestNavigateTo', doProfilesNavigation); // gadgets.rpc.register('requestNavigateTo', doOrngNavigation);
shindig.container.gadgetClass = ProfilesGadget; shindig.container.gadgetClass = OrngGadget;
shindig.container.layoutManager = new ProfilesLayoutManager(); shindig.container.layoutManager = new OrngLayoutManager();
shindig.container.setNoCache(my.noCache); shindig.container.setNoCache(my.noCache);
shindig.container.gadgetService = new ProfilesGadgetService(); shindig.container.gadgetService = new OrngGadgetService();
// since we render multiple views, we need to do somethign fancy by swapping out this value in getIframeUrl // since we render multiple views, we need to do somethign fancy by swapping out this value in getIframeUrl
shindig.container.setView('REPLACE_THIS_VIEW'); shindig.container.setView('REPLACE_THIS_VIEW');
// do multiple times as needed if we have multiple views // do multiple times as needed if we have multiple views
// find out what views are being used and call requestGadgetMetaData for each one // find out what views are being used and call requestGadgetMetaData for each one
var views = {}; var views = {};
for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) { for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) {
var view = my.gadgets[moduleId].view; var view = my.gadgets[moduleId].view;
if (!views[view]) { if (!views[view]) {
views[view] = view; views[view] = view;
my.requestGadgetMetaData(view, my.generateGadgets); my.requestGadgetMetaData(view, my.generateGadgets);
} }
} }
}; };
// ProfilesGadgetService // OrngGadgetService
ProfilesGadgetService = function() { OrngGadgetService = function() {
shindig.IfrGadgetService.call(this); shindig.IfrGadgetService.call(this);
}; };
ProfilesGadgetService.inherits(shindig.IfrGadgetService); OrngGadgetService.inherits(shindig.IfrGadgetService);
ProfilesGadgetService.prototype.requestNavigateTo = function(view, opt_params) { OrngGadgetService.prototype.requestNavigateTo = function(view, opt_params) {
var urlTemplate = gadgets.config.get('views')[view].urlTemplate; var viewConfig = gadgets.config.get('views')[view];
var url = urlTemplate || 'OpenSocial.aspx?'; var url = viewConfig.urlTemplate;
url += window.location.search.substring(1); url += window.location.search.substring(1);
// remove appId if present // remove appId if present
url = my.removeParameterFromURL(url, 'appId'); url = my.removeParameterFromURL(url, 'appId');
// Add appId if the URL Template begins with the word 'gadget' // Add appId if isOnlyVisible is TRUE for this view
if (urlTemplate.toLowerCase().indexOf('gadget') == 0) { if (viewConfig.isOnlyVisible) {
var moduleId = shindig.container.gadgetService.getGadgetIdFromModuleId(this.f); var moduleId = shindig.container.gadgetService.getGadgetIdFromModuleId(this.f);
var appId = my.gadgets[moduleId].appId; var appId = my.gadgets[moduleId].appId;
url += (url.indexOf('?') != url.length - 1 ? '&' : '') + 'appId=' + appId; url += (url.indexOf('?') != url.length - 1 ? '&' : '') + 'appId=' + appId;
} }
if (opt_params) { if (opt_params) {
var paramStr = gadgets.json.stringify(opt_params); var paramStr = gadgets.json.stringify(opt_params);
if (paramStr.length > 0) { if (paramStr.length > 0) {
url += (url.indexOf('?') != url.length - 1 ? '&' : '') + 'appParams=' + encodeURIComponent(paramStr); url += (url.indexOf('?') != url.length - 1 ? '&' : '') + 'appParams=' + encodeURIComponent(paramStr);
} }
} }
if (url && document.location.href.indexOf(url) == -1) { if (url && document.location.href.indexOf(url) == -1) {
document.location.href = url; document.location.href = url;
} }
}; };
// ProfilesGadget // OrngGadget
ProfilesGadget = function(opt_params) { OrngGadget = function(opt_params) {
shindig.Gadget.call(this, opt_params); shindig.Gadget.call(this, opt_params);
this.debug = my.debug; this.debug = my.debug;
this.serverBase_ = my.openSocialURL + "/gadgets/"; this.serverBase_ = my.openSocialURL + "/gadgets/";
var gadget = this; var gadget = this;
var subClass = shindig.IfrGadget; var subClass = shindig.IfrGadget;
this.metadata = {}; this.metadata = {};
for (var name in subClass) if (subClass.hasOwnProperty(name)) { for (var name in subClass) if (subClass.hasOwnProperty(name)) {
if (name == 'getIframeUrl') { if (name == 'getIframeUrl') {
// we need to keep this old one // we need to keep this old one
gadget['originalGetIframeUrl'] = subClass[name]; gadget['originalGetIframeUrl'] = subClass[name];
} }
else if (name != 'finishRender') { else if (name != 'finishRender') {
gadget[name] = subClass[name]; gadget[name] = subClass[name];
} }
} }
}; };
ProfilesGadget.inherits(shindig.BaseIfrGadget); OrngGadget.inherits(shindig.BaseIfrGadget);
ProfilesGadget.prototype.setMetadata = function(metadata) { OrngGadget.prototype.setMetadata = function(metadata) {
this.metadata = metadata; this.metadata = metadata;
}; };
ProfilesGadget.prototype.hasFeature = function(feature) { OrngGadget.prototype.hasFeature = function(feature) {
for (var i = 0; i < this.metadata.features.length; i++) { for (var i = 0; i < this.metadata.features.length; i++) {
if (this.metadata.features[i] == feature) { if (this.metadata.features[i] == feature) {
return true; return true;
} }
} }
return false; return false;
}; };
ProfilesGadget.prototype.getAdditionalParams = function() { OrngGadget.prototype.getAdditionalParams = function() {
var params = ''; var params = '';
for (var key in my.gadgets[this.id].additionalParams) { for (var key in my.gadgets[this.id].additionalParams) {
params += '&' + key + '=' + my.gadgets[this.id].additionalParams[key]; params += '&' + key + '=' + my.gadgets[this.id].additionalParams[key];
} }
return params; return params;
}; };
ProfilesGadget.prototype.finishRender = function(chrome) { OrngGadget.prototype.finishRender = function(chrome) {
window.frames[this.getIframeId()].location = this.getIframeUrl(); window.frames[this.getIframeId()].location = this.getIframeUrl();
if (my.gadgets[this.id].start_closed) { if (my.gadgets[this.id].start_closed) {
this.handleToggle(); this.handleToggle();
} }
else if (chrome) { else if (chrome) {
// set the gadget box width, and remember that we always render as open // set the gadget box width, and remember that we always render as open
chrome.style.width = (my.gadgets[this.id].open_width || 600) + 'px'; chrome.style.width = (my.gadgets[this.id].open_width || 600) + 'px';
} }
}; };
ProfilesGadget.prototype.getIframeUrl = function() { OrngGadget.prototype.getIframeUrl = function() {
var url = this.originalGetIframeUrl(); var url = this.originalGetIframeUrl();
return url.replace('REPLACE_THIS_VIEW', my.gadgets[this.id].view); return url.replace('REPLACE_THIS_VIEW', my.gadgets[this.id].view);
}; };
ProfilesGadget.prototype.handleToggle = function() { OrngGadget.prototype.handleToggle = function() {
var gadgetIframe = document.getElementById(this.getIframeId()); var gadgetIframe = document.getElementById(this.getIframeId());
if (gadgetIframe) { if (gadgetIframe) {
var gadgetContent = gadgetIframe.parentNode; var gadgetContent = gadgetIframe.parentNode;
var gadgetImg = document.getElementById('gadgets-gadget-title-image-' + this.id); var gadgetImg = document.getElementById('gadgets-gadget-title-image-' + this.id);
if (gadgetContent.style.display) { if (gadgetContent.style.display) {
//OPEN //OPEN
gadgetContent.parentNode.style.width = (my.gadgets[this.id].open_width || 600) + 'px'; gadgetContent.parentNode.style.width = (my.gadgets[this.id].open_width || 600) + 'px';
gadgetContent.style.display = ''; gadgetContent.style.display = '';
gadgetImg.src = '/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_minus_sign.gif'; gadgetImg.src = '/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_minus_sign.gif';
// refresh if certain features require so // refresh if certain features require so
//if (this.hasFeature('dynamic-height')) { //if (this.hasFeature('dynamic-height')) {
if (my.gadgets[this.id].chrome_id == 'gadgets-search') { if (my.gadgets[this.id].chrome_id == 'gadgets-search') {
this.refresh(); this.refresh();
document.getElementById(this.getIframeId()).contentWindow.location.reload(true); document.getElementById(this.getIframeId()).contentWindow.location.reload(true);
} }
if (my.gadgets[this.id].view == 'home') { if (my.gadgets[this.id].view == 'home') {
// record in google analytics // record in google analytics
_gaq.push(['_trackEvent', my.gadgets[this.id].name, 'OPEN_IN_EDIT', 'profile_edit_view']); _gaq.push(['_trackEvent', my.gadgets[this.id].name, 'OPEN_IN_EDIT', 'profile_edit_view']);
} }
else { else {
osapi.activities.create( osapi.activities.create(
{ 'userId': gadgets.util.getUrlParameters()['Person'], { 'userId': gadgets.util.getUrlParameters()['Person'],
'appId': my.gadgets[this.id].appId, 'appId': my.gadgets[this.id].appId,
'activity': {'postedTime': new Date().getTime(), 'title': 'gadget viewed', 'body': my.gadgets[this.id].name + ' gadget was viewed' } 'activity': {'postedTime': new Date().getTime(), 'title': 'gadget viewed', 'body': my.gadgets[this.id].name + ' gadget was viewed' }
}).execute(function(response){}); }).execute(function(response){});
// record in google analytics // record in google analytics
_gaq.push(['_trackEvent', my.gadgets[this.id].name, 'OPEN']); _gaq.push(['_trackEvent', my.gadgets[this.id].name, 'OPEN']);
} }
} }
else { else {
//CLOSE //CLOSE
gadgetContent.parentNode.style.width = (my.gadgets[this.id].closed_width || 600) + 'px'; gadgetContent.parentNode.style.width = (my.gadgets[this.id].closed_width || 600) + 'px';
gadgetContent.style.display = 'none'; gadgetContent.style.display = 'none';
gadgetImg.src = '/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_plus_sign.gif'; gadgetImg.src = '/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_plus_sign.gif';
if (my.gadgets[this.id].view == 'home') { if (my.gadgets[this.id].view == 'home') {
// record in google analytics // record in google analytics
_gaq.push(['_trackEvent', my.gadgets[this.id].name, 'CLOSE_IN_EDIT', 'profile_edit_view']); _gaq.push(['_trackEvent', my.gadgets[this.id].name, 'CLOSE_IN_EDIT', 'profile_edit_view']);
} }
else { else {
// record in google analytics // record in google analytics
_gaq.push(['_trackEvent', my.gadgets[this.id].name, 'CLOSE']); _gaq.push(['_trackEvent', my.gadgets[this.id].name, 'CLOSE']);
} }
} }
} }
}; };
ProfilesGadget.prototype.getTitleBarContent = function(continuation) { OrngGadget.prototype.getTitleBarContent = function(continuation) {
if (my.gadgets[this.id].view == 'canvas') { if (my.gadgets[this.id].view == 'canvas') {
document.getElementById("gadgets-title").innerHTML = (this.title ? this.title : 'Gadget'); document.getElementById("gadgets-title").innerHTML = (this.title ? this.title : 'Gadget');
continuation('<span class="gadgets-gadget-canvas-title"></span>'); continuation('<span class="gadgets-gadget-canvas-title"></span>');
} }
else { else {
continuation( continuation(
'<div id="' + this.cssClassTitleBar + '-' + this.id + '<div id="' + this.cssClassTitleBar + '-' + this.id +
'" class="' + this.cssClassTitleBar + '"><span class="' + '" class="' + this.cssClassTitleBar + '"><span class="' +
this.cssClassTitleButtonBar + '">' + this.cssClassTitleButtonBar + '">' +
'<a href="#" onclick="shindig.container.getGadget(' + this.id + '<a href="#" onclick="shindig.container.getGadget(' + this.id +
').handleToggle();return false;" class="' + this.cssClassTitleButton + ').handleToggle();return false;" class="' + this.cssClassTitleButton +
'"><img id="gadgets-gadget-title-image-' + this.id + '" src="/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_minus_sign.gif"/></a></span> <span id="' + '"><img id="gadgets-gadget-title-image-' + this.id + '" src="/' + location.pathname.split('/')[1] + '/themes/wilma/images/green_minus_sign.gif"/></a></span> <span id="' +
this.getIframeId() + '_title" class="' + this.cssClassTitle + '">' + this.getIframeId() + '_title" class="' + this.cssClassTitle + '">' +
'<a href="#" onclick="shindig.container.getGadget(' + this.id + ').handleToggle();return false;">' + '<a href="#" onclick="shindig.container.getGadget(' + this.id + ').handleToggle();return false;">' +
(this.title ? this.title : 'Gadget') + '</a>' + '</span><span id="' + (this.title ? this.title : 'Gadget') + '</a>' + '</span><span id="' +
this.getIframeId() + '_status" class="gadgets-gadget-status"></span></div>'); this.getIframeId() + '_status" class="gadgets-gadget-status"></span></div>');
} }
}; };
// ProfilesLayoutManager. Creates a FloatLeftLayoutManager for every chromeId in our gadgets // OrngLayoutManager. Creates a FloatLeftLayoutManager for every chromeId in our gadgets
ProfilesLayoutManager = function() { OrngLayoutManager = function() {
shindig.LayoutManager.call(this); shindig.LayoutManager.call(this);
// find out what chromeId's are being used, create a FloatLeftLayoutManager for each // find out what chromeId's are being used, create a FloatLeftLayoutManager for each
this.layoutManagers = {}; this.layoutManagers = {};
for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) { for (var moduleId = 0; moduleId < my.gadgets.length; moduleId++) {
var chromeId = my.gadgets[moduleId].chrome_id; var chromeId = my.gadgets[moduleId].chrome_id;
if (!this.layoutManagers[chromeId]) { if (!this.layoutManagers[chromeId]) {
this.layoutManagers[chromeId] = new shindig.FloatLeftLayoutManager(chromeId); this.layoutManagers[chromeId] = new shindig.FloatLeftLayoutManager(chromeId);
} }
} }
}; };
ProfilesLayoutManager.inherits(shindig.LayoutManager); OrngLayoutManager.inherits(shindig.LayoutManager);
ProfilesLayoutManager.prototype.getGadgetChrome = function(gadget) { OrngLayoutManager.prototype.getGadgetChrome = function(gadget) {
return this.layoutManagers[my.gadgets[gadget.id].chrome_id].getGadgetChrome(gadget); return this.layoutManagers[my.gadgets[gadget.id].chrome_id].getGadgetChrome(gadget);
}; };