Beispiel #1
0
        /**
         * Validates that the parent parameter was acceptable.
         *
         * @return True if the parent parameter is valid for the current container.
         */
        private bool ValidateParent(GadgetContext context)
        {
            String container = context.getContainer();
            String parent    = context.getParameter("parent");

            if (parent == null)
            {
                // If there is no parent parameter, we are still safe because no
                // dependent code ever has to trust it anyway.
                return(true);
            }

            try
            {
                JsonArray parents = containerConfig.GetJsonArray(container, "gadgets.parent");
                if (parents == null)
                {
                    return(true);
                }
                // We need to check each possible parent parameter against this regex.
                for (int i = 0, j = parents.Length; i < j; ++i)
                {
                    if (Regex.IsMatch(parents[i].ToString(), parent))
                    {
                        return(true);
                    }
                }
            }
            catch (JsonException)
            {
            }
            return(false);
        }
Beispiel #2
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);
            }
        }
Beispiel #3
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);
            }
        }
Beispiel #4
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);
        }
Beispiel #5
0
        /**
         * Processes a JSON request.
         *
         * @param request Original JSON request
         * @return The JSON response.
         */
        public JsonObject Process(JsonObject request)
        {
            JsonObject response = new JsonObject();

            JsonObject requestContext   = request.getJSONObject("context");
            JsonArray  requestedGadgets = request["gadgets"] as JsonArray;

            // Process all JSON first so that we don't wind up with hanging threads if
            // a JsonException is thrown.
            List <IAsyncResult> gadgets = new List <IAsyncResult>(requestedGadgets.Length);

            for (int i = 0, j = requestedGadgets.Length; i < j; ++i)
            {
                var context             = new JsonRpcGadgetContext(requestContext, (JsonObject)requestedGadgets[i]);
                PreloadProcessor proc   = new PreloadProcessor(CallJob);
                IAsyncResult     result = proc.BeginInvoke(context, null, null);
                gadgets.Add(result);
            }

            foreach (var entry in gadgets)
            {
                try
                {
                    AsyncResult      result = (AsyncResult)entry;
                    PreloadProcessor proc   = (PreloadProcessor)result.AsyncDelegate;
                    JsonObject       gadget = proc.EndInvoke(result);
                    response.Accumulate("gadgets", gadget);
                }
                catch (JsonException e)
                {
                    throw new RpcException("Unable to write JSON", e);
                }
                catch (Exception ee)
                {
                    if (!(ee is RpcException))
                    {
                        throw new RpcException("Processing interrupted", ee);
                    }
                    RpcException e = (RpcException)ee;
                    // Just one gadget failed; mark it as such.
                    try
                    {
                        GadgetContext context = e.Context;

                        JsonObject errorObj = new JsonObject();
                        errorObj.Put("url", context.getUrl())
                        .Put("moduleId", context.getModuleId());
                        errorObj.Accumulate("errors", e.Message);
                        response.Accumulate("gadgets", errorObj);
                    }
                    catch (JsonException je)
                    {
                        throw new RpcException("Unable to write JSON", je);
                    }
                }
            }
            return(response);
        }
Beispiel #6
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);
            }
        }
