Пример #1
0
  /**
   * Handle text node during validation.
   *
   * @param received
   * @param source
   */
  private void doText(Node received, Node source) {
    if (log.isDebugEnabled()) {
      log.debug("Validating node value for element: " + received.getParentNode());
    }

    if (received.getNodeValue() != null) {
      Assert.isTrue(
          source.getNodeValue() != null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              null,
              received.getNodeValue().trim()));

      Assert.isTrue(
          received.getNodeValue().trim().equals(source.getNodeValue().trim()),
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              received.getNodeValue().trim()));
    } else {
      Assert.isTrue(
          source.getNodeValue() == null,
          ValidationUtils.buildValueMismatchErrorMessage(
              "Node value not equal for element '" + received.getParentNode().getLocalName() + "'",
              source.getNodeValue().trim(),
              null));
    }

    if (log.isDebugEnabled()) {
      log.debug("Node value '" + received.getNodeValue().trim() + "': OK");
    }
  }
Пример #2
0
  /**
   * Method getStrFromNode
   *
   * @param xpathnode
   * @return the string for the node.
   */
  public static String getStrFromNode(Node xpathnode) {

    if (xpathnode.getNodeType() == Node.TEXT_NODE) {

      // we iterate over all siblings of the context node because eventually,
      // the text is "polluted" with pi's or comments
      StringBuffer sb = new StringBuffer();

      for (Node currentSibling = xpathnode.getParentNode().getFirstChild();
          currentSibling != null;
          currentSibling = currentSibling.getNextSibling()) {
        if (currentSibling.getNodeType() == Node.TEXT_NODE) {
          sb.append(((Text) currentSibling).getData());
        }
      }

      return sb.toString();
    } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) {
      return ((Attr) xpathnode).getNodeValue();
    } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
      return ((ProcessingInstruction) xpathnode).getNodeValue();
    }

    return null;
  }
Пример #3
0
  /**
   * Pretty prints a node.
   *
   * @param doc The document the node comes from.
   * @param node The node that should be pretty printed.
   */
  public static void prettyPrint(Document doc, Node node) {
    // Get the text before the node and extract the indenting
    Node parent = node.getParentNode();

    String indenting = "";
    NodeList siblingList = parent.getChildNodes();
    for (int i = 1; i < siblingList.getLength(); i++) {
      Node sibling = siblingList.item(i);
      if (sibling == node) {
        Node nodeBefore = siblingList.item(i - 1);
        // Check whether this is a text node
        if (nodeBefore.getNodeName().equals("#text")) {
          // There is text before the node -> Extract the indenting
          String text = nodeBefore.getNodeValue();
          int newlinePos = text.lastIndexOf('\n');
          if (newlinePos != -1) {
            indenting = text.substring(newlinePos);
            if (indenting.trim().length() != 0) {
              // The indenting is no whitespace -> Forget it
              indenting = "";
            }
          }
        }
        break;
      }
    }

    // Now pretty print the node
    prettyPrint(doc, node, indenting);
  }
Пример #4
0
 public XNode getParent() {
   Node parent = node.getParentNode();
   if (parent == null || !(parent instanceof Element)) {
     return null;
   } else {
     return new XNode(xpathParser, parent);
   }
 }
Пример #5
0
  protected void removeAllEmptyNodes(Document document, String xpath, int parentLevel)
      throws TransformerException {
    NodeList emptyElements = XPathAPI.selectNodeList(document, xpath);

    for (int i = emptyElements.getLength() - 1; i > -1; i--) {
      Node nodeToBeRemoved = emptyElements.item(i);
      int hierLevel = parentLevel;
      while (hierLevel-- > 0) {
        nodeToBeRemoved = nodeToBeRemoved.getParentNode();
      }
      nodeToBeRemoved.getParentNode().removeChild(nodeToBeRemoved);
    }
    NodeList moreEmptyElements = XPathAPI.selectNodeList(document, xpath);
    if (moreEmptyElements.getLength() > 0) {
      removeAllEmptyNodes(document, xpath, parentLevel);
    }
  }
Пример #6
0
 private void removeNodes(NodeList nl) {
   int count = nl.getLength();
   for (int i = 0; i < count; i++) {
     Node node = nl.item(i);
     Node parent = node.getParentNode();
     if (parent == null) continue;
     parent.removeChild(node);
   }
 }
