/** * Appends an image child to the panelGroup in the underlying JSP document */ public void appendChildToDocument(ActionEvent event) { UIComponent eventSource = event.getComponent(); UIComponent uic = eventSource.findComponent("pg1"); // only allow the image to be added once if (_findChildById(uic,"oi3") != null) return; FacesContext fc = FacesContext.getCurrentInstance(); DocumentFragment imageFragment = _createDocumentFragment(_IMAGE_MARK_UP); if (imageFragment != null) { DocumentChange change = new AddChildDocumentChange(imageFragment); ChangeManager apm = RequestContext.getCurrentInstance().getChangeManager(); apm.addDocumentChange(fc, uic, change); } }
/** * Attempt to decrypt by resolving the decryption key by first resolving EncryptedKeys, and using the KEK credential * resolver to resolve the key decryption for each. * * @param encryptedData the encrypted data to decrypt * @param algorithm the algorithm of the key to be decrypted * @return the decrypted document fragment, or null if decryption key could not be resolved or decryption failed */ private DocumentFragment decryptUsingResolvedEncryptedKey(EncryptedData encryptedData, String algorithm) { if (encKeyResolver != null) { for (EncryptedKey encryptedKey : encKeyResolver.resolve(encryptedData)) { try { Key decryptedKey = decryptKey(encryptedKey, algorithm); return decryptDataToDOM(encryptedData, decryptedKey); } catch (DecryptionException e) { String msg = "Attempt to decrypt EncryptedData using key extracted from EncryptedKey failed: "; log.debug(msg, e); continue; } } } return null; }
/** * Parse the specified input stream in a DOM DocumentFragment, owned by the specified Document. * * @param input the InputStream to parse * @param owningDocument the Document which will own the returned DocumentFragment * @return a DocumentFragment * @throws DecryptionException thrown if there is an error parsing the input stream */ private DocumentFragment parseInputStream(InputStream input, Document owningDocument) throws DecryptionException { // Since Xerces currently seems not to handle parsing into a DocumentFragment // without a bit hackery, use this to simulate, so we can keep the API // the way it hopefully will look in the future. Obviously this only works for // input streams containing valid XML instances, not fragments. Document newDocument = null; try { newDocument = parserPool.parse(input); } catch (XMLParserException e) { log.error("Error parsing decrypted input stream", e); throw new DecryptionException("Error parsing input stream", e); } Element element = newDocument.getDocumentElement(); owningDocument.adoptNode(element); DocumentFragment container = owningDocument.createDocumentFragment(); container.appendChild(element); return container; }
public Element getElement(DOMResult r) { // JAXP spec is ambiguous about what really happens in this case, // so work defensively Node n = r.getNode(); if( n instanceof Document ) { return ((Document)n).getDocumentElement(); } if( n instanceof Element ) return (Element)n; if( n instanceof DocumentFragment ) return (Element)n.getChildNodes().item(0); // if the result object contains something strange, // it is not a user problem, but it is a JAXB provider's problem. // That's why we throw a runtime exception. throw new IllegalStateException(n.toString()); }
protected void addNode(org.w3c.dom.Node newElement) throws SOAPException { insertBefore(soapDocument.getDomNode(newElement), null); if (getOwnerDocument() instanceof DocumentFragment) return; if (newElement instanceof ElementImpl) { ElementImpl element = (ElementImpl) newElement; QName elementName = element.getElementQName(); if (!"".equals(elementName.getNamespaceURI())) { element.ensureNamespaceIsDeclared( elementName.getPrefix(), elementName.getNamespaceURI()); } } }
/** Run all defined filters. */ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { // loop on each filter for (int i = 0; i < this.htmlParseFilters.length; i++) { // call filter interface parseResult = htmlParseFilters[i].filter(content, parseResult, metaTags, doc); // any failure on parse obj, return if (!parseResult.isSuccess()) { // TODO: What happens when parseResult.isEmpty() ? // Maybe clone parseResult and use parseResult as backup... // remove failed parse before return parseResult.filter(); return parseResult; } } return parseResult; }
/** * Scan the HTML document looking at possible rel-tags */ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { // get parse obj Parse parse = parseResult.get(content.getUrl()); // Trying to find the document's rel-tags Parser parser = new Parser(doc); Set<?> tags = parser.getRelTags(); Iterator<?> iter = tags.iterator(); Metadata metadata = parse.getData().getParseMeta(); while (iter.hasNext()) metadata.add(REL_TAG, (String) iter.next()); return parseResult; }
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { Parse parse = parseResult.get(content.getUrl()); String url = content.getBaseUrl(); ArrayList<Outlink> outlinks = new ArrayList<Outlink>(); walk(doc, parse, metaTags, url, outlinks); if (outlinks.size() > 0) { Outlink[] old = parse.getData().getOutlinks(); String title = parse.getData().getTitle(); List<Outlink> list = Arrays.asList(old); outlinks.addAll(list); ParseStatus status = parse.getData().getStatus(); String text = parse.getText(); Outlink[] newlinks = (Outlink[]) outlinks.toArray(new Outlink[outlinks .size()]); ParseData parseData = new ParseData(status, title, newlinks, parse .getData().getContentMeta(), parse.getData().getParseMeta()); // replace original parse obj with new one parseResult.put(content.getUrl(), new ParseText(text), parseData); } return parseResult; }
/** Try to find the document's language from page headers and metadata */ private String detectLanguage(Parse page, DocumentFragment doc) { String lang = getLanguageFromMetadata(page.getData().getParseMeta()); if (lang == null) { LanguageParser parser = new LanguageParser(doc); lang = parser.getLanguage(); } if (lang != null) { return lang; } lang = page.getData().getContentMeta().get(Response.CONTENT_LANGUAGE); return lang; }
public Element getElement(DOMResult r) { // JAXP spec is ambiguous about what really happens in this case, // so work defensively Node n = r.getNode(); if( n instanceof Document) { return ((Document)n).getDocumentElement(); } if( n instanceof Element ) return (Element)n; if( n instanceof DocumentFragment) return (Element)n.getChildNodes().item(0); // if the result object contains something strange, // it is not a user problem, but it is a JAXB provider's problem. // That's why we throw a runtime exception. throw new IllegalStateException(n.toString()); }
public static DocumentFragment createBlockForSdt(FOConversionContext context, NodeIterator pPrNodeIt, String pStyleVal, NodeIterator childResults, String tag) { DocumentFragment docfrag = createBlock(context, pPrNodeIt, pStyleVal, childResults, true); // Set margins, but only for a shading container, // not a borders container if (tag.equals(Containerization.TAG_SHADING) && docfrag!=null) { // docfrag.getNodeName() is #document-fragment Node foBlock = docfrag.getFirstChild(); if (foBlock!=null) { ((Element)foBlock).setAttribute("margin-top", "0in"); ((Element)foBlock).setAttribute("margin-bottom", "0in"); // ((Element)foBlock).setAttribute("padding-top", "0in"); // ((Element)foBlock).setAttribute("padding-bottom", "0in"); } } return docfrag; }
/** * Use RunFontSelector to determine the correct font for the list item label. * * @param context * @param foListItemLabelBody * @param pPr * @param rPr * @param text */ protected static void setFont(FOConversionContext context, Element foListItemLabelBody, PPr pPr, RPr rPr, String text) { DocumentFragment result = (DocumentFragment)context.getRunFontSelector().fontSelector(pPr, rPr, text); log.debug(XmlUtils.w3CDomNodeToString(result)); // eg <fo:inline xmlns:fo="http://www.w3.org/1999/XSL/Format" font-family="Times New Roman">1)</fo:inline> // Now get the attribute value if (result!=null && result.getFirstChild()!=null) { Attr attr = ((Element)result.getFirstChild()).getAttributeNode("font-family"); if (attr!=null) { foListItemLabelBody.setAttribute("font-family", attr.getValue()); } } }
public static DocumentFragment getLayoutMasterSetFragment(AbstractWmlConversionContext context) { LayoutMasterSet lms = getFoLayoutMasterSet(context); // Set suitable extents, for which we need area tree FOSettings foSettings = (FOSettings)context.getConversionSettings(); if ( !foSettings.lsLayoutMasterSetCalculationInProgress()) // Avoid infinite loop // Can't just do it where foSettings.getApacheFopMime() is not MimeConstants.MIME_FOP_AREA_TREE, // since TOC functionality uses that. { fixExtents( lms, context, true); } org.w3c.dom.Document document = XmlUtils.marshaltoW3CDomDocument(lms, Context.getXslFoContext() ); DocumentFragment docfrag = document.createDocumentFragment(); docfrag.appendChild(document.getDocumentElement()); return docfrag; }
Object getValue(Stylesheet stylesheet, QName mode, Node context, int pos, int len) throws TransformerException { if (select != null) return select.evaluate(context, pos, len); else if (children != null) { Document doc = (context instanceof Document) ? (Document) context : context.getOwnerDocument(); DocumentFragment fragment = doc.createDocumentFragment(); children.apply(stylesheet, mode, context, pos, len, fragment, null); return Collections.singleton(fragment); } else return null; }
Object getValue(Stylesheet stylesheet, QName mode, Node context, int pos, int len) throws TransformerException { if (select != null) { return select.evaluate(context, pos, len); } else if (content == null) { return ""; } else { Document doc = (context instanceof Document) ? (Document) context : context.getOwnerDocument(); DocumentFragment fragment = doc.createDocumentFragment(); content.apply(stylesheet, mode, context, pos, len, fragment, null); return Collections.singleton(fragment); } }
void doApply(Stylesheet stylesheet, QName mode, Node context, int pos, int len, Node parent, Node nextSibling) throws TransformerException { if (children != null) { Document doc = (parent instanceof Document) ? (Document) parent : parent.getOwnerDocument(); DocumentFragment fragment = doc.createDocumentFragment(); children.apply(stylesheet, mode, context, pos, len, fragment, null); String message = Expr.stringValue(fragment); logger.info(message); if (terminate) stylesheet.terminated = true; } if (next != null && !terminate) next.apply(stylesheet, mode, context, pos, len, parent, nextSibling); }
protected Node stringToNode(String str) { try { final DOMFragmentParser parser = new DOMFragmentParser(); final DocumentFragment fragment = document.createDocumentFragment(); parser.parse(new InputSource(new StringReader(str)), fragment); return fragment; // try and return the element itself if possible... // NodeList nl = fragment.getChildNodes(); // for (int i=0; i<nl.getLength(); i++) if (nl.item(i).getNodeType() // == Node.ELEMENT_NODE) return nl.item(i); // return fragment; } catch (final Exception e) { throw new RuntimeException(e); } }
/** Run all defined filters. */ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { // loop on each filter for (int i = 0 ; i < this.htmlParseFilters.length; i++) { // call filter interface parseResult = htmlParseFilters[i].filter(content, parseResult, metaTags, doc); // any failure on parse obj, return if (!parseResult.isSuccess()) { // TODO: What happens when parseResult.isEmpty() ? // Maybe clone parseResult and use parseResult as backup... // remove failed parse before return parseResult.filter(); return parseResult; } } return parseResult; }
/** * Scan the HTML document looking at possible rel-tags */ public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { // get parse obj Parse parse = parseResult.get(content.getUrl()); // Trying to find the document's rel-tags Parser parser = new Parser(doc); Set tags = parser.getRelTags(); Iterator iter = tags.iterator(); Metadata metadata = parse.getData().getParseMeta(); while (iter.hasNext()) { metadata.add(REL_TAG, (String) iter.next()); } return parseResult; }
public ParseResult filter(Content content, ParseResult parseResult, HTMLMetaTags metaTags, DocumentFragment doc) { Parse parse = parseResult.get(content.getUrl()); String url = content.getBaseUrl(); ArrayList outlinks = new ArrayList(); walk(doc, parse, metaTags, url, outlinks); if (outlinks.size() > 0) { Outlink[] old = parse.getData().getOutlinks(); String title = parse.getData().getTitle(); List list = Arrays.asList(old); outlinks.addAll(list); ParseStatus status = parse.getData().getStatus(); String text = parse.getText(); Outlink[] newlinks = (Outlink[])outlinks.toArray(new Outlink[outlinks.size()]); ParseData parseData = new ParseData(status, title, newlinks, parse.getData().getContentMeta(), parse.getData().getParseMeta()); // replace original parse obj with new one parseResult.put(content.getUrl(), new ParseText(text), parseData); } return parseResult; }
public DocumentFragment parseFragment(InputStream is) throws EXIException { try { // // create empty document fragment // Document document = domImplementation.createDocument(null, null, // null); // DocumentFragment docFragment = document.createDocumentFragment(); // create SAX to DOM Handlers SaxToDomHandler s2dHandler = new SaxToDomHandler(domImplementation, true); XMLReader reader = new SAXFactory(factory).createEXIReader(); reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); reader.setContentHandler(s2dHandler); reader.parse(new InputSource(is)); // return docFragment; return s2dHandler.getDocumentFragment(); } catch (Exception e) { throw new EXIException(e); } }
public static XMLStreamWriter createXMLStreamWriter(Result r) { if (r instanceof DOMResult) { //use our own DOM writer to avoid issues with Sun's //version that doesn't support getNamespaceContext DOMResult dr = (DOMResult)r; Node nd = dr.getNode(); if (nd instanceof Document) { return new W3CDOMStreamWriter((Document)nd); } else if (nd instanceof Element) { return new W3CDOMStreamWriter((Element)nd); } else if (nd instanceof DocumentFragment) { return new W3CDOMStreamWriter((DocumentFragment)nd); } } XMLOutputFactory factory = getXMLOutputFactory(); try { return factory.createXMLStreamWriter(r); } catch (XMLStreamException e) { throw new RuntimeException("Cant' create XMLStreamWriter", e); } finally { returnXMLOutputFactory(factory); } }
public final void testRenderWithUnknownNamespace() throws Exception { DocumentFragment fragment = xmlFragment(fromString( "" + "<foo xmlns='http://www.w3.org/XML/1998/namespace'" + " xmlns:bar='http://bobs.house.of/XML&BBQ'>" + "<bar:baz boo='howdy' xml:lang='es'/>" + "</foo>")); // Remove any XMLNS attributes and prefixes. Element el = (Element) fragment.getFirstChild(); while (el.getAttributes().getLength() != 0) { el.removeAttributeNode((Attr) el.getAttributes().item(0)); } el.setPrefix(""); el.getFirstChild().setPrefix(""); assertEquals( "" + "<xml:foo>" + "<_ns1:baz xmlns:_ns1=\"http://bobs.house.of/XML&BBQ\"" + " boo=\"howdy\" xml:lang=\"es\"></_ns1:baz>" + "</xml:foo>", Nodes.render(fragment, MarkupRenderMode.XML)); }
static <R> R visitNode(Node node, NodeVisitor<R> visitor) { switch (node.getNodeType()) { case Node.ELEMENT_NODE: return visitor.visitElement((Element) node); case Node.ATTRIBUTE_NODE: return visitor.visitAttr((Attr) node); case Node.TEXT_NODE: return visitor.visitText((Text) node); case Node.CDATA_SECTION_NODE: return visitor.visitCDATASection((CDATASection) node); case Node.ENTITY_REFERENCE_NODE: return visitor.visitEntityReference((EntityReference) node); case Node.ENTITY_NODE: return visitor.visitEntity((Entity) node); case Node.PROCESSING_INSTRUCTION_NODE: return visitor.visitProcessingInstruction((ProcessingInstruction) node); case Node.COMMENT_NODE: return visitor.visitComment((Comment) node); case Node.DOCUMENT_NODE: return visitor.visitDocument((Document) node); case Node.DOCUMENT_TYPE_NODE: return visitor.visitDocumentType((DocumentType) node); case Node.DOCUMENT_FRAGMENT_NODE: return visitor.visitDocumentFragment((DocumentFragment) node); case Node.NOTATION_NODE: return visitor.visitNotation((Notation) node); default: throw new RuntimeException(); } }
public final void testRenderWithMaskedOutputNamespace1() throws Exception { DocumentFragment fragment = xmlFragment(fromString( "<svg:foo><xml:bar/></svg:foo>")); Namespaces ns = new Namespaces( Namespaces.HTML_DEFAULT, "svg", Namespaces.XML_NAMESPACE_URI); StringBuilder sb = new StringBuilder(); RenderContext rc = new RenderContext(new Concatenator(sb)) .withMarkupRenderMode(MarkupRenderMode.XML); Nodes.render(fragment, ns, rc); rc.getOut().noMoreTokens(); assertEquals( "" + "<_ns2:foo xmlns:_ns2=\"http://www.w3.org/2000/svg\">" + "<svg:bar></svg:bar></_ns2:foo>", sb.toString()); }
@Override public void filter(String URL, byte[] content, DocumentFragment doc, ParseResult parse) { // skip existing links logLinks(parse, URL, "Skipped links"); parse.setOutlinks(new ArrayList<Outlink>()); super.filter(URL, content, doc, parse); for (Outlink outlink : parse.getOutlinks()) outlink.getMetadata().addValue(FeedParserBolt.isFeedKey, "true"); logLinks(parse, URL, "Added links"); }
@Override protected DocumentFragment convertXML(Element xmlValue) throws ConverterException { Document doc = xmlValue.getOwnerDocument(); DocumentFragment result = doc.createDocumentFragment(); for (Node child : XMLUtils.childrenNodes(xmlValue)) { Node clone = child.cloneNode(true); result.appendChild(clone); } return result; }
/** * Constructs an AddFacetDocumentChange with the specified child component mark up and * the name of the facet. * @param facetName Name of facet to create the child component in * @param fragment DOM mark up for child component to be inserted. * @throws IllegalArgumentException if facetName or componentFragment is * <code>null</code> */ public SetFacetChildDocumentChange( String facetName, DocumentFragment fragment) { super(fragment); if ((facetName == null) || (facetName.length() == 0)) throw new IllegalArgumentException(_LOG.getMessage( "FACET_NAME_MUST_SPECIFIED")); _facetName = facetName; }
/** * Given the DOM Node representing a Component, apply any necessary * DOM changes. * While applying this Change, the child component is created and added to * the document. If the facet doesn't exist, it will be created. If the facet * does exist, all of its content will be removed and the new content added. */ public void changeDocument(Node componentNode) { if (componentNode == null) throw new IllegalArgumentException(_LOG.getMessage( "NO_NODE_SPECIFIED")); // get the fragement, imported into the target document DocumentFragment targetFragment = getImportedComponentFragment(componentNode); Element facetElement = ChangeUtils.__getFacetElement(componentNode, _facetName); if (facetElement != null) { // remove any current children ChangeUtils.__removeAllChildren(facetElement); } else { Document targetDocument = componentNode.getOwnerDocument(); facetElement = targetDocument.createElementNS(_JSF_CORE_NAMESPACE, "f:facet"); // set the xmlns for the prefix to make sure that "f:" is the // prefix for faces // =-= bts TODO In theory, this could cause problems if the // added component used the prefix "f:" for something other than // the JSF core facetElement.setAttributeNS(_XMLNS_NAMESPACE, "xmlns:f", _JSF_CORE_NAMESPACE); facetElement.setAttribute(_FACET_ATTRIBUTE_NAME, _facetName); componentNode.appendChild(facetElement); } // add our new facet content facetElement.appendChild(targetFragment); }
protected AddComponentDocumentChange( DocumentFragment fragment) { if (fragment == null) throw new IllegalArgumentException(_LOG.getMessage( "DOCUMENTFRAGMENT_REQUIRED")); _fragment = fragment; }
/** * Given the target Node, return the DocumentFragment, imported into the * target Document * @param targetNode */ protected final DocumentFragment getImportedComponentFragment(Node targetNode) { Document targetDocument = targetNode.getOwnerDocument(); // return a deep import return (DocumentFragment)targetDocument.importNode(_fragment, true); }
/** * Decrypts the supplied EncryptedData and returns the resulting DOM {@link DocumentFragment}. * * @param encryptedData encrypted data element containing the data to be decrypted * @return the decrypted DOM {@link DocumentFragment} * @throws DecryptionException exception indicating a decryption error */ public DocumentFragment decryptDataToDOM(EncryptedData encryptedData) throws DecryptionException { if (resolver == null && encKeyResolver == null) { log.error("Decryption can not be attempted, required resolvers are not available"); throw new DecryptionException("Unable to decrypt EncryptedData, required resolvers are not available"); } DocumentFragment docFrag = null; if (resolver != null) { docFrag = decryptUsingResolvedKey(encryptedData); if (docFrag != null) { return docFrag; } else { log.debug("Failed to decrypt EncryptedData using standard KeyInfo resolver"); } } String algorithm = encryptedData.getEncryptionMethod().getAlgorithm(); if (DatatypeHelper.isEmpty(algorithm)) { String msg = "EncryptedData's EncryptionMethod Algorithm attribute was empty, " + "key decryption could not be attempted"; log.error(msg); throw new DecryptionException(msg); } if (encKeyResolver != null) { docFrag = decryptUsingResolvedEncryptedKey(encryptedData, algorithm); if (docFrag != null) { return docFrag; } else { log.debug("Failed to decrypt EncryptedData using EncryptedKeyResolver"); } } log.error("Failed to decrypt EncryptedData using either EncryptedData KeyInfoCredentialResolver " + "or EncryptedKeyResolver + EncryptedKey KeyInfoCredentialResolver"); throw new DecryptionException("Failed to decrypt EncryptedData"); }