Пример #1
0
  @Override
  protected Node toNode(AbstractWmlConversionContext context, R.Sym sym, Document doc)
      throws TransformerException {
    String value = sym.getChar();

    // Pre-process according to ECMA-376 2.3.3.29
    if (value.startsWith("F0") || value.startsWith("f0")) {
      value = value.substring(2);
    }

    Text theChar = doc.createTextNode(new String(hexStringToByteArray(value)));

    DocumentFragment docfrag = doc.createDocumentFragment();

    String fontName = sym.getFont();
    PhysicalFont pf = context.getWmlPackage().getFontMapper().getFontMappings().get(fontName);

    if (pf == null) {
      log.warn("No physical font present for:" + fontName);
      docfrag.appendChild(theChar);

    } else {

      Element span = doc.createElement("span");
      docfrag.appendChild(span);

      span.setAttribute("style", "font-family:" + pf.getName());
      span.appendChild(theChar);
    }

    return docfrag;
  }
Пример #2
0
  /**
   * This method is an extension that implements as a Xalan extension the node-set function also
   * found in xt and saxon. If the argument is a Result Tree Fragment, then <code>nodeset</code>
   * returns a node-set consisting of a single root node as described in section 11.1 of the XSLT
   * 1.0 Recommendation. If the argument is a node-set, <code>nodeset</code> returns a node-set. If
   * the argument is a string, number, or boolean, then <code>nodeset</code> returns a node-set
   * consisting of a single root node with a single text node child that is the result of calling
   * the XPath string() function on the passed parameter. If the argument is anything else, then a
   * node-set is returned consisting of a single root node with a single text node child that is the
   * result of calling the java <code>toString()</code> method on the passed argument. Most of the
   * actual work here is done in <code>MethodResolver</code> and <code>XRTreeFrag</code>.
   *
   * @param myProcessor Context passed by the extension processor
   * @param rtf Argument in the stylesheet to the nodeset extension function
   *     <p>NEEDSDOC ($objectName$) @return
   */
  public static NodeSet nodeset(ExpressionContext myProcessor, Object rtf) {

    String textNodeValue;

    if (rtf instanceof NodeIterator) {
      return new NodeSet((NodeIterator) rtf);
    } else {
      if (rtf instanceof String) {
        textNodeValue = (String) rtf;
      } else if (rtf instanceof Boolean) {
        textNodeValue = new XBoolean(((Boolean) rtf).booleanValue()).str();
      } else if (rtf instanceof Double) {
        textNodeValue = new XNumber(((Double) rtf).doubleValue()).str();
      } else {
        textNodeValue = rtf.toString();
      }

      // This no longer will work right since the DTM.
      // Document myDoc = myProcessor.getContextNode().getOwnerDocument();
      try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document myDoc = db.newDocument();

        Text textNode = myDoc.createTextNode(textNodeValue);
        DocumentFragment docFrag = myDoc.createDocumentFragment();

        docFrag.appendChild(textNode);

        return new NodeSet(docFrag);
      } catch (ParserConfigurationException pce) {
        throw new org.apache.xml.utils.WrappedRuntimeException(pce);
      }
    }
  }