Пример #7
0
 public Node insertBetween(Node child, Node prev, Node next) {
   assert prev == null || this == prev.getParentNode();
   assert next == null || this == next.getParentNode();
   assert prev != null || next == firstChild;
   assert next != null || prev == lastChild;
   assert prev == null || next == null || prev.getNextSibling() == next;
   if (next == null) {
     return appendChild(child);
   }
   child.detach();
   child.setParentNode(this);
   child.setNextSibling(next);
   if (prev == null) {
     firstChild = child;
   } else {
     prev.setNextSibling(child);
   }
   return child;
 }
  public ModifyDBInstanceRequest unmarshall(Node node) throws Exception {
    if (node == null) return null;

    ModifyDBInstanceRequest modifyDBInstanceRequest = new ModifyDBInstanceRequest();

    Node dBInstanceIdentifierNode = XpathUtils.asNode("DBInstanceIdentifier", node);
    modifyDBInstanceRequest.setDBInstanceIdentifier(
        new StringUnmarshaller().unmarshall(dBInstanceIdentifierNode));

    Node allocatedStorageNode = XpathUtils.asNode("AllocatedStorage", node);
    modifyDBInstanceRequest.setAllocatedStorage(
        new IntegerUnmarshaller().unmarshall(allocatedStorageNode));

    Node dBInstanceClassNode = XpathUtils.asNode("DBInstanceClass", node);
    modifyDBInstanceRequest.setDBInstanceClass(
        new StringUnmarshaller().unmarshall(dBInstanceClassNode));

    NodeList dBSecurityGroupsNodes =
        XpathUtils.asNodeList("DBSecurityGroups/DBSecurityGroupName", node);
    for (int dBSecurityGroupsIndex = 0;
        dBSecurityGroupsIndex < XpathUtils.nodeLength(dBSecurityGroupsNodes);
        ++dBSecurityGroupsIndex) {
      Node dBSecurityGroupsNode = dBSecurityGroupsNodes.item(dBSecurityGroupsIndex);
      modifyDBInstanceRequest
          .getDBSecurityGroups()
          .add(new StringUnmarshaller().unmarshall(dBSecurityGroupsNode));
      dBSecurityGroupsNode.getParentNode().removeChild(dBSecurityGroupsNode);
    }

    Node applyImmediatelyNode = XpathUtils.asNode("ApplyImmediately", node);
    modifyDBInstanceRequest.setApplyImmediately(
        new BooleanUnmarshaller().unmarshall(applyImmediatelyNode));

    Node masterUserPasswordNode = XpathUtils.asNode("MasterUserPassword", node);
    modifyDBInstanceRequest.setMasterUserPassword(
        new StringUnmarshaller().unmarshall(masterUserPasswordNode));

    Node dBParameterGroupNameNode = XpathUtils.asNode("DBParameterGroupName", node);
    modifyDBInstanceRequest.setDBParameterGroupName(
        new StringUnmarshaller().unmarshall(dBParameterGroupNameNode));

    Node backupRetentionPeriodNode = XpathUtils.asNode("BackupRetentionPeriod", node);
    modifyDBInstanceRequest.setBackupRetentionPeriod(
        new IntegerUnmarshaller().unmarshall(backupRetentionPeriodNode));

    Node preferredBackupWindowNode = XpathUtils.asNode("PreferredBackupWindow", node);
    modifyDBInstanceRequest.setPreferredBackupWindow(
        new StringUnmarshaller().unmarshall(preferredBackupWindowNode));

    Node preferredMaintenanceWindowNode = XpathUtils.asNode("PreferredMaintenanceWindow", node);
    modifyDBInstanceRequest.setPreferredMaintenanceWindow(
        new StringUnmarshaller().unmarshall(preferredMaintenanceWindowNode));

    return modifyDBInstanceRequest;
  }
Пример #9
0
 private String getXPath(Node node, String xpath) {
   if (node == null) {
     return "";
   }
   String nodeName = node.getNodeName();
   Node parent = node.getParentNode();
   if (parent == null) {
     return xpath;
   }
   return getXPath(parent, "/" + nodeName + xpath);
 }
Пример #10
0
 public String getPath() {
   StringBuilder builder = new StringBuilder();
   Node current = node;
   while (current != null && current instanceof Element) {
     if (current != node) {
       builder.insert(0, "/");
     }
     builder.insert(0, current.getNodeName());
     current = current.getParentNode();
   }
   return builder.toString();
 }