Beispiel #7
0
        /**
         * Creates a set of all configuration needed to satisfy the requested feature set.
         *
         * Appends special configuration for gadgets.util.hasFeature and gadgets.util.getFeatureParams to
         * the output js.
         *
         * This can't be handled via the normal configuration mechanism because it is something that
         * varies per request.
         *
         * @param reqs The features needed to satisfy the request.
         * @throws GadgetException If there is a problem with the gadget auth token
         */
        private String GetLibraryConfig(Gadget gadget, ICollection <GadgetFeature> reqs)

        {
            GadgetContext context = gadget.getContext();

            JsonObject features = containerConfig.GetJsonObject(context.getContainer(), FEATURES_KEY);

            Dictionary <String, Object> config = new Dictionary <string, object>(features == null ? 2 : features.Names.Count + 2);

            if (features != null)
            {
                // Discard what we don't care about.
                foreach (GadgetFeature feature in reqs)
                {
                    String name = feature.getName();
                    Object conf = features.Opt(name);
                    if (conf != null)
                    {
                        config.Add(name, conf);
                    }
                }
            }

            // Add gadgets.util support. This is calculated dynamically based on request inputs.
            ModulePrefs prefs  = gadget.getSpec().getModulePrefs();
            var         values = prefs.getFeatures().Values;
            Dictionary <String, Dictionary <String, String> > featureMap =
                new Dictionary <string, Dictionary <string, string> >(values.Count);

            foreach (Feature feature in values)
            {
                featureMap.Add(feature.getName(), feature.getParams());
            }
            config.Add("core.util", featureMap);

            // Add authentication token config
            ISecurityToken authToken = context.getToken();

            if (authToken != null)
            {
                Dictionary <String, String> authConfig = new Dictionary <String, String>(2);
                String updatedToken = authToken.getUpdatedToken();
                if (updatedToken != null)
                {
                    authConfig.Add("authToken", updatedToken);
                }
                String trustedJson = authToken.getTrustedJson();
                if (trustedJson != null)
                {
                    authConfig.Add("trustedJson", trustedJson);
                }
                config.Add("shindig.auth", authConfig);
            }
            return("gadgets.config.init(" + JsonConvert.ExportToString(config) + ");\n");
        }
Beispiel #8
0
 public static sRequest newHttpRequest(GadgetContext context,
             RequestAuthenticationInfo authenticationInfo)
 {
     sRequest request = new sRequest(authenticationInfo.getHref())
         .setSecurityToken(context.getToken())
         .setOAuthArguments(new OAuthArguments(authenticationInfo))
         .setAuthType(authenticationInfo.getAuthType())
         .setContainer(context.getContainer())
         .setGadget(Uri.fromJavaUri(context.getUrl()));
     return request;
 }
Beispiel #9
0
        public static sRequest newHttpRequest(GadgetContext context,
                                              RequestAuthenticationInfo authenticationInfo)
        {
            sRequest request = new sRequest(authenticationInfo.getHref())
                               .setSecurityToken(context.getToken())
                               .setOAuthArguments(new OAuthArguments(authenticationInfo))
                               .setAuthType(authenticationInfo.getAuthType())
                               .setContainer(context.getContainer())
                               .setGadget(Uri.fromJavaUri(context.getUrl()));

            return(request);
        }
Beispiel #10
0
        /**
         * Injects message bundles into the gadget output.
         * @throws GadgetException If we are unable to retrieve the message bundle.
         */
        private void InjectMessageBundles(Gadget gadget, Node scriptTag)
        {
            GadgetContext context = gadget.getContext();
            MessageBundle bundle  = messageBundleFactory.getBundle(
                gadget.getSpec(), context.getLocale(), context.getIgnoreCache());

            String msgs = bundle.ToJSONString();

            Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setMessages_(");

            text.appendData(msgs);
            text.appendData(");");
            scriptTag.appendChild(text);
        }
Beispiel #11
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);
        }
Beispiel #12
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));
        }
Beispiel #13
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;
            }
        }
Beispiel #14
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;
            }
        }
Beispiel #15
0
        private void InjectBaseTag(Gadget gadget, Node headTag)
        {
            GadgetContext context = gadget.getContext();

            if ("true".Equals(containerConfig.Get(context.getContainer(), INSERT_BASE_ELEMENT_KEY)))
            {
                Uri  baseUrl = gadget.getSpec().getUrl();
                View view    = gadget.getCurrentView();
                if (view != null && view.getHref() != null)
                {
                    baseUrl = view.getHref();
                }
                Element baseTag = headTag.getOwnerDocument().createElement("base");
                baseTag.setAttribute("href", baseUrl.ToString());
                headTag.insertBefore(baseTag, headTag.getFirstChild());
            }
        }
Beispiel #16
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;
 }