Пример #3
0
  public static DocumentFragment shapeToSVG(SvgConversionContext context, NodeIterator shapeIt) {

    DocumentFragment docfrag = null;
    Document d = null;

    try {
      Object shape = null;
      if (shapeIt != null) {
        Node n = shapeIt.nextNode();
        if (n == null) {
          d = makeErr("[null node?!]");
        } else {
          log.debug("Handling " + n.getNodeName());

          if (n.getNodeName().equals("p:cxnSp")) {

            shape = nodeToObjectModel(n, CxnSp.class);
            d = CxnSpToSVG((CxnSp) shape);

          } else {
            log.info("** TODO " + n.getNodeName());
            d = makeErr("[" + n.getNodeName() + "]");
          }
        }
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
      d = makeErr(e.getMessage());
    }

    // Machinery
    docfrag = d.createDocumentFragment();
    docfrag.appendChild(d.getDocumentElement());
    return docfrag;
  }
 private static <T> T getParamXPath(
     final Class<T> pClass, final String pXpath, final CompactFragment pBody) throws XmlException {
   // TODO Avoid JAXB where possible, use XMLDeserializer instead
   final boolean string = CharSequence.class.isAssignableFrom(pClass);
   Node match;
   DocumentFragment fragment =
       DomUtil.childrenToDocumentFragment(XMLFragmentStreamReader.from(pBody));
   for (Node n = fragment.getFirstChild(); n != null; n = n.getNextSibling()) {
     match = xpathMatch(n, pXpath);
     if (match != null) {
       if (!string) {
         XmlDeserializer deserializer = pClass.getAnnotation(XmlDeserializer.class);
         if (deserializer != null) {
           try {
             XmlDeserializerFactory<?> factory = deserializer.value().newInstance();
             factory.deserialize(XmlStreaming.newReader(new DOMSource(n)));
           } catch (InstantiationException | IllegalAccessException e) {
             throw new RuntimeException(e);
           }
         } else {
           return JAXB.unmarshal(new DOMSource(match), pClass);
         }
       } else {
         return pClass.cast(nodeToString(match));
       }
     }
   }
   return null;
 }
Пример #5
0
 @Method("GET")
 @Path("?fragment")
 @requires("urn:test:grant")
 @Type("application/xml")
 public DocumentFragment fragment() throws ParserConfigurationException {
   Document doc = builder.newDocumentBuilder().newDocument();
   DocumentFragment frag = doc.createDocumentFragment();
   Element element = doc.createElement("fragment");
   frag.appendChild(element);
   return frag;
 }
Пример #6
0
 private DocumentFragment appendPushContent(
     final DocumentFragment pushcontent, final DocumentFragment target) {
   DocumentFragment df = target;
   if (df == null) {
     df = pushDocument.createDocumentFragment();
   }
   final NodeList children = pushcontent.getChildNodes();
   for (int i = 0; i < children.getLength(); i++) {
     df.appendChild(pushDocument.importNode(children.item(i), true));
   }
   return df;
 }
Пример #7
0
  /**
   * Create some content in the context of a given document
   *
   * @return
   *     <ul>
   *       <li>A {@link DocumentFragment} if <code>text</code> is well-formed.
   *       <li><code>null</code>, if <code>text</code> is plain text or not well formed
   *     </ul>
   */
  static final DocumentFragment createContent(Document doc, String text) {

    // Text might hold XML content
    if (text != null && text.contains("<")) {
      DocumentBuilder builder = builder();

      try {

        // [#128] Trimming will get rid of leading and trailing whitespace, which would
        // otherwise cause a HIERARCHY_REQUEST_ERR raised by the parser
        text = text.trim();

        // There is a processing instruction. We can safely assume
        // valid XML and parse it as such
        if (text.startsWith("<?xml")) {
          Document parsed = builder.parse(new InputSource(new StringReader(text)));
          DocumentFragment fragment = parsed.createDocumentFragment();
          fragment.appendChild(parsed.getDocumentElement());

          return (DocumentFragment) doc.importNode(fragment, true);
        }

        // Any XML document fragment. To be on the safe side, fragments
        // are wrapped in a dummy root node
        else {
          String wrapped = "<dummy>" + text + "</dummy>";
          Document parsed = builder.parse(new InputSource(new StringReader(wrapped)));
          DocumentFragment fragment = parsed.createDocumentFragment();
          NodeList children = parsed.getDocumentElement().getChildNodes();

          // appendChild removes children also from NodeList!
          while (children.getLength() > 0) {
            fragment.appendChild(children.item(0));
          }

          return (DocumentFragment) doc.importNode(fragment, true);
        }
      }

      // This does not occur
      catch (IOException ignore) {
      }

      // The XML content is invalid
      catch (SAXException ignore) {
      }
    }

    // Plain text or invalid XML
    return null;
  }
Пример #8
0
 public W3CDOMStreamReader(DocumentFragment docfrag) {
   super(
       new ElementFrame<Node, Node>(docfrag, true) {
         public boolean isDocumentFragment() {
           return true;
         }
       });
   this.document = docfrag.getOwnerDocument();
 }
Пример #9
0
 public static String getStringRepresentation(DocumentFragment df) {
   StringBuilder sb = new StringBuilder();
   NodeList nl = df.getChildNodes();
   for (int i = 0; i < nl.getLength(); i++) {
     Node n = nl.item(i);
     sb.append(nodeToString(n));
   }
   return sb.toString();
 }
Пример #10
0
  public static DocumentFragment createBlockForR(
      SvgConversionContext context, NodeIterator rPrNodeIt, NodeIterator childResults) {

    DocumentFragment docfrag = null;
    Document d = null;
    Element span = null;

    try {

      // Create a DOM builder and parse the fragment
      d = XmlUtils.getNewDocumentBuilder().newDocument();

      span = d.createElement("span");
      d.appendChild(span);

      CTTextCharacterProperties textCharProps =
          (CTTextCharacterProperties)
              nodeToObjectModel(rPrNodeIt.nextNode(), CTTextCharacterProperties.class);

      RPr rPr = TextStyles.getWmlRPr(textCharProps);

      // Does our rPr contain anything else?
      StringBuilder inlineStyle = new StringBuilder();
      HtmlCssHelper.createCss(context.getPmlPackage(), rPr, inlineStyle);
      if (!inlineStyle.toString().equals("")) {
        span.setAttribute("style", inlineStyle.toString());
      }

      Node n = childResults.nextNode();
      XmlUtils.treeCopy(n, span);

    } catch (Exception e) {
      log.error(e.getMessage(), e);
      // If something went wrong with the formatting,
      // still try to display the text!
      Node n = childResults.nextNode();
      XmlUtils.treeCopy(n, span);
    }

    // Machinery
    docfrag = d.createDocumentFragment();
    docfrag.appendChild(d.getDocumentElement());
    return docfrag;
  }
Пример #11
0
 public static Node coerceToNode(ELContext ctx, Object value) {
   if (value == null) {
     return null;
   } else if (value instanceof XmlNode) {
     return ((XmlNode) value).toDOM();
   } else if (value instanceof Node) {
     return (Node) value;
   } else if (value instanceof ClosureObject) {
     Object obj = ((ClosureObject) value).invoke(ctx, "toXML", ELUtils.NO_PARAMS);
     return coerceToNode(ctx, obj);
   } else if (value instanceof Iterable) {
     DocumentFragment frag = getContextDocument(ctx).createDocumentFragment();
     for (Iterator i = ((Iterable) value).iterator(); i.hasNext(); )
       frag.appendChild(coerceToNode(ctx, i.next()));
     return frag;
   } else {
     String text = TypeCoercion.coerceToString(value);
     return getContextDocument(ctx).createTextNode(text);
   }
 }
Пример #12
0
  @NotNull
  @Override
  public SimpleAdapter marshal(@NotNull final XmlSerializable v) throws Exception {

    final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    final Document document = dbf.newDocumentBuilder().newDocument();
    final DocumentFragment content = document.createDocumentFragment();
    final XMLOutputFactory xof = XMLOutputFactory.newFactory();
    final XMLStreamWriter out = xof.createXMLStreamWriter(new DOMResult(content));

    v.serialize(XmlStreaming.newWriter(new DOMResult(content)));
    final int childCount = content.getChildNodes().getLength();
    if (childCount == 0) {
      return new SimpleAdapter();
    } else if (childCount == 1) {
      final SimpleAdapter result = new SimpleAdapter();
      final Node child = content.getFirstChild();
      if (child instanceof Element) {
        result.setAttributes(child.getAttributes());
        for (Node child2 = child.getFirstChild();
            child2 != null;
            child2 = child2.getNextSibling()) {
          result.children.add(child2);
        }
      } else {
        result.children.add(child);
      }
      return result;
    } else { // More than one child
      final SimpleAdapter result = new SimpleAdapter();
      for (Node child = content.getFirstChild(); child != null; child = child.getNextSibling()) {
        result.children.add(child);
      }
      return result;
    }
  }
Пример #13
0
  /**
   * @param ctx
   * @param inputSource
   * @return the Node resulting from the parse of the source
   * @throws XMLEncryptionException
   */
  private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException {
    try {
      if (dbf == null) {
        dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
        dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);
        dbf.setValidating(false);
      }
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document d = db.parse(inputSource);

      Document contextDocument = null;
      if (Node.DOCUMENT_NODE == ctx.getNodeType()) {
        contextDocument = (Document) ctx;
      } else {
        contextDocument = ctx.getOwnerDocument();
      }

      Element fragElt = (Element) contextDocument.importNode(d.getDocumentElement(), true);
      DocumentFragment result = contextDocument.createDocumentFragment();
      Node child = fragElt.getFirstChild();
      while (child != null) {
        fragElt.removeChild(child);
        result.appendChild(child);
        child = fragElt.getFirstChild();
      }
      return result;
    } catch (SAXException se) {
      throw new XMLEncryptionException("empty", se);
    } catch (ParserConfigurationException pce) {
      throw new XMLEncryptionException("empty", pce);
    } catch (IOException ioe) {
      throw new XMLEncryptionException("empty", ioe);
    }
  }