Пример #11
0
 public NodeList getImediateElementsByTagName(Element el, String tagname) {
   NodeList list = el.getElementsByTagName(tagname);
   SimpleNodeList result = new SimpleNodeList();
   int length = list.getLength();
   for (int i = 0; i < length; i++) {
     Node node = list.item(i);
     if ((Element) node.getParentNode() == el) {
       result.add(node);
     }
   }
   return result;
 }
Пример #12
0
  @Override
  public boolean equals(Object node1, Node node2) {
    if (node1 == node2) return true;
    NodeInfo n1 = (NodeInfo) node1;
    Node n2 = node2;

    while (true) {
      if (!shallowEquals(n1, n2)) return false;
      if (n1 == null) {
        assert n2 == null;
        return true;
      }
      NodeInfo n1Child = new NodeInfoSequence(n1, Axis.CHILD).findNext();
      Node n2Child = null;
      if (n2.getNodeType() == Node.DOCUMENT_NODE || n2.getNodeType() == Node.ELEMENT_NODE)
        n2Child = n2.getFirstChild(); // the jdk's dom impl returns non-null child for attribute etc
      if (!shallowEquals(n1Child, n2Child)) return false;
      if (n1Child == null) {
        assert n2Child == null;

        if (n1 == node1 && n2 == node2) return true;

        while (true) {
          NodeInfo n1Sibling = new NodeInfoSequence(n1, Axis.FOLLOWING_SIBLING).findNext();
          Node n2Sibling = n2.getNextSibling();
          if (!shallowEquals(n1Sibling, n2Sibling)) return false;
          if (n1Sibling == null) {
            assert n2Sibling == null;
            NodeInfo n1Parent = new NodeInfoSequence(n1, Axis.ANCESTOR).findNext();
            Node n2Parent = n2.getParentNode();

            if (n1Parent == null && n2Parent == null) return true;
            if (n1Parent == node1 && n2Parent == node2) return true;
            assert n1Parent != null && n2Parent != null;
            n1 = n1Parent;
            n2 = n2Parent;
          } else {
            assert n2Sibling != null;
            n1 = n1Sibling;
            n2 = n2Sibling;
            break;
          }
        }
      } else {
        n1 = n1Child;
        n2 = n2Child;
      }
    }
  }
Пример #13
0
 private void replaceXmlEntry(Document doc, Node opReplace) {
   NodeList targetNodes = findNodes(doc, opReplace);
   NodeList valueNodes = getValueNodes(opReplace);
   if (targetNodes == null) {
     return;
   }
   int targetNodesCount = targetNodes.getLength();
   for (int i = 0; i < targetNodesCount; i++) {
     Node target = targetNodes.item(i);
     Node parent = target.getParentNode();
     if (parent == null) continue;
     parent.removeChild(target);
     appendNodes(doc, parent, valueNodes);
   }
 }
