Example usage for org.w3c.dom Node getOwnerDocument

List of usage examples for org.w3c.dom Node getOwnerDocument

Introduction

In this page you can find the example usage for org.w3c.dom Node getOwnerDocument.

Prototype

public Document getOwnerDocument();

Source Link

Document

The Document object associated with this node.

Usage

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

protected void injectBaseTag(Gadget gadget, Node headTag) {
    GadgetContext context = gadget.getContext();
    if (containerConfig.getBool(context.getContainer(), INSERT_BASE_ELEMENT_KEY)) {
        Uri base = gadget.getSpec().getUrl();
        View view = gadget.getCurrentView();
        if (view != null && view.getHref() != null) {
            base = view.getHref();/*from   www. j  a va 2s. c om*/
        }
        Element baseTag = headTag.getOwnerDocument().createElement("base");
        baseTag.setAttribute("href", base.toString());
        headTag.insertBefore(baseTag, headTag.getFirstChild());
    }
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

protected void injectOnLoadHandlers(Node bodyTag) {
    Element onloadScript = bodyTag.getOwnerDocument().createElement("script");
    bodyTag.appendChild(onloadScript);/*  www.  j  av  a 2s.co m*/
    onloadScript.appendChild(bodyTag.getOwnerDocument().createTextNode("gadgets.util.runOnLoadHandlers();"));
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

protected void injectGadgetBeacon(Gadget gadget, Node headTag, Node firstHeadChild) throws GadgetException {
    Element beaconNode = headTag.getOwnerDocument().createElement("script");
    beaconNode.setTextContent(IS_GADGET_BEACON);
    headTag.insertBefore(beaconNode, firstHeadChild);
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects javascript libraries needed to satisfy feature dependencies.
 *//* w  w w. j  a  va 2s. c  o  m*/
protected void injectFeatureLibraries(Gadget gadget, Node headTag, Node firstHeadChild) throws GadgetException {
    // 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();

    // Set of extern libraries requested by the container
    Set<String> externForcedLibs = defaultExternLibs;

    // gather the libraries we'll need to generate the extern libs
    String externParam = context.getParameter("libs");
    if (StringUtils.isNotBlank(externParam)) {
        externForcedLibs = Sets.newTreeSet(Arrays.asList(StringUtils.split(externParam, ':')));
    }

    if (!externForcedLibs.isEmpty()) {
        String jsUrl = jsUriManager.makeExternJsUri(gadget, externForcedLibs).toString();
        Element libsTag = headTag.getOwnerDocument().createElement("script");
        libsTag.setAttribute("src", jsUrl);
        headTag.insertBefore(libsTag, firstHeadChild);
    }

    List<String> unsupported = Lists.newLinkedList();

    List<FeatureResource> externForcedResources = featureRegistry.getFeatureResources(context, externForcedLibs,
            unsupported);
    if (!unsupported.isEmpty()) {
        LOG.info("Unknown feature(s) in extern &libs=: " + unsupported.toString());
        unsupported.clear();
    }

    // Get all resources requested by the gadget's requires/optional features.
    Map<String, Feature> featureMap = gadget.getSpec().getModulePrefs().getFeatures();
    List<String> gadgetFeatureKeys = Lists.newArrayList(gadget.getDirectFeatureDeps());
    List<FeatureResource> gadgetResources = featureRegistry.getFeatureResources(context, gadgetFeatureKeys,
            unsupported);
    if (!unsupported.isEmpty()) {
        List<String> requiredUnsupported = Lists.newLinkedList();
        for (String notThere : unsupported) {
            if (!featureMap.containsKey(notThere) || featureMap.get(notThere).getRequired()) {
                // if !containsKey, the lib was forced with Gadget.addFeature(...) so implicitly req'd.
                requiredUnsupported.add(notThere);
            }
        }
        if (!requiredUnsupported.isEmpty()) {
            throw new UnsupportedFeatureException(requiredUnsupported.toString());
        }
    }

    // Inline or externalize the gadgetFeatureKeys
    List<FeatureResource> inlineResources = Lists.newArrayList();
    List<String> allRequested = Lists.newArrayList(gadgetFeatureKeys);

    if (externalizeFeatures) {
        Set<String> externGadgetLibs = Sets.newTreeSet(featureRegistry.getFeatures(gadgetFeatureKeys));
        externGadgetLibs.removeAll(externForcedLibs);

        if (!externGadgetLibs.isEmpty()) {
            String jsUrl = jsUriManager.makeExternJsUri(gadget, externGadgetLibs).toString();
            Element libsTag = headTag.getOwnerDocument().createElement("script");
            libsTag.setAttribute("src", jsUrl);
            headTag.insertBefore(libsTag, firstHeadChild);
        }
    } else {
        inlineResources.addAll(gadgetResources);
    }

    // Calculate inlineResources as all resources that are needed by the gadget to
    // render, minus all those included through externResources.
    // TODO: profile and if needed, optimize this a bit.
    if (!externForcedLibs.isEmpty()) {
        allRequested.addAll(externForcedLibs);
        inlineResources.removeAll(externForcedResources);
    }

    // Precalculate the maximum length in order to avoid excessive garbage generation.
    int size = 0;
    for (FeatureResource resource : inlineResources) {
        if (!resource.isExternal()) {
            if (context.getDebug()) {
                size += resource.getDebugContent().length();
            } else {
                size += resource.getContent().length();
            }
        }
    }

    String libraryConfig = getLibraryConfig(gadget, featureRegistry.getFeatures(allRequested));

    // Size has a small fudge factor added to it for delimiters and such.
    StringBuilder inlineJs = new StringBuilder(size + libraryConfig.length() + INLINE_JS_BUFFER);

    // Inline any libs that weren't extern. The ugly context switch between inline and external
    // Js is needed to allow both inline and external scripts declared in feature.xml.
    for (FeatureResource resource : inlineResources) {
        String theContent = context.getDebug() ? resource.getDebugContent() : resource.getContent();
        if (resource.isExternal()) {
            if (inlineJs.length() > 0) {
                Element inlineTag = headTag.getOwnerDocument().createElement("script");
                headTag.insertBefore(inlineTag, firstHeadChild);
                inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.toString()));
                inlineJs.setLength(0);
            }
            Element referenceTag = headTag.getOwnerDocument().createElement("script");
            referenceTag.setAttribute("src", theContent);
            headTag.insertBefore(referenceTag, firstHeadChild);
        } else {
            inlineJs.append(theContent).append(";\n");
        }
    }

    inlineJs.append(libraryConfig);

    if (inlineJs.length() > 0) {
        Element inlineTag = headTag.getOwnerDocument().createElement("script");
        headTag.insertBefore(inlineTag, firstHeadChild);
        inlineTag.appendChild(headTag.getOwnerDocument().createTextNode(inlineJs.toString()));
    }
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects message bundles into the gadget output.
 * @throws GadgetException If we are unable to retrieve the message bundle.
 *//*  w  w  w .  j  a v a 2  s .co m*/
protected void injectMessageBundles(MessageBundle bundle, Node scriptTag) throws GadgetException {
    String msgs = bundle.toJSONString();

    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setMessages_(");
    text.appendData(msgs);
    text.appendData(");");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects default values for user prefs into the gadget output.
 *///from w  w  w .j  a  v a 2  s  . com
protected void injectDefaultPrefs(Gadget gadget, Node scriptTag) {
    Collection<UserPref> prefs = gadget.getSpec().getUserPrefs().values();
    Map<String, String> defaultPrefs = Maps.newHashMapWithExpectedSize(prefs.size());
    for (UserPref up : prefs) {
        defaultPrefs.put(up.getName(), up.getDefaultValue());
    }
    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.Prefs.setDefaultPrefs_(");
    text.appendData(JsonSerializer.serialize(defaultPrefs));
    text.appendData(");");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.render.RenderingGadgetRewriter.java

/**
 * Injects preloads into the gadget output.
 *
 * If preloading fails for any reason, we just output an empty object.
 *//*from  w ww.j av  a  2s .  c  o  m*/
protected void injectPreloads(Gadget gadget, Node scriptTag) {
    List<Object> preload = Lists.newArrayList();
    for (PreloadedData preloaded : gadget.getPreloads()) {
        try {
            preload.addAll(preloaded.toJson());
        } catch (PreloadException pe) {
            // This will be thrown in the event of some unexpected exception. We can move on.
            LOG.log(Level.WARNING, "Unexpected error when preloading", pe);
        }
    }
    Text text = scriptTag.getOwnerDocument().createTextNode("gadgets.io.preloaded_=");
    text.appendData(JsonSerializer.serialize(preload));
    text.appendData(";");
    scriptTag.appendChild(text);
}

From source file:org.apache.shindig.gadgets.rewrite.AbsolutePathReferenceVisitor.java

/**
 * Returns the uri to resolve any relative url on the current page to.
 * This is equal to the base uri (in case the page has one) or the current
 * page uri./*from   www .  j  a  v  a2s. com*/
 * @param gadget The gadget (container for page) being processed.
 * @param node The current node being processed.
 * @return The uri to resolve non absolute uri's relative to.
 */
private Uri getBaseResolutionUri(Gadget gadget, Node node) {
    Uri pageUri = gadget.getSpec().getUrl();
    Uri baseUri = getBaseUri(node.getOwnerDocument());
    return baseUri != null ? baseUri : pageUri;
}

From source file:org.apache.shindig.gadgets.templates.tags.FlashTagHandler.java

public void process(Node result, Element tag, TemplateProcessor processor) {
    SwfObjectConfig config;//w  w  w .  jav  a 2 s  .  c o m
    try {
        config = getSwfConfig(tag, processor);
    } catch (RuntimeException re) {
        // Record the processing error into the output
        Element err = result.getOwnerDocument().createElement("span");
        err.setTextContent("Failed to process os:Flash tag: " + StringEscapeUtils.escapeHtml(re.getMessage()));
        result.appendChild(err);
        return;
    }

    // Bind the security token to the flashvars if its available
    String st = processor.getTemplateContext().getGadget().getContext().getParameter("st");
    if (!StringUtils.isEmpty(st)) {
        String stVar = "st=" + Utf8UrlCoder.encode(st);
        if (StringUtils.isEmpty(config.flashvars)) {
            config.flashvars = stVar;
        } else {
            config.flashvars += '&' + stVar;
        }
    }

    // Restrict the content if sanitization is enabled
    if (processor.getTemplateContext().getGadget().sanitizeOutput()) {
        config.allowscriptaccess = SwfObjectConfig.ScriptAccess.never;
        config.swliveconnect = false;
        config.allownetworking = SwfObjectConfig.NetworkAccess.internal;
        // TODO - Implement container control over autoplay on views
    }

    // Create a div wrapper around the provided alternate content
    Element altHolder = result.getOwnerDocument().createElement("div");
    String altContentId = ALT_CONTENT_PREFIX + idGenerator.incrementAndGet();
    altHolder.setAttribute("id", altContentId);
    result.appendChild(altHolder);

    // Add the alternate content to the holder
    NodeList alternateContent = tag.getChildNodes();
    if (alternateContent.getLength() > 0) {
        processor.processChildNodes(altHolder, tag);
    }

    // Create the call to swfobject
    String swfObjectCall = buildSwfObjectCall(config, altContentId);
    Element script = result.getOwnerDocument().createElement("script");
    script.setAttribute("type", "text/javascript");
    result.appendChild(script);

    if (config.play == SwfObjectConfig.Play.immediate) {
        // Call swfobject immediately
        script.setTextContent(swfObjectCall);
    } else {
        // Add onclick handler to trigger call to swfobject
        script.setTextContent("function " + altContentId + "(){ " + swfObjectCall + " }");
        altHolder.setAttribute("onclick", altContentId + "()");
    }

    // Bypass sanitization for the holder tag and the call to swfobject
    SanitizingGadgetRewriter.bypassSanitization(altHolder, false);
    SanitizingGadgetRewriter.bypassSanitization(script, false);
    ensureSwfobject(result.getOwnerDocument(), processor);
}

From source file:org.apache.xml.security.utils.XMLUtils.java

/**
 * This method returns the owner document of a particular node.
 * This method is necessary because it <I>always</I> returns a
 * {@link Document}. {@link Node#getOwnerDocument} returns <CODE>null</CODE>
 * if the {@link Node} is a {@link Document}.
 *
 * @param node/*w ww  .  j  a va 2s . c  o m*/
 * @return the owner document of the node
 */
public static Document getOwnerDocument(Node node) {
    if (node.getNodeType() == Node.DOCUMENT_NODE) {
        return (Document) node;
    }
    try {
        return node.getOwnerDocument();
    } catch (NullPointerException npe) {
        throw new NullPointerException(
                I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\"");
    }
}