Пример #14
0
 /** Rewrite link attributes. */
 private DocumentFragment replaceContent(final DocumentFragment pushcontent) {
   final NodeList children = pushcontent.getChildNodes();
   for (int i = 0; i < children.getLength(); i++) {
     final Node child = children.item(i);
     switch (child.getNodeType()) {
       case Node.ELEMENT_NODE:
         final Element e = (Element) child;
         replaceLinkAttributes(e);
         final NodeList elements = e.getElementsByTagName("*");
         for (int j = 0; i < elements.getLength(); i++) {
           replaceLinkAttributes((Element) elements.item(j));
         }
         break;
     }
   }
   return pushcontent;
 }
Пример #15
0
  /**
   * Append a node to the current container.
   *
   * @param newNode New node to append
   */
  protected void append(Node newNode) throws org.xml.sax.SAXException {

    Node currentNode = m_currentNode;

    if (null != currentNode) {
      currentNode.appendChild(newNode);

      // System.out.println(newNode.getNodeName());
    } else if (null != m_docFrag) {
      m_docFrag.appendChild(newNode);
    } else {
      boolean ok = true;
      short type = newNode.getNodeType();

      if (type == Node.TEXT_NODE) {
        String data = newNode.getNodeValue();

        if ((null != data) && (data.trim().length() > 0)) {
          throw new org.xml.sax.SAXException(
              XSLMessages.createXPATHMessage(
                  XPATHErrorResources.ER_CANT_OUTPUT_TEXT_BEFORE_DOC,
                  null)); // "Warning: can't output text before document element!  Ignoring...");
        }

        ok = false;
      } else if (type == Node.ELEMENT_NODE) {
        if (m_doc.getDocumentElement() != null) {
          throw new org.xml.sax.SAXException(
              XSLMessages.createXPATHMessage(
                  XPATHErrorResources.ER_CANT_HAVE_MORE_THAN_ONE_ROOT,
                  null)); // "Can't have more than one root on a DOM!");
        }
      }

      if (ok) m_doc.appendChild(newNode);
    }
  }