Пример #14
0
  public void trim() {
    try {
      XPathFactory xpathFactory = XPathFactory.newInstance();
      XPathExpression xpathExp =
          xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
      NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(node, XPathConstants.NODESET);

      // Remove each empty text node from document.
      for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Пример #15
0
  /**
   * Removes empty #text nodes from a document. From James Murty on this StackOverflow post:
   * http://stackoverflow.com/questions/978810/how-to-strip-whitespace-only-text-nodes-from-a-dom-before-serialization
   *
   * @param doc The document to remove empty text nodes from.
   */
  private static void removeEmptyTextNodes(Document doc) {
    try {
      XPathFactory xpathFactory = XPathFactory.newInstance();
      // XPath to find empty text nodes.
      XPathExpression xpathExp =
          xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
      NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

      // Remove each empty text node from document.
      for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #16
0
 /**
  * Remove a child from this node.
  *
  * @param node the child to remove
  */
 void removeChild(Node node) {
   assert this == node.getParentNode();
   if (firstChild == node) {
     firstChild = node.getNextSibling();
     if (lastChild == node) {
       lastChild = null;
     }
   } else {
     Node prev = firstChild;
     Node next = firstChild.getNextSibling();
     while (next != node) {
       prev = next;
       next = next.getNextSibling();
     }
     prev.setNextSibling(node.getNextSibling());
     if (lastChild == node) {
       lastChild = prev;
     }
   }
 }
Пример #17
0
 /**
  * Insert a new child before a pre-existing child and return the newly inserted child.
  *
  * @param child the new child
  * @param sibling the existing child before which to insert (must be a child of this node) or
  *     <code>null</code> to append
  * @return <code>child</code>
  */
 public Node insertBefore(Node child, Node sibling) {
   assert sibling == null || this == sibling.getParentNode();
   if (sibling == null) {
     return appendChild(child);
   }
   child.detach();
   child.setParentNode(this);
   if (firstChild == sibling) {
     child.setNextSibling(sibling);
     firstChild = child;
   } else {
     Node prev = firstChild;
     Node next = firstChild.getNextSibling();
     while (next != sibling) {
       prev = next;
       next = next.getNextSibling();
     }
     prev.setNextSibling(child);
     child.setNextSibling(next);
   }
   return child;
 }
  public DescribeLaunchConfigurationsResult unmarshall(Node node) throws Exception {
    if (node == null) return null;

    DescribeLaunchConfigurationsResult describeLaunchConfigurationsResult =
        new DescribeLaunchConfigurationsResult();

    NodeList launchConfigurationsNodes = XpathUtils.asNodeList("LaunchConfigurations/member", node);
    for (int launchConfigurationsIndex = 0;
        launchConfigurationsIndex < XpathUtils.nodeLength(launchConfigurationsNodes);
        ++launchConfigurationsIndex) {
      Node launchConfigurationsNode = launchConfigurationsNodes.item(launchConfigurationsIndex);
      describeLaunchConfigurationsResult
          .getLaunchConfigurations()
          .add(new LaunchConfigurationUnmarshaller().unmarshall(launchConfigurationsNode));
      launchConfigurationsNode.getParentNode().removeChild(launchConfigurationsNode);
    }

    Node nextTokenNode = XpathUtils.asNode("NextToken", node);
    describeLaunchConfigurationsResult.setNextToken(
        new StringUnmarshaller().unmarshall(nextTokenNode));

    return describeLaunchConfigurationsResult;
  }
  public RegisterInstancesWithLoadBalancerRequest unmarshall(Node node) throws Exception {
    if (node == null) return null;

    RegisterInstancesWithLoadBalancerRequest registerInstancesWithLoadBalancerRequest =
        new RegisterInstancesWithLoadBalancerRequest();

    Node loadBalancerNameNode = XpathUtils.asNode("LoadBalancerName", node);
    registerInstancesWithLoadBalancerRequest.setLoadBalancerName(
        new StringUnmarshaller().unmarshall(loadBalancerNameNode));

    NodeList instancesNodes = XpathUtils.asNodeList("Instances/member", node);
    for (int instancesIndex = 0;
        instancesIndex < XpathUtils.nodeLength(instancesNodes);
        ++instancesIndex) {
      Node instancesNode = instancesNodes.item(instancesIndex);
      registerInstancesWithLoadBalancerRequest
          .getInstances()
          .add(new InstanceUnmarshaller().unmarshall(instancesNode));
      instancesNode.getParentNode().removeChild(instancesNode);
    }

    return registerInstancesWithLoadBalancerRequest;
  }
Пример #20
0
    @Override
    public SVGDocument toSVG(ConcreteDiagram cd) {
      /*
       * Use a Plain drawer to generate an SVG Document, then
       * "post-process" any SVG circles in the document to convert them
       * into "sketches".
       */
      SVGDocument document = (new PlainCircleSVGDrawer()).toSVG(cd);
      // return document;

      // find each circle in the document and turn it into a sketch. We
      // need to keep track of the circles and their eventual replacements
      // as each circle is replaced by 10's of smaller circles, thus the
      // DOM updates and we get the 10's of circles in our NodeList circles.
      NodeList circles = document.getElementsByTagName("circle");
      List<Node> replaceable = nodeListToList(circles);
      for (Node n : replaceable) {
        Node circleAsSketch = circleToSketch(document, (SVGCircleElement) n);
        n.getParentNode().replaceChild(circleAsSketch, n);
      }

      return document;
    }
Пример #21
0
  /** updates the XMl with hashcode for the files */
  protected BudgetSubAwards updateXML(
      byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean, Budget budget)
      throws Exception {

    javax.xml.parsers.DocumentBuilderFactory domParserFactory =
        javax.xml.parsers.DocumentBuilderFactory.newInstance();
    javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents);

    org.w3c.dom.Document document = domParser.parse(byteArrayInputStream);
    byteArrayInputStream.close();
    String namespace = null;
    String formName = null;
    if (document != null) {
      Node node;
      Element element = document.getDocumentElement();
      NamedNodeMap map = element.getAttributes();
      String namespaceHolder =
          element.getNodeName().substring(0, element.getNodeName().indexOf(':'));
      node = map.getNamedItem("xmlns:" + namespaceHolder);
      namespace = node.getNodeValue();
      FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace);
      formName = formMappingInfo.getFormName();
      budgetSubAwardBean.setNamespace(namespace);
      budgetSubAwardBean.setFormName(formName);
    }

    String xpathEmptyNodes =
        "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']";
    String xpathOtherPers =
        "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]";
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    removeAllEmptyNodes(document, xpathOtherPers, 1);
    removeAllEmptyNodes(document, xpathEmptyNodes, 0);
    changeDataTypeForNumberOfOtherPersons(document);

    List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms();
    NodeList budgetYearList =
        XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']");
    for (int i = 0; i < budgetYearList.getLength(); i++) {
      Node bgtYearNode = budgetYearList.item(i);
      String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod"));
      if (fedNonFedSubAwardForms.contains(namespace)) {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName());
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      } else {
        Element newBudgetYearElement =
            copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period);
        bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode);
      }
    }

    Node oldroot = document.removeChild(document.getDocumentElement());
    Node newroot = document.appendChild(document.createElement("Forms"));
    newroot.appendChild(oldroot);

    org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName");
    org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation");
    org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType");
    org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue");

    if ((lstFileName.getLength() != lstFileLocation.getLength())
        || (lstFileLocation.getLength() != lstHashValue.getLength())) {
      //            throw new RuntimeException("Tag occurances mismatch in XML File");
    }

    org.w3c.dom.Node fileNode, hashNode, mimeTypeNode;
    org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap;
    String fileName;
    byte fileBytes[];
    String contentId;
    List attachmentList = new ArrayList();

    for (int index = 0; index < lstFileName.getLength(); index++) {
      fileNode = lstFileName.item(index);

      Node fileNameNode = fileNode.getFirstChild();
      fileName = fileNameNode.getNodeValue();

      fileBytes = (byte[]) fileMap.get(fileName);

      if (fileBytes == null) {
        throw new RuntimeException("FileName mismatch in XML and PDF extracted file");
      }
      String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes);

      hashNode = lstHashValue.item(index);
      hashNodeMap = hashNode.getAttributes();

      Node temp = document.createTextNode(hashVal);
      hashNode.appendChild(temp);

      hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm");

      hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM);

      fileNode = lstFileLocation.item(index);
      fileNodeMap = fileNode.getAttributes();
      fileNode = fileNodeMap.getNamedItem("att:href");

      contentId = fileNode.getNodeValue();
      String encodedContentId = cleanContentId(contentId);
      fileNode.setNodeValue(encodedContentId);

      mimeTypeNode = lstMimeType.item(0);
      String contentType = mimeTypeNode.getFirstChild().getNodeValue();

      BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment();
      budgetSubAwardAttachmentBean.setAttachment(fileBytes);
      budgetSubAwardAttachmentBean.setContentId(encodedContentId);

      budgetSubAwardAttachmentBean.setContentType(contentType);
      budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId());
      budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber());

      attachmentList.add(budgetSubAwardAttachmentBean);
    }

    budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList);

    javax.xml.transform.Transformer transformer =
        javax.xml.transform.TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    javax.xml.transform.stream.StreamResult result =
        new javax.xml.transform.stream.StreamResult(bos);
    javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document);

    transformer.transform(source, result);

    budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray()));

    bos.close();

    return budgetSubAwardBean;
  }