Beispiel #17
0
        /**
         * Fetches js configuration for the given feature set & container.
         *
         * @param config The configuration to extract js config from.
         * @param context The request context.
         * @param features A set of all features needed.
         */
        public static JsonObject GetJsConfig(ContainerConfig config, GadgetContext context, HashSet <string> features)
        {
            JsonObject containerFeatures = config.GetJsonObject(context.getContainer(),
                                                                "gadgets.features");
            JsonObject retv = new JsonObject();

            if (containerFeatures != null)
            {
                foreach (string feat in features)
                {
                    if (containerFeatures.Contains(feat))
                    {
                        retv.Put(feat, containerFeatures[feat]);
                    }
                }
            }
            return(retv);
        }
Beispiel #18
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 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;
        }
        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);
        }
Beispiel #21
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);
        }
Beispiel #22
0
 public RpcException()
     : this(null)
 {
     context = null;
 }
Beispiel #23
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);
Beispiel #24
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;
        }
Beispiel #25
0
        private JsonObject CallJob(GadgetContext context)
        {
            try
            {
                JsonObject gadgetJson = new JsonObject();
                Gadget     gadget     = Processor.Process(context);

                GadgetSpec  spec  = gadget.getSpec();
                ModulePrefs prefs = spec.getModulePrefs();

                // TODO: modularize response fields based on requested items.
                JsonObject views = new JsonObject();
                foreach (View view in spec.getViews().Values)
                {
                    views.Put(view.getName(), new JsonObject()
                              // .Put("content", view.getContent())
                              .Put("type", view.getType().ToString().ToLower())
                              .Put("quirks", view.getQuirks())
                              .Put("preferredHeight", view.getPreferredHeight())
                              .Put("preferredWidth", view.getPreferredWidth()));
                }

                // Features.
                List <String> feats = new List <String>();
                foreach (var entry in prefs.getFeatures())
                {
                    feats.Add(entry.Key);
                }
                string[] features = new string[feats.Count];
                feats.CopyTo(features, 0);

                // Links
                JsonObject links = new JsonObject();
                foreach (LinkSpec link in prefs.getLinks().Values)
                {
                    links.Put(link.getRel(), link.getHref());
                }

                JsonObject userPrefs = new JsonObject();

                // User pref specs
                foreach (UserPref pref in spec.getUserPrefs())
                {
                    JsonObject up = new JsonObject()
                                    .Put("displayName", pref.getDisplayName())
                                    .Put("type", pref.getDataType().ToString().ToLower())
                                    .Put("default", pref.getDefaultValue())
                                    .Put("enumValues", pref.getEnumValues())
                                    .Put("orderedEnumValues", getOrderedEnums(pref));
                    userPrefs.Put(pref.getName(), up);
                }

                // TODO: This should probably just copy all data from
                // ModulePrefs.getAttributes(), but names have to be converted to
                // camel case.
                gadgetJson.Put("iframeUrl", UrlGenerator.getIframeUrl(gadget))
                .Put("url", context.getUrl().ToString())
                .Put("moduleId", context.getModuleId())
                .Put("title", prefs.getTitle())
                .Put("titleUrl", prefs.getTitleUrl().ToString())
                .Put("views", views)
                .Put("features", features)
                .Put("userPrefs", userPrefs)
                .Put("links", links)

                // extended meta data
                .Put("directoryTitle", prefs.getDirectoryTitle())
                .Put("description", prefs.getDescription())
                .Put("thumbnail", prefs.getThumbnail().ToString())
                .Put("screenshot", prefs.getScreenshot().ToString())
                .Put("author", prefs.getAuthor())
                .Put("authorEmail", prefs.getAuthorEmail())
                .Put("authorAffiliation", prefs.getAuthorAffiliation())
                .Put("authorLocation", prefs.getAuthorLocation())
                .Put("authorPhoto", prefs.getAuthorPhoto())
                .Put("authorAboutme", prefs.getAuthorAboutme())
                .Put("authorQuote", prefs.getAuthorQuote())
                .Put("authorLink", prefs.getAuthorLink())
                .Put("categories", prefs.getCategories())
                .Put("screenshot", prefs.getScreenshot().ToString())
                .Put("height", prefs.getHeight())
                .Put("width", prefs.getWidth())
                .Put("showStats", prefs.getShowStats())
                .Put("showInDirectory", prefs.getShowInDirectory())
                .Put("singleton", prefs.getSingleton())
                .Put("scaling", prefs.getScaling())
                .Put("scrolling", prefs.getScrolling());
                return(gadgetJson);
            }
            catch (ProcessingException e)
            {
                throw new RpcException(context, e);
                //throw e;
            }
            catch (JsonException e)
            {
                // Shouldn't be possible
                throw new RpcException(context, e);
            }
        }
