public MessageBundle getBundle(GadgetSpec spec, Locale locale, bool ignoreCache)
        {
            if (ignoreCache)
            {
                return(getNestedBundle(spec, locale, true));
            }

            String key = spec.getUrl().ToString() + '.' + locale.ToString();

            MessageBundle cached = HttpRuntime.Cache[key] as MessageBundle;

            MessageBundle bundle;

            if (cached == null)
            {
                try
                {
                    bundle = getNestedBundle(spec, locale, ignoreCache);
                }
                catch (GadgetException)
                {
                    // Enforce negative caching.
                    bundle = cached ?? MessageBundle.EMPTY;
                }
                HttpRuntime.Cache.Insert(key, bundle, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(refresh));
            }
            else
            {
                bundle = cached;
            }

            return(bundle);
        }
 public PreparedGadget(GadgetSpec gadgetSpec, OpenSocialHelper helper, int moduleId, string securityToken)
 {
     this.gadgetSpec    = gadgetSpec;
     this.helper        = helper;
     this.moduleId      = moduleId;
     this.securityToken = securityToken;
 }
        /**
         * Lookup information contained in the gadget spec.
         */
        private OAuthServiceProvider lookupSpecInfo(ISecurityToken securityToken, OAuthArguments arguments,
                                                    AccessorInfoBuilder accessorBuilder, OAuthResponseParams responseParams)
        {
            GadgetSpec spec      = findSpec(securityToken, arguments, responseParams);
            OAuthSpec  oauthSpec = spec.getModulePrefs().getOAuthSpec();

            if (oauthSpec == null)
            {
                throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
                                                           "Failed to retrieve OAuth URLs, spec for gadget " +
                                                           securityToken.getAppUrl() + " does not contain OAuth element.");
            }
            OAuthService service = oauthSpec.getServices()[arguments.getServiceName()];

            if (service == null)
            {
                throw responseParams.oauthRequestException(OAuthError.BAD_OAUTH_CONFIGURATION,
                                                           "Failed to retrieve OAuth URLs, spec for gadget does not contain OAuth service " +
                                                           arguments.getServiceName() + ".  Known services: " +
                                                           String.Join(",", oauthSpec.getServices().Keys.AsEnumerable().ToArray()) + '.');
            }
            // In theory some one could specify different parameter locations for request token and
            // access token requests, but that's probably not useful.  We just use the request token
            // rules for everything.
            accessorBuilder.setParameterLocation(getStoreLocation(service.getRequestUrl().location, responseParams));
            accessorBuilder.setMethod(getStoreMethod(service.getRequestUrl().method, responseParams));
            OAuthServiceProvider provider = new OAuthServiceProvider(
                service.getRequestUrl().url.ToString(),
                service.getAuthorizationUrl().ToString(),
                service.getAccessUrl().url.ToString());

            return(provider);
        }
        public virtual RewriterResults rewrite(sRequest request, sResponse original, MutableContent content)
        {
            ByteArrayOutputStream baos   = new ByteArrayOutputStream((content.getContent().Length * 110) / 100);
            OutputStreamWriter    output = new OutputStreamWriter(baos);
            String mimeType = original.getHeader("Content-Type");

            if (request.RewriteMimeType != null)
            {
                mimeType = request.RewriteMimeType;
            }
            GadgetSpec spec = null;

            if (request.Gadget != null)
            {
                spec = _specFactory.getGadgetSpec(request.Gadget.toJavaUri(), false);
            }
            if (rewrite(spec, request.getUri(),
                        content,
                        mimeType,
                        output))
            {
                content.setContent(Encoding.Default.GetString(baos.toByteArray()));
                return(RewriterResults.cacheableIndefinitely());
            }

            return(null);
        }