Пример #22
0
  // 主にnodamushiがEclipseから起動してなんやかんややってるときのメソッド。
  private static void testMain() throws Exception {
    String file = "testdataMain.tex";
    LamuriyanEngine e = new LamuriyanEngine(file, "testdata");
    e.setFileSearchDirectories(Paths.get("."));
    e.setInitFiles(Paths.get("testdata\\_init_test.tex"));
    e.evaluate();
    // Lamuriyanの変換完了
    RootDocument root = e.getDocument();
    // コンバート
    HTMLConverter hcon = new HTMLConverter(root, new File("testdata\\convsetting.hcv").toPath());
    hcon.convert();
    List<PageLinkObject> plos = hcon.refs();
    Document document = hcon.getDocument();

    NodeList chapters = document.getElementsByTagName("chapter");
    ArrayList<Element> chapterlist = new ArrayList<>();
    for (int i = chapters.getLength() - 1; i >= 0; i--) {
      Node node = chapters.item(i);
      node.getParentNode().removeChild(node);
      chapterlist.add(0, (Element) node);

      Element el = (Element) node;
      hcon.fixLink(el, "index_chapter" + (i + 1) + ".html");
    }

    NodeList headcontentlist = document.getElementsByTagName("headcontent");

    StringBuilder headcontent = new StringBuilder();
    for (int i = 0, end = headcontentlist.getLength(); i < end; i++) {
      Node node = headcontentlist.item(i);
      HTMLConverter.toStringChildNode(headcontent, node, "", 0, "\n");
      Attr numbera = ((Element) node).getAttributeNode("number");
    }
    StringBuilder contents = new StringBuilder();
    Node documentcontent = document.getElementById("document");

    HTMLConverter.toStringChildNode(contents, documentcontent, "", 0, "\n");

    // テンプレートファイル読み込み
    String templatefile = "testdata\\template.html";
    List<String> template = Files.readAllLines(Paths.get(templatefile), Charset.forName("utf-8"));

    String title = root.getProperty("title");
    if (title == null) {
      title = "";
    }

    ArrayList<String> lis = new ArrayList<>(template.size());

    File write = new File("testdata\\output\\index.html");
    //        System.out.println(e.current);
    PrintStream s = new PrintStream(write, "UTF-8");
    //        s.print(hcon.toHTML());
    for (String str : template) {
      if (str.equals("<!--{PAGETITLE}-->")) {
        //                lis.add(title);
        //                System.out.println(title);
        s.println(title);
      } else if (str.equals("<!--{HEADCONTENT}-->")) {
        //                lis.add(headcontent.toString());
        //                System.out.println(headcontent.toString());
        s.println(headcontent);
      } else if (str.equals("<!--{CONTENTS}-->")) {
        //                lis.add(contents.toString());
        //                System.out.println(contents);
        s.println(contents);
      } else {
        //                lis.add(str);
        s.println(str);
      }
    }
    s.close();
    for (int i = 0, end = chapterlist.size(); i < end; i++) {
      Element node = chapterlist.get(i);
      write = new File("testdata\\output\\index_chapter" + (i + 1) + ".html");
      //        System.out.println(e.current);
      s = new PrintStream(write, "UTF-8");
      contents.setLength(0);
      HTMLConverter.toStringChildNode(contents, node, "", 0, "\n");
      Attr numbera = node.getAttributeNode("number");
      Attr titla = node.getAttributeNode("title");
      //            System.out.println(contents);
      title = numbera.getValue() + "  " + titla.getValue();
      for (String str : template) {
        if (str.equals("<!--{PAGETITLE}-->")) {
          //                    lis.add(title);
          //                    System.out.println(title);
          s.println(title);
        } else if (str.equals("<!--{HEADCONTENT}-->")) {
          //                    lis.add(headcontent.toString());
          //                    System.out.println(headcontent.toString());
          s.println(headcontent);
        } else if (str.equals("<!--{CONTENTS}-->")) {
          //                    lis.add(contents.toString());
          //                    System.out.println(contents);
          s.println(contents);
        } else {
          //                    lis.add(str);
          s.println(str);
        }
      }
      s.close();
    }
  }