Beispiel #26
0
        /**
        * Validates that the parent parameter was acceptable.
        *
        * @return True if the parent parameter is valid for the current container.
        */
        private bool ValidateParent(GadgetContext context) 
        {
            String container = context.getContainer();
            String parent = context.getParameter("parent");

            if (parent == null) 
            {
                // If there is no parent parameter, we are still safe because no
                // dependent code ever has to trust it anyway.
                return true;
            }

            try
            {
                JsonArray parents = containerConfig.GetJsonArray(container, "gadgets.parent");
                if (parents == null) 
                {
                    return true;
                }
                // We need to check each possible parent parameter against this regex.
                for (int i = 0, j = parents.Length; i < j; ++i) 
                {
                    if (Regex.IsMatch(parents[i].ToString(), parent))
                    {
                        return true;
                    }
                }
            } 
            catch (JsonException) 
            {

            }
            return false;
        }
Beispiel #27
0
  /**
 * Begin all preload operations.
 *
 * @param context The request that needs preloading.
 * @param gadget The gadget that the operations will be performed for.
 * @return The preloads for the gadget.
 *
 * TODO: This should probably have a read only input. If we can
 */
  public abstract IPreloads preload(GadgetContext context, GadgetSpec gadget, PreloadPhase phase);
Beispiel #28
0
 public RpcException(GadgetContext context, Exception cause)
     : base(cause.Message, cause)
 {
     this.context = context;
 }
Beispiel #29
0
 public RpcException(String message)
     : base(message)
 {
     context = null;
 }
Beispiel #30
0
 public RpcException()
     : this(null)
 {
     context = null;
 }
Beispiel #31
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);
Beispiel #32
0
 /**
 * Fetches js configuration for the given feature set & container.
 *
 * @param config The configuration to extract js config from.
 * @param context The request context.
 * @param features A set of all features needed.
 */
 public static JsonObject GetJsConfig(ContainerConfig config, GadgetContext context, HashSet<string> features)
 {
     JsonObject containerFeatures = config.GetJsonObject(context.getContainer(),
                                                         "gadgets.features");
     JsonObject retv = new JsonObject();
     if (containerFeatures != null)
     {
         foreach (string feat in features)
         {
             if (containerFeatures.Contains(feat))
             {
                 retv.Put(feat, containerFeatures[feat]);
             }
         }
     }
     return retv;
 }
Beispiel #33
0
 /**
  * Begin all preload operations.
  *
  * @param context The request that needs preloading.
  * @param gadget The gadget that the operations will be performed for.
  * @return The preloads for the gadget.
  *
  * TODO: This should probably have a read only input. If we can
  */
 public abstract IPreloads preload(GadgetContext context, GadgetSpec gadget, PreloadPhase phase);
Beispiel #34
0
 public RpcException(String message)
     : base(message)
 {
     context = null;
 }
Beispiel #35
0
 public RpcException(String message, Exception cause)
     : base(message, cause)
 {
     this.context = null;
 }
Beispiel #36
0
 public RpcException(String message, Exception cause)
     : base(message, cause)
 {
     this.context = null;
 }
Beispiel #37
0
 public RpcException(GadgetContext context, Exception cause)
     : base(cause.Message, cause)
 {
     this.context = context;
 }