Example #5
0
        /// <summary>
        /// Process a single gadget. Creates a gadget from a retrieved GadgetSpec and context object,
        /// automatically performing variable substitution on the spec for use elsewhere.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Gadget Process(GadgetContext context)
        {
            Uri url = context.getUrl();

            if (url == null)
            {
                throw new ProcessingException("Missing or malformed url parameter");
            }

            if (!url.Scheme.ToLower().Equals("http") && !url.Scheme.ToLower().Equals("https"))
            {
                throw new ProcessingException("Unsupported scheme (must be http or https).");
            }

            if (blacklist.isBlacklisted(context.getUrl()))
            {
                throw new ProcessingException("The requested gadget is unavailable");
            }

            try
            {
                GadgetSpec spec = gadgetSpecFactory.getGadgetSpec(context);
                spec = substituter.substitute(context, spec);

                return(new Gadget()
                       .setContext(context)
                       .setSpec(spec)
                       .setCurrentView(GetView(context, spec)));
            }
            catch (GadgetException e)
            {
                throw new ProcessingException(e.Message, e);
            }
        }
Example #6
0
        /// <summary>
        /// Attempts to extract the "current" view for the given gadget.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="spec"></param>
        /// <returns></returns>
        private View GetView(GadgetContext context, GadgetSpec spec)
        {
            String viewName = context.getView();
            View   view     = spec.getView(viewName);

            if (view == null)
            {
                JsonObject views = containerConfig.GetJsonObject(context.getContainer(), "gadgets.features/views");
                foreach (DictionaryEntry v in views)
                {
                    JsonArray aliases = ((JsonObject)v.Value)["aliases"] as JsonArray;
                    if (aliases != null && view == null)
                    {
                        for (int i = 0, j = aliases.Length; i < j; ++i)
                        {
                            if (viewName == aliases.GetString(i))
                            {
                                view = spec.getView(v.Key.ToString());
                                if (view != null)
                                {
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            if (view == null)
            {
                view = spec.getView(GadgetSpec.DEFAULT_VIEW);
            }

            return(view);
        }
        private MutableContent GetMutableContent(GadgetSpec spec, View v)
        {
            // TODO - Consider using caching here to avoid parse costs
            MutableContent mc = new MutableContent(htmlParser, v.getContent());

            return(mc);
        }
        private bool rewrite(GadgetSpec spec, Uri source, MutableContent mc, String mimeType, java.io.Writer writer)
        {
            // Dont rewrite content if the spec is unavailable
            if (spec == null)
            {
                return(false);
            }

            // Store the feature in the spec so we dont keep parsing it
            ContentRewriterFeature rewriterFeature = new ContentRewriterFeature(spec, includeUrls, excludeUrls, expires, includeTags);

            if (!rewriterFeature.isRewriteEnabled())
            {
                return(false);
            }
            if (isHTML(mimeType))
            {
                Dictionary <String, IHtmlTagTransformer> transformerMap = new Dictionary <string, IHtmlTagTransformer>();

                if (ProxyUrl != null)
                {
                    ILinkRewriter      linkRewriter = CreateLinkRewriter(spec, rewriterFeature);
                    LinkingTagRewriter rewriter     = new LinkingTagRewriter(linkRewriter, source);
                    HashSet <String>   toProcess    = new HashSet <string>();
                    foreach (var item in rewriter.getSupportedTags())
                    {
                        toProcess.Add(item);
                    }

                    toProcess.IntersectWith(rewriterFeature.getIncludedTags());

                    foreach (string tag in toProcess)
                    {
                        transformerMap[tag] = rewriter;
                    }
                    if (rewriterFeature.getIncludedTags().Contains("style"))
                    {
                        transformerMap["style"] = new StyleTagRewriter(source, linkRewriter);
                    }
                }
                if (ConcatUrl != null &&
                    rewriterFeature.getIncludedTags().Contains("script"))
                {
                    transformerMap["script"] = new JavascriptTagMerger(spec, rewriterFeature, ConcatUrl, source);
                }
                HtmlRewriter.rewrite(new StringReader(mc.getContent()), source, transformerMap, writer);
                return(true);
            }
            if (isCSS(mimeType))
            {
                if (ProxyUrl != null)
                {
                    CssRewriter.rewrite(new StringReader(mc.getContent()), source, CreateLinkRewriter(spec, rewriterFeature), writer, false);
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Example #9
0
        /**
         * Render the gadget into a string by performing the following steps:
         *
         * - Retrieve gadget specification information (GadgetSpec, MessageBundle, etc.)
         *
         * - Fetch any preloaded data needed to handle the request, as handled by Preloader.
         *
         * - Perform rewriting operations on the output content, handled by Rewriter.
         *
         * @param gadget The gadget for the rendering operation.
         * @return The rendered gadget content
         * @throws RenderingException if any issues arise that prevent rendering.
         */
        public String render(Gadget gadget)
        {
            try
            {
                View          view    = gadget.getCurrentView();
                GadgetContext context = gadget.getContext();
                GadgetSpec    spec    = gadget.getSpec();

                IPreloads preloads = preloader.preload(context, spec,
                                                       PreloaderService.PreloadPhase.HTML_RENDER);
                gadget.setPreloads(preloads);
                String content;

                if (view.getHref() == null)
                {
                    content = view.getContent();
                }
                else
                {
                    // TODO: Add current url to GadgetContext to support transitive proxying.
                    UriBuilder uri = new UriBuilder(view.getHref());
                    uri.addQueryParameter("lang", context.getLocale().getLanguage());
                    uri.addQueryParameter("country", context.getLocale().getCountry());

                    sRequest request = new sRequest(uri.toUri())
                                       .setIgnoreCache(context.getIgnoreCache())
                                       .setOAuthArguments(new OAuthArguments(view))
                                       .setAuthType(view.getAuthType())
                                       .setSecurityToken(context.getToken())
                                       .setContainer(context.getContainer())
                                       .setGadget(spec.getUrl());
                    sResponse response = DefaultHttpCache.Instance.getResponse(request);

                    if (response == null || response.isStale())
                    {
                        sRequest proxyRequest = createPipelinedProxyRequest(gadget, request);
                        response = requestPipeline.execute(proxyRequest);
                        DefaultHttpCache.Instance.addResponse(request, response);
                    }

                    if (response.isError())
                    {
                        throw new RenderingException("Unable to reach remote host. HTTP status " +
                                                     response.getHttpStatusCode());
                    }
                    content = response.responseString;
                }

                return(rewriter.rewriteGadget(gadget, content));
            }
            catch (GadgetException e)
            {
                throw new RenderingException(e.Message, e);
            }
        }
        private String GetLockedDomain(GadgetSpec gadget, String container)
        {
            String suffix;

            if (!lockedSuffixes.TryGetValue(container, out suffix))
            {
                return(null);
            }
            String hash = SHA1.Create().ComputeHash(Encoding.Default.GetBytes(gadget.getUrl().ToString())).ToString();

            return(hash + suffix);
        }
        public ContentRewriterFeature get(GadgetSpec spec)
        {
            ContentRewriterFeature rewriterFeature =
                (ContentRewriterFeature)spec.getAttribute("content-rewriter");

            if (rewriterFeature != null)
            {
                return(rewriterFeature);
            }
            rewriterFeature = new ContentRewriterFeature(spec, includeUrls, excludeUrls, expires, includeTags);
            spec.setAttribute("content-rewriter", rewriterFeature);
            return(rewriterFeature);
        }
 public String getLockedDomainForGadget(GadgetSpec gadget, String container)
 {
     container = NormalizeContainer(container);
     if (enabled)
     {
         if (GadgetWantsLockedDomain(gadget) ||
             ContainerRequiresLockedDomain(container))
         {
             return(GetLockedDomain(gadget, container));
         }
     }
     return(null);
 }
Example #13
0
        private MessageBundle getParentBundle(GadgetSpec spec, Locale locale, bool ignoreCache)
        {
            if (locale.getLanguage().Equals("all"))
            {
                // Top most locale already.
                return(null);
            }

            if (locale.getCountry().Equals("ALL"))
            {
                return(getBundle(spec, new Locale("all", "ALL"), ignoreCache));
            }

            return(getBundle(spec, new Locale(locale.getLanguage(), "ALL"), ignoreCache));
        }
 public bool gadgetCanRender(String host, GadgetSpec gadget, String container)
 {
     container = NormalizeContainer(container);
     if (enabled)
     {
         if (GadgetWantsLockedDomain(gadget) ||
             HostRequiresLockedDomain(host) ||
             ContainerRequiresLockedDomain(container))
         {
             String neededHost = GetLockedDomain(gadget, container);
             return(host.Equals(neededHost));
         }
     }
     return(true);
 }
        /**
         * @param concatBase Base url of the Concat servlet. Expected to be of the
         *                   form www.host.com/concat?
         * @param relativeUrlBase to resolve relative urls
         */
        public JavascriptTagMerger(GadgetSpec spec, ContentRewriterFeature rewriterFeature,
                                   String concatBase, Uri relativeUrlBase)
        {
            // Force the mime-type to mimic browser expectation so rewriters
            // can function properly
            this.concatBase = concatBase
                              + ProxyBase.REWRITE_MIME_TYPE_PARAM
                              + "=text/javascript&"
                              + "gadget="
                              + HttpUtility.UrlEncode(spec.getUrl().ToString())
                              + "&fp="
                              + rewriterFeature.getFingerprint()
                              + '&';

            this.relativeUrlBase = relativeUrlBase;
        }
Example #16
0
        /**
         * Substitutes all hangman variables into the gadget spec.
         *
         * @return A new GadgetSpec, with all fields substituted as needed.
         */
        public GadgetSpec substitute(GadgetContext context, GadgetSpec spec)
        {
            MessageBundle bundle =
                messageBundleFactory.getBundle(spec, context.getLocale(), context.getIgnoreCache());
            String dir = bundle.getLanguageDirection();

            Substitutions substituter = new Substitutions();

            substituter.addSubstitutions(Substitutions.Type.MESSAGE, bundle.getMessages());
            BidiSubstituter.addSubstitutions(substituter, dir);
            substituter.addSubstitution(Substitutions.Type.MODULE, "ID",
                                        context.getModuleId());
            UserPrefSubstituter.addSubstitutions(substituter, spec, context.getUserPrefs());

            return(spec.substitute(substituter));
        }
Example #17
0
        /**
         * Attempts to render the requested gadget.
         *
         * @return The results of the rendering attempt.
         *
         * TODO: Localize error messages.
         */
        public RenderingResults Render(GadgetContext context)
        {
            if (!ValidateParent(context))
            {
                return(RenderingResults.error("Unsupported parent parameter. Check your container code."));
            }

            try
            {
                Gadget gadget = processor.Process(context);

                if (gadget.getCurrentView() == null)
                {
                    return(RenderingResults.error("Unable to locate an appropriate view in this gadget. " +
                                                  "Requested: '" + gadget.getContext().getView() +
                                                  "' Available: " + String.Join(",", gadget.getSpec().getViews().Keys.ToArray())));
                }

                if (gadget.getCurrentView().getType() == View.ContentType.URL)
                {
                    return(RenderingResults.mustRedirect(getRedirect(gadget)));
                }

                GadgetSpec spec = gadget.getSpec();
                if (!lockedDomainService.gadgetCanRender(context.getHost(), spec, context.getContainer()))
                {
                    return(RenderingResults.mustRedirect(getRedirect(gadget)));
                }
                return(RenderingResults.ok(renderer.render(gadget)));
            }
            catch (RenderingException e)
            {
                return(LogError(context.getUrl(), e));
            }
            catch (ProcessingException e)
            {
                return(LogError(context.getUrl(), e));
            }
            catch (Exception e)
            {
                if (e.GetBaseException() is GadgetException)
                {
                    return(LogError(context.getUrl(), e.GetBaseException()));
                }
                throw;
            }
        }
        public virtual RewriterResults rewrite(Gadget gadget, MutableContent content)
        {
            java.io.StringWriter sw   = new java.io.StringWriter();
            GadgetSpec           spec = gadget.getSpec();
            Uri  _base = spec.getUrl();
            View view  = gadget.getCurrentView();

            if (view != null && view.getHref() != null)
            {
                _base = view.getHref();
            }
            if (rewrite(spec, _base, content, "text/html", sw))
            {
                content.setContent(sw.toString());
            }
            return(null);
        }
 public static void addSubstitutions(Substitutions substituter,
                                     GadgetSpec spec, UserPrefs values)
 {
     foreach (UserPref pref in spec.getUserPrefs())
     {
         String name  = pref.getName();
         String value = values.getPref(name);
         if (value == null)
         {
             value = pref.getDefaultValue();
             if (value == null)
             {
                 value = "";
             }
         }
         substituter.addSubstitution(Substitutions.Type.USER_PREF, name, HttpUtility.HtmlEncode(value));
     }
 }
Example #20
0
        protected void cmdSearch_Click(object sender, EventArgs e)
        {
            // get the list that we already have
            String[]      existingGadgetURLs = txtGadgetURLS.Text.Split(Environment.NewLine.ToCharArray());
            List <String> existingFileNames  = new List <String>();

            foreach (String url in existingGadgetURLs)
            {
                existingFileNames.Add(GadgetSpec.GetGadgetFileNameFromURL(url));
            }

            try
            {
                // don't include any that we already have, based on file name
                HttpWebRequest myReq         = (HttpWebRequest)WebRequest.Create(txtNewGadgetsLocation.Text);
                Uri            newGadgetsUri = new Uri(txtNewGadgetsLocation.Text);
                using (StreamReader sr = new StreamReader(myReq.GetResponse().GetResponseStream()))
                {
                    bool     newGadgetsFound    = false;
                    String[] newGadgetHtmlCunks = sr.ReadToEnd().Split(new string[] { "<A HREF=\"" }, StringSplitOptions.None);
                    foreach (String newGadgetHtmlChunk in newGadgetHtmlCunks)
                    {
                        if (!newGadgetHtmlChunk.Contains("\">"))
                        {
                            continue;
                        }
                        String linkName = newGadgetHtmlChunk.Substring(0, newGadgetHtmlChunk.IndexOf("\">"));
                        if (linkName.EndsWith(".xml") && !existingFileNames.Contains(GadgetSpec.GetGadgetFileNameFromURL(linkName)))
                        {
                            txtGadgetURLS.Text += newGadgetsUri.Scheme + "://" + newGadgetsUri.Host + HttpUtility.UrlDecode(linkName) + Environment.NewLine;
                            newGadgetsFound     = true;
                        }
                    }
                    if (!newGadgetsFound)
                    {
                        lblError.Text = "No new gadgets found at " + txtNewGadgetsLocation.Text;
                    }
                }
            }
            catch (Exception ex)
            {
                lblError.Text = "Unable to read " + txtNewGadgetsLocation.Text;
            }
        }
Example #21
0
        public override List <preloadProcessor> createPreloadTasks(GadgetContext context,
                                                                   GadgetSpec gadget, PreloaderService.PreloadPhase phase)
        {
            List <preloadProcessor> preloads = new List <preloadProcessor>();

            if (phase == PreloaderService.PreloadPhase.HTML_RENDER)
            {
                foreach (Preload preload in gadget.getModulePrefs().getPreloads())
                {
                    HashSet <String> preloadViews = preload.getViews();
                    if (preloadViews.Count == 0 || preloadViews.Contains(context.getView()))
                    {
                        PreloadTask task = new PreloadTask(context, preload, preload.getHref().ToString());
                        preloads.Add(new preloadProcessor(task.call));
                    }
                }
            }
            return(preloads);
        }
        public GadgetSpec getGadgetSpec(URI gadgetUri, bool ignoreCache)
        {
            Uri uri = Uri.fromJavaUri(gadgetUri);

            if (ignoreCache)
            {
                return(FetchObjectAndCache(uri, ignoreCache));
            }

            GadgetSpec cached = HttpRuntime.Cache[gadgetUri.ToString()] as GadgetSpec;

            GadgetSpec spec;

            if (cached == null)
            {
                try
                {
                    spec = FetchObjectAndCache(uri, ignoreCache);
                }
                catch (GadgetException e)
                {
                    // We create this dummy spec to avoid the cost of re-parsing when a remote site is out.
                    spec = new GadgetSpec(uri, ERROR_SPEC);
                    spec.setAttribute(ERROR_KEY, e);
                    HttpRuntime.Cache.Insert(uri.ToString(), spec, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(ERROR_DELAY));
                }
            }
            else
            {
                spec = cached;
            }

            GadgetException exception = (GadgetException)spec.getAttribute(ERROR_KEY);

            if (exception != null)
            {
                throw exception;
            }
            return(spec);
        }
Example #23
0
        public MessageBundle getBundle(GadgetSpec spec, Locale locale, bool ignoreCache)
        {
            MessageBundle parent     = getParentBundle(spec, locale, ignoreCache);
            MessageBundle child      = null;
            LocaleSpec    localeSpec = spec.getModulePrefs().getLocale(locale);

            if (localeSpec == null)
            {
                return(parent ?? MessageBundle.EMPTY);
            }
            Uri messages = localeSpec.getMessages();

            if (messages == null || messages.ToString().Length == 0)
            {
                child = localeSpec.getMessageBundle();
            }
            else
            {
                child = fetchBundle(localeSpec, ignoreCache);
            }
            return(new MessageBundle(parent, child));
        }
        public override IPreloads preload(GadgetContext context, GadgetSpec gadget, PreloadPhase phase)
        {
            if (preloaders.Count == 0)
            {
                return(null);
            }

            var tasks = new List <Preloader.preloadProcessor>();

            foreach (Preloader preloader in preloaders)
            {
                ICollection <Preloader.preloadProcessor> taskCollection = preloader.createPreloadTasks(context, gadget, phase);
                tasks.AddRange(taskCollection);
            }
            ConcurrentPreloads preloads = new ConcurrentPreloads();

            foreach (var task in tasks)
            {
                preloads.add(task.BeginInvoke(null, null));
            }
            return(preloads);
        }
Example #25
0
        /// <summary>
        /// Get all features needed to satisfy this rendering request.
        /// </summary>
        /// <param name="spec"></param>
        /// <param name="forced">Forced libraries; added in addition to those found in the spec. Defaults to "core"</param>
        /// <returns></returns>
        private ICollection <GadgetFeature> GetFeatures(GadgetSpec spec, ICollection <String> forced)
        {
            Dictionary <String, Feature> features = spec.getModulePrefs().getFeatures();
            HashKey <String>             libs     = new HashKey <string>();

            foreach (var item in features.Keys)
            {
                libs.Add(item);
            }
            if (forced.Count != 0)
            {
                foreach (var item in forced)
                {
                    libs.Add(item);
                }
            }

            HashSet <String>            unsupported = new HashSet <String>();
            ICollection <GadgetFeature> feats       = featureRegistry.GetFeatures(libs, unsupported);

            foreach (var item in forced)
            {
                unsupported.Remove(item);
            }

            if (unsupported.Count != 0)
            {
                // Remove non-required libs
                unsupported.RemoveWhere(x => !features[x].getRequired());

                // Throw error with full list of unsupported libraries
                if (unsupported.Count != 0)
                {
                    throw new UnsupportedFeatureException(String.Join(",", unsupported.ToArray()));
                }
            }
            return(feats);
        }
Example #26
0
        /**
         * Creates a proxy request by fetching pipelined data and adding it to an existing request.
         *
         */
        private sRequest createPipelinedProxyRequest(Gadget gadget, sRequest original)
        {
            sRequest request = new sRequest(original);

            request.setIgnoreCache(true);
            GadgetSpec    spec          = gadget.getSpec();
            GadgetContext context       = gadget.getContext();
            IPreloads     proxyPreloads = preloader.preload(context, spec,
                                                            PreloaderService.PreloadPhase.PROXY_FETCH);

            // TODO: Add current url to GadgetContext to support transitive proxying.

            // POST any preloaded content
            if ((proxyPreloads != null) && proxyPreloads.getData().Count != 0)
            {
                JsonArray array = new JsonArray();

                foreach (PreloadedData preload in proxyPreloads.getData())
                {
                    Dictionary <String, Object> dataMap = preload.toJson();
                    foreach (var entry in dataMap)
                    {
                        // TODO: the existing, supported content is JSONObjects that contain the
                        // key already.  Discarding the key is odd.
                        array.Put(entry.Value);
                    }
                }

                String postContent = array.ToString();
                // POST the preloaded content, with a method override of GET
                // to enable caching
                request.setMethod("POST")
                .setPostBody(Encoding.UTF8.GetBytes(postContent))
                .setHeader("Content-Type", "text/json;charset=utf-8");
            }
            return(request);
        }
        private GadgetSpec FetchObjectAndCache(Uri url, bool ignoreCache)
        {
            sRequest request = new sRequest(url)
                               .setIgnoreCache(ignoreCache)
                               .setGadget(url);

            // Since we don't allow any variance in cache time, we should just force the cache time
            // globally. This ensures propagation to shared caches when this is set.
            request.setCacheTtl((int)(refresh / 1000));

            sResponse response = fetcher.fetch(request);

            if (response.getHttpStatusCode() != (int)HttpStatusCode.OK)
            {
                throw new GadgetException(GadgetException.Code.FAILED_TO_RETRIEVE_CONTENT,
                                          "Unable to retrieve gadget xml. HTTP error " +
                                          response.getHttpStatusCode());
            }

            GadgetSpec spec = new GadgetSpec(url, response.responseString);

            HttpRuntime.Cache.Insert(url.ToString(), spec, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(refresh));
            return(spec);
        }
    public OpenSocialHelper(int viewerId, int ownerId, Page page)
    {
        this.viewerId = viewerId;
        this.ownerId  = ownerId;
        this.isDebug  = page.Session != null && page.Session[OPENSOCIAL_DEBUG] != null && (bool)page.Session[OPENSOCIAL_DEBUG];
        this.noCache  = page.Session != null && page.Session[OPENSOCIAL_NOCACHE] != null && (bool)page.Session[OPENSOCIAL_NOCACHE];
        this.pageName = page.AppRelativeVirtualPath.Substring(2);

        if (ConfigUtil.GetConfigItem("OpenSocialURL") == null)
        {
            // do nothing
            return;
        }

        Random random = new Random();

        bool   gadgetLogin  = page.AppRelativeVirtualPath.EndsWith("gadgetlogin.aspx");
        String requestAppId = page.Request.QueryString["appId"];

        Dictionary <string, GadgetSpec> dbApps       = new Dictionary <string, GadgetSpec>();
        Dictionary <string, GadgetSpec> officialApps = new Dictionary <string, GadgetSpec>();
        // Load gadgets from the DB first
        IDataReader reader = null;

        try
        {
            Database db = DatabaseFactory.CreateDatabase();

            string sqlCommand = "select appId, name, url, channels, enabled from shindig_apps";
            // if a specific app is requested, only grab it
            if (requestAppId != null)
            {
                sqlCommand += " where appId = " + requestAppId;
            }
            DbCommand dbCommand = db.GetSqlStringCommand(sqlCommand);
            reader = db.ExecuteReader(dbCommand);
            while (reader.Read())
            {
                GadgetSpec spec           = new GadgetSpec(Convert.ToInt32(reader[0]), reader[1].ToString(), reader[2].ToString(), reader[3].ToString());
                string     gadgetFileName = GetGadgetFileNameFromURL(reader[2].ToString());

                dbApps.Add(gadgetFileName, spec);
                if (requestAppId != null || Convert.ToBoolean(reader[4]))
                {
                    officialApps.Add(gadgetFileName, spec);
                }
            }
        }
        catch (Exception e)
        {
            throw new Exception(e.Message);
        }
        finally
        {
            if (reader != null)
            {
                reader.Close();
            }
        }


        // Add manual gadgets if there are any
        // Note that this block of code only gets executed after someone logs in with gadgetlogin.aspx!
        int moduleId = 0;

        if (page.Session != null && (string)page.Session[OPENSOCIAL_GADGETS] != null)
        {
            String   openSocialGadgetURLS = (string)page.Session[OPENSOCIAL_GADGETS];
            String[] urls = openSocialGadgetURLS.Split(Environment.NewLine.ToCharArray());
            for (int i = 0; i < urls.Length; i++)
            {
                String openSocialGadgetURL = urls[i];
                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;
                string[] channels       = new string[0];
                bool     sandboxOnly    = true;
                if (dbApps.ContainsKey(gadgetFileName))
                {
                    appId       = dbApps[gadgetFileName].GetAppId();
                    name        = dbApps[gadgetFileName].GetName();
                    channels    = dbApps[gadgetFileName].GetChannels();
                    sandboxOnly = false;
                }
                else
                {
                    CharEnumerator ce = openSocialGadgetURL.GetEnumerator();
                    while (ce.MoveNext())
                    {
                        appId += (int)ce.Current;
                    }
                }
                // if they asked for a specific one, only let it in
                if (requestAppId != null && Convert.ToInt32(requestAppId) != appId)
                {
                    continue;
                }
                GadgetSpec gadget = new GadgetSpec(appId, name, openSocialGadgetURL, channels, sandboxOnly);
                // only add ones that are visible in this context!
                if (sandboxOnly || gadget.Show(viewerId, ownerId, page.AppRelativeVirtualPath.Substring(2)))
                {
                    String securityToken = SocketSendReceive(viewerId, ownerId, "" + gadget.GetAppId());
                    gadgets.Add(new PreparedGadget(gadget, this, moduleId++, securityToken));
                }
            }
        }

        // if no manual one were added, use the ones from the DB
        if (gadgets.Count == 0)
        {
            // Load DB gadgets
            if (gadgetLogin)
            {
                officialApps = dbApps;
            }
            foreach (KeyValuePair <string, GadgetSpec> pair in officialApps)
            {
                GadgetSpec gadget = new GadgetSpec(pair.Value.GetAppId(), pair.Value.GetName(), pair.Value.GetGadgetURL(), pair.Value.GetChannels(), false);
                // only add ones that are visible in this context!
                if (gadgetLogin || gadget.Show(viewerId, ownerId, GetPageName()))
                {
                    String securityToken = SocketSendReceive(viewerId, ownerId, "" + gadget.GetAppId());
                    gadgets.Add(new PreparedGadget(gadget, this, moduleId++, securityToken));
                }
            }
        }
        // sort the gadgets
        gadgets.Sort();

        // trigger the javascript to render gadgets
        HtmlGenericControl body = (HtmlGenericControl)page.Master.FindControl("bodyMaster");

        if (body == null)
        {
            body = (HtmlGenericControl)page.Master.Master.FindControl("bodyMaster");
        }
        body.Attributes.Add("onload", "my.init();");
    }
Example #29
0
 /**
  * Create new preload tasks for the provided gadget.
  *
  * @param context The request that needs preloading.
  * @param gadget The gadget that the operations will be performed for.
  * @return Preloading tasks that will be executed by
  *  {@link PreloaderService#preload(GadgetContext, GadgetSpec)}.
  */
 public abstract List <preloadProcessor> createPreloadTasks(GadgetContext context, GadgetSpec gadget, PreloaderService.PreloadPhase phase);
 private static bool GadgetWantsLockedDomain(GadgetSpec gadget)
 {
     return(gadget.getModulePrefs().getFeatures().ContainsKey("locked-domain"));
 }