Пример #23
0
 private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception {
   Object object = null;
   currentType = null;
   currentNode = node;
   currentName = node.getNodeName();
   boolean isNull = false;
   NamedNodeMap attrs = node.getAttributes();
   String arrayType = null;
   for (int i = 0; i < attrs.getLength(); i++) {
     String nodeName = attrs.item(i).getNodeName();
     String nodeValue = attrs.item(i).getNodeValue();
     if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE))
       currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(
         NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE))
       arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null"))
       isNull = nodeValue.equals("true");
   }
   Class cls = null;
   if (currentType != null) cls = getXsdTypeClass(currentType);
   // Handle array, Vector, ArrayList, LinkedList, Hashtable,
   // Properties, and HashMap data types
   if ((cls != null)
       && ((cls == java.lang.reflect.Array.class)
           || (cls == Vector.class)
           || (cls == ArrayList.class)
           || (cls == LinkedList.class)
           || (cls == Hashtable.class)
           || (cls == Properties.class)
           || (cls == HashMap.class)
           || (cls == SortedMap.class))) {
     parentNode = currentNode;
     String name = node.getNodeName();
     // Handle arrays
     if (cls == java.lang.reflect.Array.class) {
       int a = arrayType.indexOf("[");
       int b = arrayType.indexOf("]");
       String s = arrayType.substring(a + 1, b);
       int arrayLen = Integer.valueOf(s).intValue();
       arrayType = arrayType.substring(0, a);
       // check if the array element is a standard Java class
       Class arrayClass = getXsdTypeClass(arrayType);
       // otherwise try to get the class of the bean
       if (arrayClass == null)
         arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType);
       object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen);
     } else {
       // Construct the list or map type
       Constructor ct = cls.getConstructor((Class[]) null);
       object = ct.newInstance((Object[]) null);
     }
     // deserialize the elements of the array, list, or map
     NodeList childNodes = node.getChildNodes();
     int arrayIndex = -1;
     Node childNode = null;
     Object nodeObj = null;
     for (int i = 0; i < childNodes.getLength(); i++) {
       childNode = childNodes.item(i);
       if (childNode.getNodeType() == Node.ELEMENT_NODE) {
         if ((cls == java.lang.reflect.Array.class)
             || (cls == Vector.class)
             || (cls == ArrayList.class)
             || (cls == LinkedList.class)) {
           nodeObj = deserialize(childNode, false, true);
           if (nodeObj != null) {
             if (cls == java.lang.reflect.Array.class)
               java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj);
             else ((List) object).add(nodeObj);
           }
         } else if ((cls == Hashtable.class)
             || (cls == Properties.class)
             || (cls == HashMap.class)
             || (cls == SortedMap.class)) {
           if (childNode.getLocalName().equals("item")) {
             NodeList htNodes = childNode.getChildNodes();
             if (htNodes.getLength() == 2) {
               Object hashKey = deserialize(htNodes.item(0), false, false);
               Object hashValue = deserialize(htNodes.item(1), false, true);
               ((Map) object).put(hashKey, hashValue);
             }
           }
         }
       }
     }
     setBeanProperty(name, object);
     // Handle everything else (primitives & POJOs)
   } else {
     // recurse on each of the child nodes
     NodeList childNodes = node.getChildNodes();
     if ((childNodes != null) && (childNodes.getLength() > 0)) {
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node childNode = childNodes.item(i);
         if (childNode.getNodeType() == Node.ELEMENT_NODE) {
           if (currentType != null)
             createObject(
                 node,
                 currentName,
                 currentPackage,
                 currentType,
                 childNode.getNodeValue(),
                 setProperty);
           parentNode = node;
           object = deserialize(childNode, true, true);
         } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) {
           object =
               createObject(
                   node,
                   currentName,
                   currentPackage,
                   currentType,
                   childNode.getNodeValue(),
                   setProperty);
         }
         currentType = null;
       }
     } else {
       if (!isNull)
         object = createObject(node, currentName, currentPackage, currentType, null, setProperty);
     }
     if (node.getParentNode() != parentNode) {
       parentNode = node.getParentNode();
       if (popBean) {
         Object bean = popBeanOffStack();
         if (bean != null) object = bean;
       }
     }
   }
   return object;
 }