Beispiel #38
0
 public RpcException(GadgetContext context, String message, Exception cause)
     : base(message, cause)
 {
     this.context = context;
 }
Beispiel #39
0
 public RpcException(GadgetContext context, String message, Exception cause)
     : base(message, cause)
 {
     this.context = context;
 }
Beispiel #40
0
 public PreloadTask(GadgetContext context, Preload preload, String key) 
 {
     this.context = context;
     this.preload = preload;
     this.key = key;
 }
Beispiel #41
0
        /// <summary>
        /// Injects javascript libraries needed to satisfy feature dependencies.
        /// </summary>
        /// <param name="gadget"></param>
        /// <param name="headTag"></param>
        private void InjectFeatureLibraries(Gadget gadget, Node headTag)
        {
            // TODO: If there isn't any js in the document, we can skip this. Unfortunately, that means
            // both script tags (easy to detect) and event handlers (much more complex).
            GadgetContext    context    = gadget.getContext();
            GadgetSpec       spec       = gadget.getSpec();
            String           forcedLibs = context.getParameter("libs");
            HashKey <String> forced;

            if (string.IsNullOrEmpty(forcedLibs))
            {
                forced = new HashKey <string>();
            }
            else
            {
                forced = new HashKey <string>();
                foreach (var item in forcedLibs.Split(':'))
                {
                    forced.Add(item);
                }
            }


            // Forced libs are always done first.
            if (forced.Count != 0)
            {
                String  jsUrl   = urlGenerator.getBundledJsUrl(forced, context);
                Element libsTag = headTag.getOwnerDocument().createElement("script");
                libsTag.setAttribute("src", jsUrl);
                headTag.appendChild(libsTag);

                // Forced transitive deps need to be added as well so that they don't get pulled in twice.
                // TODO: Figure out a clean way to avoid having to call getFeatures twice.
                foreach (GadgetFeature dep in featureRegistry.GetFeatures(forced))
                {
                    forced.Add(dep.getName());
                }
            }

            // Inline any libs that weren't forced. The ugly context switch between inline and external
            // Js is needed to allow both inline and external scripts declared in feature.xml.
            String container = context.getContainer();
            ICollection <GadgetFeature> features = GetFeatures(spec, forced);

            // Precalculate the maximum length in order to avoid excessive garbage generation.
            int size = 0;

            foreach (GadgetFeature feature in features)
            {
                foreach (JsLibrary library in feature.getJsLibraries(RenderingContext.GADGET, container))
                {
                    if (library._Type == JsLibrary.Type.URL)
                    {
                        size += library.Content.Length;
                    }
                }
            }

            // Really inexact.
            StringBuilder inlineJs = new StringBuilder(size);

            foreach (GadgetFeature feature in features)
            {
                foreach (JsLibrary library in feature.getJsLibraries(RenderingContext.GADGET, container))
                {
                    if (library._Type == JsLibrary.Type.URL)
                    {
                        if (inlineJs.Length > 0)
                        {
                            Element inlineTag = headTag.getOwnerDocument().createElement("script");
                            headTag.appendChild(inlineTag);
                            inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.ToString()));
                            inlineJs.Length = 0;
                        }
                        Element referenceTag = headTag.getOwnerDocument().createElement("script");
                        referenceTag.setAttribute("src", library.Content);
                        headTag.appendChild(referenceTag);
                    }
                    else
                    {
                        if (!forced.Contains(feature.getName()))
                        {
                            // already pulled this file in from the shared contents.
                            if (context.getDebug())
                            {
                                inlineJs.Append(library.DebugContent);
                            }
                            else
                            {
                                inlineJs.Append(library.Content);
                            }
                            inlineJs.Append(";\n");
                        }
                    }
                }
            }

            inlineJs.Append(GetLibraryConfig(gadget, features));

            if (inlineJs.Length > 0)
            {
                Element inlineTag = headTag.getOwnerDocument().createElement("script");
                headTag.appendChild(inlineTag);
                inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.ToString()));
            }
        }