Пример #16
0
 @Method("PUT")
 @Path("?fragment")
 @requires("urn:test:grant")
 public void fragment(@Type("*/*") DocumentFragment frag) throws ParserConfigurationException {
   assert frag.hasChildNodes();
 }
 @XContent
 protected void setGuards(DocumentFragment content) {
   Node node = content.getFirstChild();
   while (node != null) {
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       String name = node.getNodeName();
       if ("guard".equals(name)) {
         NamedNodeMap map = node.getAttributes();
         Node aId = map.getNamedItem("id");
         Node aType = map.getNamedItem("type");
         if (aId == null) {
           throw new IllegalArgumentException("id is required");
         }
         String id = aId.getNodeValue();
         if (aType == null) {
           throw new IllegalArgumentException("type is required");
         } else {
           // String value = node.getTextContent().trim();
           // guards.put(id, new ScriptGuard(value));
           // TODO: compound guard
         }
         String type = aType.getNodeValue();
         if ("permission".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new PermissionGuard(value));
         } else if ("isAdministrator".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new IsAdministratorGuard(value));
         } else if ("facet".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new FacetGuard(value));
         } else if ("type".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new TypeGuard(value));
         } else if ("schema".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new SchemaGuard(value));
         } else if ("user".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new UserGuard(value));
         } else if ("group".equals(type)) {
           String value = node.getTextContent().trim();
           guards.put(id, new GroupGuard(value));
         } else if ("script".equals(type)) {
           Node engineNode = map.getNamedItem("engine");
           if (engineNode == null) {
             throw new IllegalArgumentException(
                 "Must specify an engine attribute on script guards");
           }
           String value = node.getTextContent().trim();
           guards.put(id, new ScriptGuard(engineNode.getNodeValue(), value));
         } else if ("expression".equals(type)) {
           String value = node.getTextContent().trim();
           try {
             guards.put(id, PermissionService.getInstance().parse(value, guards));
           } catch (ParseException e) {
             log.error(e, e);
           }
         } else { // the type should be a guard factory
           String value = node.getTextContent().trim();
           try {
             Class<?> factory = Class.forName(type);
             Guard guard = ((GuardFactory) factory.newInstance()).newGuard(value);
             guards.put(id, guard);
           } catch (Exception e) {
             log.error(e, e); // TODO should throw a DeployException
           }
         }
       }
     }
     node = node.getNextSibling();
   }
 }
Пример #18
0
  public Node toNode(Model tableModel, TransformState transformState, Document doc)
      throws TransformerException {
    TableModel table = (TableModel) tableModel;
    getLog().debug("Table asXML:\n" + table.debugStr());

    DocumentFragment docfrag = doc.createDocumentFragment();
    Element tableRoot = createNode(doc, null, NODE_TABLE);
    List<Property> rowProperties = new ArrayList<Property>();
    int rowPropertiesTableSize = -1;

    List<Property> cellProperties = new ArrayList<Property>();
    int cellPropertiesTableSize = -1;
    int cellPropertiesRowSize = -1;
    boolean inHeader = (table.getHeaderMaxRow() > -1);

    TableModelRow rowModel = null;
    Element rowContainer = null;
    Element row = null;
    Element cellNode = null;

    createRowProperties(rowProperties, table.getEffectiveTableStyle().getTrPr(), true);
    rowPropertiesTableSize = rowProperties.size();
    createCellProperties(cellProperties, table.getEffectiveTableStyle().getTrPr());
    createCellProperties(cellProperties, table.getEffectiveTableStyle().getTcPr());
    // will apply these as a default on each td, and then override
    createCellProperties(cellProperties, table.getEffectiveTableStyle().getTblPr());
    cellPropertiesTableSize = cellProperties.size();

    docfrag.appendChild(tableRoot);
    applyTableStyles(table, transformState, tableRoot);

    // setup column widths
    createColumns(table, transformState, doc, tableRoot);

    rowContainer = createNode(doc, tableRoot, (inHeader ? NODE_TABLE_HEADER : NODE_TABLE_BODY));
    tableRoot.appendChild(rowContainer);

    applyTableRowContainerCustomAttributes(table, transformState, rowContainer, inHeader);

    for (int rowIndex = 0; rowIndex < table.getCells().size(); rowIndex++) {
      rowModel = table.getCells().get(rowIndex);

      if ((inHeader) && (rowIndex > table.getHeaderMaxRow())) {
        rowContainer = createNode(doc, tableRoot, NODE_TABLE_BODY);
        tableRoot.appendChild(rowContainer);
        inHeader = false;
        applyTableRowContainerCustomAttributes(table, transformState, rowContainer, inHeader);
      }
      row = createNode(doc, rowContainer, (inHeader ? NODE_TABLE_HEADER_ROW : NODE_TABLE_BODY_ROW));
      TrPr trPr = rowModel.getRowProperties();
      CTTblPrEx tblPrEx = rowModel.getRowPropertiesExceptions();

      createRowProperties(rowProperties, trPr, false);
      processAttributes(rowProperties, row);
      applyTableRowCustomAttributes(table, transformState, row, rowIndex, inHeader);

      createCellProperties(cellProperties, trPr);
      createCellProperties(cellProperties, tblPrEx);
      cellPropertiesRowSize = cellProperties.size();

      for (Cell cell : rowModel.getRowContents()) {
        // process cell

        if (cell.isDummy()) {
          if (!cell.isVMerged()) {
            // Dummy-Cells resulting from vertical merged cells shouldn't be included
            cellNode =
                createNode(doc, row, (inHeader ? NODE_TABLE_HEADER_CELL : NODE_TABLE_BODY_CELL));
            row.appendChild(cellNode);
            applyTableCellCustomAttributes(table, transformState, cell, cellNode, inHeader, true);
          }
        } else {

          cellNode =
              createNode(doc, row, (inHeader ? NODE_TABLE_HEADER_CELL : NODE_TABLE_BODY_CELL));
          row.appendChild(cellNode);
          // Apply cell style
          createCellProperties(cellProperties, cell.getTcPr());
          processAttributes(cellProperties, cellNode);
          applyTableCellCustomAttributes(table, transformState, cell, cellNode, inHeader, false);
          // remove properties defined on cell level
          resetProperties(cellProperties, cellPropertiesRowSize);

          // insert content into cell
          // skipping w:tc node itself, insert only its children
          if (cell.getContent() == null) {
            getLog().warn("model cell had no contents!");
          } else {
            getLog().debug("copying cell contents..");
            XmlUtils.treeCopy(cell.getContent().getChildNodes(), cellNode);
          }
        }
      }
      // remove properties defined on row level
      resetProperties(cellProperties, cellPropertiesTableSize);
      resetProperties(rowProperties, rowPropertiesTableSize);
    }
    return docfrag;
  }