Пример #24
0
  /**
   * Convenience function for UI building. Returns created widget for further configuration.
   *
   * <p>This will be replaced by a separate GUI-handling behavior, but not for a while. UI widgets
   * can be made from a hub with SemanticUI.
   *
   * @param type is one of "button", "checkbox", "radiobox", "menubutton", "separator", "entry",
   *     "label".
   * @param title can be HTML fragment.
   * @param script can be a {@link java.lang.String} or {@link multivalent.SemanticEvent}
   * @see multivalent.std.ui.SemanticUI
   */
  public Node createUI(
      String type, String title, Object script, INode parent, String category, boolean disabled) {
    // assert ... any param can be null

    type = type == null ? "button" : type.toLowerCase().intern();
    String name = parent instanceof VMenu ? "menuitem" : type;

    // System.out.println("createUI: "+type+", "+title+", "+script+", "+parent+", "+category+",
    // "+disabled);
    Node butt = null;
    // later replace by getInstance()?
    if ("checkbox" == type) butt = new VCheckbox(name, null, null);
    else if ("radiobox" == type) butt = new VRadiobox(name, null, null, null);
    else if ("menubutton" == type) butt = new VMenuButton(name, null, null);
    else if ("separator" == type) {
      butt = new VSeparator(title, null, null);
      disabled = false;
    } else if ("entry" == type) butt = new VEntry(name, null, null);
    // caller has to size WxH
    else if ("label" == type) butt = null;
    else {
      assert "button" == type;
      butt = new VButton(name, null, null);
    }

    Node content = null;
    if (title
        != null) { // && butt.isStruct()) {	// VSeparator could have name like "<SEARCH-GROUP>"
      int tags = title.indexOf('<'), tage = tags != -1 ? title.indexOf('>') : -1;
      if (tags != -1 && tage != -1 /*&& tage < title.length()-1*/)
        // interpret as XML... for now, HTML
        // MediaAdaptor htmlparser__ = (MediaAdaptor)getInstance("gui","HTML",null,
        // getDocument().getLayer(Layer.SCRATCH));
        try {
          if (Behavior.htmlparser__ == null)
            Behavior.htmlparser__ =
                (MediaAdaptor)
                    getInstance(
                        "gui",
                        "HTML",
                        null,
                        getDocument()
                            .getLayer(
                                Layer.SCRATCH)); // null no good because need Browser to make span
          // instances, and layer_ no good because just random
          // Document doc = new Document(null, null, null, getBrowser());
          Document rootdoc = new Root(null, getBrowser());
          // if (htmlroot__==null) htmlroot__ = new Root(null, getBrowser()); else
          // htmlroot__.getLayer(Layer.SCRATCH).clear();
          // Document rootdoc = htmlroot__;
          Behavior.htmlparser__.setInput(new com.pt.io.InputUniString(title, null));
          INode html = (INode) Behavior.htmlparser__.parse(rootdoc);
          // html.dump();
          Node bodyn = html.findDFS("body");
          // INode body = (INode)(html.findDFS("body"));
          // System.out.println("html = "+html+", body="+body); body.dump();
          INode body =
              bodyn instanceof INode ? (INode) bodyn : null; // could have leaf named "body"
          if (body == null) content = html.childAt(1);
          else if (body.size() == 1) content = body.childAt(0);
          else content = body;
          /*if (parent!=null) {	// kludgy: HTML attributes put in style sheet
          	StyleSheet ssp = body.getDocument().getStyleSheet(),
          			   ssn=parent.getDocument().getStyleSheet();
          	for (Iterator<> i=ssp.name2span.entrySet().iterator(); i.hasNext(); ) {
          		Map.Entry<> e = i.next();
          		if (e.getKey() instanceof Node) ssn.put(e.getKey(), (ContextListener)e.getValue());
          	}
          }*/
          // body.dump();
          // System.out.println("============");
          // content.dump();
          // new LeafUnicode(title,null, n);
        } catch (Exception badhtml) {
          System.err.println("can't parse |" + title + "| as HTML => " + badhtml);
          badhtml.printStackTrace();
        } finally {
          try {
            Behavior.htmlparser__.close();
          } catch (java.io.IOException ioe) {
          }
        }
      // htmlparser__.destroy();
      else {
        if (title.startsWith("$"))
          title = VScript.getVal(title, getBrowser().getCurDocument(), getAttributes());
        content = new LeafUnicode(title, null, null);
      }
    }

    if (content != null)
      if (butt == null) butt = content;
      else if (butt.isStruct()) {
        Node pn = butt.getFirstLeaf();
        if (pn == null) pn = butt;
        else pn = pn.getParentNode();
        INode p = (INode) pn;
        p.removeAllChildren();
        p.appendChild(content);
        // ((INode)butt).appendChild(content);
      }

    if (script != null) butt.putAttr("script", script);

    if (parent != null) parent.addCategory(butt, category);

    if (disabled)
      //		  Document doc = parent.getDocument();	// a popup menu itself may not have
      // parent-hence-doc
      // System.out.println("disabled: "+br+", doc="+doc);
      // System.out.println("layer="+doc.getLayer(Layer.SCRATCH));
      //		if (disabled) butt.addObserver(getInstance("isableTree",null,
      // doc.getLayer(Layer.SCRATCH)));
      // if (disinst_ == null) disinst_ = getInstance("disabled","DisableTree",null, null);
      // butt.addObserver(disinst_);
      butt.addObserver(getInstance("disabled", "DisableTree", null, null));

    return butt;
  }
Пример #25
0
 public static Node parent(Node node) {
   return node.getParentNode();
 }