Beispiel #42
0
        private JsonObject CallJob(GadgetContext context)
        {
            try
            {
                JsonObject gadgetJson = new JsonObject();
                Gadget gadget = Processor.Process(context);

                GadgetSpec spec = gadget.getSpec();
                ModulePrefs prefs = spec.getModulePrefs();

                // TODO: modularize response fields based on requested items.
                JsonObject views = new JsonObject();
                foreach (View view in spec.getViews().Values)
                {
                    views.Put(view.getName(), new JsonObject()
                                                  // .Put("content", view.getContent())
                                                  .Put("type", view.getType().ToString().ToLower())
                                                  .Put("quirks", view.getQuirks())
                                                  .Put("preferredHeight", view.getPreferredHeight())
                                                  .Put("preferredWidth", view.getPreferredWidth()));
                }

                // Features.
                List<String> feats = new List<String>();
                foreach (var entry in prefs.getFeatures())
                {
                    feats.Add(entry.Key);
                }
                string[] features = new string[feats.Count];
                feats.CopyTo(features, 0);

                // Links
                JsonObject links = new JsonObject();
                foreach (LinkSpec link in prefs.getLinks().Values)
                {
                    links.Put(link.getRel(), link.getHref());
                }

                JsonObject userPrefs = new JsonObject();

                // User pref specs
                foreach (UserPref pref in spec.getUserPrefs())
                {
                    JsonObject up = new JsonObject()
                        .Put("displayName", pref.getDisplayName())
                        .Put("type", pref.getDataType().ToString().ToLower())
                        .Put("default", pref.getDefaultValue())
                        .Put("enumValues", pref.getEnumValues())
                        .Put("orderedEnumValues", getOrderedEnums(pref));
                    userPrefs.Put(pref.getName(), up);
                }

                // TODO: This should probably just copy all data from
                // ModulePrefs.getAttributes(), but names have to be converted to
                // camel case.
                gadgetJson.Put("iframeUrl", UrlGenerator.getIframeUrl(gadget))
                    .Put("url", context.getUrl().ToString())
                    .Put("moduleId", context.getModuleId())
                    .Put("title", prefs.getTitle())
                    .Put("titleUrl", prefs.getTitleUrl().ToString())
                    .Put("views", views)
                    .Put("features", features)
                    .Put("userPrefs", userPrefs)
                    .Put("links", links)

                    // extended meta data
                    .Put("directoryTitle", prefs.getDirectoryTitle())
                    .Put("description", prefs.getDescription())
                    .Put("thumbnail", prefs.getThumbnail().ToString())
                    .Put("screenshot", prefs.getScreenshot().ToString())
                    .Put("author", prefs.getAuthor())
                    .Put("authorEmail", prefs.getAuthorEmail())
                    .Put("authorAffiliation", prefs.getAuthorAffiliation())
                    .Put("authorLocation", prefs.getAuthorLocation())
                    .Put("authorPhoto", prefs.getAuthorPhoto())
                    .Put("authorAboutme", prefs.getAuthorAboutme())
                    .Put("authorQuote", prefs.getAuthorQuote())
                    .Put("authorLink", prefs.getAuthorLink())
                    .Put("categories", prefs.getCategories())
                    .Put("screenshot", prefs.getScreenshot().ToString())
                    .Put("height", prefs.getHeight())
                    .Put("width", prefs.getWidth())
                    .Put("showStats", prefs.getShowStats())
                    .Put("showInDirectory", prefs.getShowInDirectory())
                    .Put("singleton", prefs.getSingleton())
                    .Put("scaling", prefs.getScaling())
                    .Put("scrolling", prefs.getScrolling());
                return gadgetJson;
            }
            catch (ProcessingException e)
            {
                throw new RpcException(context, e);
                //throw e;
            }
            catch (JsonException e)
            {
                // Shouldn't be possible
                throw new RpcException(context, e);
            }
        }
Beispiel #43
0
 public PreloadTask(GadgetContext context, Preload preload, String key)
 {
     this.context = context;
     this.preload = preload;
     this.key     = key;
 }