Пример #19
0
  public static DocumentFragment createBlockForP(
      SvgConversionContext context,
      String lvl,
      String cNvPrName,
      String phType,
      NodeIterator childResults,
      NodeIterator lvlNpPr) {

    StyleTree styleTree = null;
    try {
      styleTree = context.getPmlPackage().getStyleTree();
    } catch (InvalidFormatException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    log.debug("lvl:" + lvl);
    int level;
    if (lvl.equals("NaN")) {
      level = 1;
    } else {
      level = Integer.parseInt(lvl);
    }
    String pStyleVal;

    System.out.println("cNvPrName: " + cNvPrName + "; " + "phType: " + phType);

    if (cNvPrName.toLowerCase().indexOf("subtitle") > -1
        || phType.toLowerCase().indexOf("subtitle") > -1) {
      // Subtitle on first page in default layout is styled as a Body.
      pStyleVal = "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Body";
    } else if (cNvPrName.toLowerCase().indexOf("title") > -1
        || phType.toLowerCase().indexOf("title") > -1) {
      pStyleVal =
          "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Title";
    } else {
      // eg cNvPrName: TextBox 2; phType:
      pStyleVal =
          "Lvl" + level + "Master" + context.getResolvedLayout().getMasterNumber() + "Other";
    }
    System.out.println("--> " + pStyleVal);

    try {

      // Create a DOM builder and parse the fragment
      Document document = XmlUtils.getNewDocumentBuilder().newDocument();

      // log.info("Document: " + document.getClass().getName() );

      Node xhtmlP = document.createElement("p");
      document.appendChild(xhtmlP);

      // Set @class
      log.debug(pStyleVal);
      Tree<AugmentedStyle> pTree = styleTree.getParagraphStylesTree();
      org.docx4j.model.styles.Node<AugmentedStyle> asn = pTree.get(pStyleVal);
      ((Element) xhtmlP).setAttribute("class", StyleTree.getHtmlClassAttributeValue(pTree, asn));

      StringBuilder inlineStyle = new StringBuilder();
      // Do we have CTTextParagraphProperties
      // <a:lvl?pPr>
      // Convert it to a WordML pPr
      CTTextParagraphProperties lvlPPr = unmarshalFormatting(lvlNpPr);
      if (lvlPPr != null) {

        log.debug("We have lvlPPr");
        log.debug(
            XmlUtils.marshaltoString(
                lvlPPr,
                true,
                true,
                Context.jcPML,
                "FIXME",
                "lvl1pPr",
                CTTextParagraphProperties.class));
        PPr pPr = TextStyles.getWmlPPr(lvlPPr);
        if (pPr != null) {
          HtmlCssHelper.createCss(context.getPmlPackage(), pPr, inlineStyle, false, false);
        }
        // TODO RPR
      }
      // Without this, top-margin is too large in Webkit (Midor).
      // Not tested elsewhere...
      inlineStyle.append("margin-left:3px; margin-top:3px;");

      if (!inlineStyle.toString().equals("")) {
        ((Element) xhtmlP).setAttribute("style", inlineStyle.toString());
      }

      // Our fo:block wraps whatever result tree fragment
      // our style sheet produced when it applied-templates
      // to the child nodes
      // init
      Node n = childResults.nextNode();
      do {

        // getNumberXmlNode creates a span node, which is empty
        // if there is no numbering.
        // Let's get rid of any such <span/>.

        // What we actually get is a document node
        if (n.getNodeType() == Node.DOCUMENT_NODE) {
          log.debug("handling DOCUMENT_NODE");
          // Do just enough of the handling here
          NodeList nodes = n.getChildNodes();
          if (nodes != null) {
            for (int i = 0; i < nodes.getLength(); i++) {

              if (((Node) nodes.item(i)).getLocalName().equals("span")
                  && !((Node) nodes.item(i)).hasChildNodes()) {
                // ignore
                log.debug(".. ignoring <span/> ");
              } else {
                XmlUtils.treeCopy((Node) nodes.item(i), xhtmlP);
              }
            }
          }
        } else {

          //					log.info("Node we are importing: " + n.getClass().getName() );
          //					foBlockElement.appendChild(
          //							document.importNode(n, true) );
          /*
           * Node we'd like to import is of type org.apache.xml.dtm.ref.DTMNodeProxy
           * which causes
           * org.w3c.dom.DOMException: NOT_SUPPORTED_ERR: The implementation does not support the requested type of object or operation.
           *
           * See http://osdir.com/ml/text.xml.xerces-j.devel/2004-04/msg00066.html
           *
           * So instead of importNode, use
           */
          XmlUtils.treeCopy(n, xhtmlP);
        }
        // next
        n = childResults.nextNode();

      } while (n != null);

      DocumentFragment docfrag = document.createDocumentFragment();
      docfrag.appendChild(document.getDocumentElement());

      return docfrag;

    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }

    return null;
  }
Пример #20
0
  @Override
  public void startElement(
      final String uri, final String localName, final String name, final Attributes atts)
      throws SAXException {
    if (start) {
      // if start is true, we need to record content in pushcontent
      // also we need to add level to make sure start is turn off
      // at the corresponding end element
      level++;
      putElement(name, atts, false);
    }

    final String conactValue = atts.getValue(ATTRIBUTE_NAME_CONACTION);
    if (!start && conactValue != null) {
      if (ATTR_CONACTION_VALUE_PUSHBEFORE.equals(conactValue)) {
        if (pushcontentDocumentFragment.getChildNodes().getLength() != 0) {
          // there are redundant "pushbefore", create a new pushcontent and emit a warning message.
          if (pushcontentWriter != null) {
            try {
              pushcontentWriter.close();
            } catch (final XMLStreamException e) {
              throw new SAXException(e);
            }
          }
          pushcontentWriter = getXMLStreamWriter();
          logger.warn(
              MessageUtils.getInstance().getMessage("DOTJ044W").setLocation(atts).toString());
        }
        start = true;
        level = 1;
        putElement(name, atts, true);
        pushType = ATTR_CONACTION_VALUE_PUSHBEFORE;
      } else if (ATTR_CONACTION_VALUE_PUSHAFTER.equals(conactValue)) {
        start = true;
        level = 1;
        if (target == null) {
          logger.error(
              MessageUtils.getInstance().getMessage("DOTJ039E").setLocation(atts).toString());
        } else {
          putElement(name, atts, true);
          pushType = ATTR_CONACTION_VALUE_PUSHAFTER;
        }
      } else if (ATTR_CONACTION_VALUE_PUSHREPLACE.equals(conactValue)) {
        start = true;
        level = 1;
        target = toURI(atts.getValue(ATTRIBUTE_NAME_CONREF));
        if (target == null) {
          logger.error(
              MessageUtils.getInstance().getMessage("DOTJ040E").setLocation(atts).toString());
        } else {
          pushType = ATTR_CONACTION_VALUE_PUSHREPLACE;
          putElement(name, atts, true);
        }

      } else if (ATTR_CONACTION_VALUE_MARK.equals(conactValue)) {
        target = toURI(atts.getValue(ATTRIBUTE_NAME_CONREF));
        if (target == null) {
          logger.error(
              MessageUtils.getInstance().getMessage("DOTJ068E").setLocation(atts).toString());
        }
        if (target != null
            && pushcontentDocumentFragment != null
            && pushcontentDocumentFragment.getChildNodes().getLength() > 0
            && ATTR_CONACTION_VALUE_PUSHBEFORE.equals(pushType)) {
          // pushcontent != null means it is pushbefore action
          // we need to add target and content to pushtable
          if (pushcontentWriter != null) {
            try {
              pushcontentWriter.close();
            } catch (final XMLStreamException e) {
              throw new SAXException(e);
            }
          }
          addtoPushTable(target, replaceContent(pushcontentDocumentFragment), pushType);
          pushcontentWriter = getXMLStreamWriter();
          target = null;
          pushType = null;
        }
      }
    } // else if (pushcontent != null && pushcontent.length() > 0 && level == 0) {
    // if there is no element with conaction="mark" after
    // one with conaction="pushbefore", report syntax error

    // }
  }
Пример #21
0
  /**
   * Adjust column widths in an HTML table.
   *
   * <p>The specification of column widths in CALS (a relative width plus an optional absolute
   * width) are incompatible with HTML column widths. This method adjusts CALS column width
   * specifiers in an attempt to produce equivalent HTML specifiers.
   *
   * <p>In order for this method to work, the CALS width specifications should be placed in the
   * "width" attribute of the &lt;col>s within a &lt;colgroup>. Then the colgroup result tree
   * fragment is passed to this method.
   *
   * <p>This method makes use of two parameters from the XSL stylesheet that calls it: <code>
   * nominal.table.width</code> and <code>table.width</code>. The value of <code>nominal.table.width
   * </code> must be an absolute distance. The value of <code>table.width</code> can be either
   * absolute or relative.
   *
   * <p>Presented with a mixture of relative and absolute lengths, the table width is used to
   * calculate appropriate values. If the <code>table.width</code> is relative, the nominal width is
   * used for this calculation.
   *
   * <p>There are three possible combinations of values:
   *
   * <ol>
   *   <li>There are no relative widths; in this case the absolute widths are used in the HTML
   *       table.
   *   <li>There are no absolute widths; in this case the relative widths are used in the HTML
   *       table.
   *   <li>There are a mixture of absolute and relative widths:
   *       <ol>
   *         <li>If the table width is absolute, all widths become absolute.
   *         <li>If the table width is relative, make all the widths absolute relative to the
   *             nominal table width then turn them all back into relative widths.
   *       </ol>
   * </ol>
   *
   * @param context The stylesheet context; supplied automatically by Xalan
   * @param xalanNI
   * @return The result tree fragment containing the adjusted colgroup.
   */
  public DocumentFragment adjustColumnWidths(ExpressionContext context, NodeIterator xalanNI) {

    int nominalWidth = convertLength(Params.getString(context, "nominal.table.width"));
    String tableWidth = Params.getString(context, "table.width");
    String styleType = Params.getString(context, "stylesheet.result.type");
    boolean foStylesheet = styleType.equals("fo");

    DocumentFragment xalanRTF = (DocumentFragment) xalanNI.nextNode();
    Element colgroup = (Element) xalanRTF.getFirstChild();

    // N.B. ...stree.ElementImpl doesn't implement getElementsByTagName()

    Node firstCol = null;
    // If this is an FO tree, there might be no colgroup...
    if (colgroup.getLocalName().equals("colgroup")) {
      firstCol = colgroup.getFirstChild();
    } else {
      firstCol = colgroup;
    }

    // Count the number of columns...
    Node child = firstCol;
    int numColumns = 0;
    while (child != null) {
      if (child.getNodeType() == Node.ELEMENT_NODE
          && (child.getNodeName().equals("col")
              || (child.getNamespaceURI().equals(foURI)
                  && child.getLocalName().equals("table-column")))) {
        numColumns++;
      }

      child = child.getNextSibling();
    }

    String widths[] = new String[numColumns];
    Element columns[] = new Element[numColumns];
    int colnum = 0;

    child = firstCol;
    while (child != null) {
      if (child.getNodeType() == Node.ELEMENT_NODE
          && (child.getNodeName().equals("col")
              || (child.getNamespaceURI().equals(foURI)
                  && child.getLocalName().equals("table-column")))) {
        Element col = (Element) child;

        columns[colnum] = col;

        if (foStylesheet) {
          if ("".equals(col.getAttribute("column-width"))) {
            widths[colnum] = "1*";
          } else {
            widths[colnum] = col.getAttribute("column-width");
          }
        } else {
          if ("".equals(col.getAttribute("width"))) {
            widths[colnum] = "1*";
          } else {
            widths[colnum] = col.getAttribute("width");
          }
        }

        colnum++;
      }
      child = child.getNextSibling();
    }

    float relTotal = 0;
    float relParts[] = new float[numColumns];

    float absTotal = 0;
    float absParts[] = new float[numColumns];

    for (int count = 0; count < numColumns; count++) {
      String width = widths[count];
      int pos = width.indexOf("*");
      if (pos >= 0) {
        String relPart = width.substring(0, pos);
        String absPart = width.substring(pos + 1);

        try {
          float rel = Float.parseFloat(relPart);
          relTotal += rel;
          relParts[count] = rel;
        } catch (NumberFormatException e) {
          System.out.println(relPart + " is not a valid relative unit.");
        }

        int pixels = 0;
        if (absPart != null && !absPart.equals("")) {
          pixels = convertLength(absPart);
        }

        absTotal += pixels;
        absParts[count] = pixels;
      } else {
        relParts[count] = 0;

        int pixels = 0;
        if (width != null && !width.equals("")) {
          pixels = convertLength(width);
        }

        absTotal += pixels;
        absParts[count] = pixels;
      }
    }

    // Ok, now we have the relative widths and absolute widths in
    // two parallel arrays.
    //
    // - If there are no relative widths, output the absolute widths
    // - If there are no absolute widths, output the relative widths
    // - If there are a mixture of relative and absolute widths,
    //   - If the table width is absolute, turn these all into absolute
    //     widths.
    //   - If the table width is relative, turn these all into absolute
    //     widths in the nominalWidth and then turn them back into
    //     percentages.

    if (relTotal == 0) {
      for (int count = 0; count < numColumns; count++) {
        Float f = new Float(absParts[count]);
        if (foStylesheet) {
          int pixels = f.intValue();
          float inches = (float) pixels / pixelsPerInch;
          widths[count] = inches + "in";
        } else {
          widths[count] = Integer.toString(f.intValue());
        }
      }
    } else if (absTotal == 0) {
      for (int count = 0; count < numColumns; count++) {
        float rel = relParts[count] / relTotal * 100;
        Float f = new Float(rel);
        widths[count] = Integer.toString(f.intValue());
      }
      widths = correctRoundingError(widths);
    } else {
      int pixelWidth = nominalWidth;

      if (tableWidth.indexOf("%") <= 0) {
        pixelWidth = convertLength(tableWidth);
      }

      if (pixelWidth <= absTotal) {
        System.out.println("Table is wider than table width.");
      } else {
        pixelWidth -= absTotal;
      }

      absTotal = 0;
      for (int count = 0; count < numColumns; count++) {
        float rel = relParts[count] / relTotal * pixelWidth;
        relParts[count] = rel + absParts[count];
        absTotal += rel + absParts[count];
      }

      if (tableWidth.indexOf("%") <= 0) {
        for (int count = 0; count < numColumns; count++) {
          Float f = new Float(relParts[count]);
          if (foStylesheet) {
            int pixels = f.intValue();
            float inches = (float) pixels / pixelsPerInch;
            widths[count] = inches + "in";
          } else {
            widths[count] = Integer.toString(f.intValue());
          }
        }
      } else {
        for (int count = 0; count < numColumns; count++) {
          float rel = relParts[count] / absTotal * 100;
          Float f = new Float(rel);
          widths[count] = Integer.toString(f.intValue());
        }
        widths = correctRoundingError(widths);
      }
    }

    // Now rebuild the colgroup with the right widths

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;

    try {
      docBuilder = docFactory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
      System.out.println("PCE!");
      return xalanRTF;
    }
    Document doc = docBuilder.newDocument();
    DocumentFragment df = doc.createDocumentFragment();
    DOMBuilder rtf = new DOMBuilder(doc, df);

    try {
      String ns = colgroup.getNamespaceURI();
      String localName = colgroup.getLocalName();
      String name = colgroup.getTagName();

      if (colgroup.getLocalName().equals("colgroup")) {
        rtf.startElement(ns, localName, name, copyAttributes(colgroup));
      }

      for (colnum = 0; colnum < numColumns; colnum++) {
        Element col = columns[colnum];

        NamedNodeMap domAttr = col.getAttributes();

        AttributesImpl attr = new AttributesImpl();
        for (int acount = 0; acount < domAttr.getLength(); acount++) {
          Node a = domAttr.item(acount);
          String a_ns = a.getNamespaceURI();
          String a_localName = a.getLocalName();

          if ((foStylesheet && !a_localName.equals("column-width"))
              || !a_localName.equalsIgnoreCase("width")) {
            attr.addAttribute(
                a.getNamespaceURI(), a.getLocalName(), a.getNodeName(), "CDATA", a.getNodeValue());
          }
        }

        if (foStylesheet) {
          attr.addAttribute("", "column-width", "column-width", "CDATA", widths[colnum]);
        } else {
          attr.addAttribute("", "width", "width", "CDATA", widths[colnum]);
        }

        rtf.startElement(col.getNamespaceURI(), col.getLocalName(), col.getTagName(), attr);
        rtf.endElement(col.getNamespaceURI(), col.getLocalName(), col.getTagName());
      }

      if (colgroup.getLocalName().equals("colgroup")) {
        rtf.endElement(ns, localName, name);
      }
    } catch (SAXException se) {
      System.out.println("SE!");
      return xalanRTF;
    }

    return df;
  }
  /**
   * Get references for a given article
   *
   * @param doc article xml
   * @return references
   */
  public ArrayList<CitationReference> getReferences(Document doc) {
    ArrayList<CitationReference> list = new ArrayList<CitationReference>();

    if (doc == null) {
      return list;
    }

    try {
      NodeList refList = getReferenceNodes(doc);

      XPathFactory factory = XPathFactory.newInstance();
      XPath xpath = factory.newXPath();

      XPathExpression typeExpr = xpath.compile("//citation | //nlm-citation | //element-citation");
      XPathExpression titleExpr = xpath.compile("//article-title");
      XPathExpression authorsExpr =
          xpath.compile("//person-group[@person-group-type='author']/name");
      XPathExpression journalExpr = xpath.compile("//source");
      XPathExpression volumeExpr = xpath.compile("//volume");
      XPathExpression numberExpr = xpath.compile("//label");
      XPathExpression fPageExpr = xpath.compile("//fpage");
      XPathExpression lPageExpr = xpath.compile("//lpage");
      XPathExpression yearExpr = xpath.compile("//year");
      XPathExpression publisherExpr = xpath.compile("//publisher-name");

      for (int i = 0; i < refList.getLength(); i++) {

        Node refNode = refList.item(i);
        CitationReference citation = new CitationReference();

        DocumentFragment df = doc.createDocumentFragment();
        df.appendChild(refNode);

        // citation type
        Object resultObj = typeExpr.evaluate(df, XPathConstants.NODE);
        Node resultNode = (Node) resultObj;
        if (resultNode != null) {
          String citationType = getCitationType(resultNode);
          if (citationType != null) {
            citation.setCitationType(citationType);
          }
        }

        // title
        resultObj = titleExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setTitle(resultNode.getTextContent());
        }

        // authors
        resultObj = authorsExpr.evaluate(df, XPathConstants.NODESET);
        NodeList resultNodeList = (NodeList) resultObj;
        ArrayList<String> authors = new ArrayList<String>();
        for (int j = 0; j < resultNodeList.getLength(); j++) {
          Node nameNode = resultNodeList.item(j);
          NodeList namePartList = nameNode.getChildNodes();
          String surName = "";
          String givenName = "";
          for (int k = 0; k < namePartList.getLength(); k++) {
            Node namePartNode = namePartList.item(k);
            if (namePartNode.getNodeName().equals("surname")) {
              surName = namePartNode.getTextContent();
            } else if (namePartNode.getNodeName().equals("given-names")) {
              givenName = namePartNode.getTextContent();
            }
          }
          authors.add(givenName + " " + surName);
        }

        citation.setAuthors(authors);

        // journal title
        resultObj = journalExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setJournalTitle(resultNode.getTextContent());
        }

        // volume
        resultObj = volumeExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setVolume(resultNode.getTextContent());
        }

        // citation number
        resultObj = numberExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setNumber(resultNode.getTextContent());
        }

        // citation pages
        String firstPage = null;
        String lastPage = null;
        resultObj = fPageExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          firstPage = resultNode.getTextContent();
        }

        resultObj = lPageExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          lastPage = resultNode.getTextContent();
        }

        if (firstPage != null) {
          if (lastPage != null) {
            citation.setPages(firstPage + "-" + lastPage);
          } else {
            citation.setPages(firstPage);
          }
        }

        // citation year
        resultObj = yearExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setYear(resultNode.getTextContent());
        }

        // citation publisher
        resultObj = publisherExpr.evaluate(df, XPathConstants.NODE);
        resultNode = (Node) resultObj;
        if (resultNode != null) {
          citation.setPublisher(resultNode.getTextContent());
        }

        list.add(citation);
      }

    } catch (Exception e) {
      log.error("Error occurred while gathering the citation references.", e);
    }

    return list;
  }