Ejemplo n.º 1
0
  /**
   * Sign a node in a document
   *
   * @param doc
   * @param nodeToBeSigned
   * @param keyPair
   * @param publicKey
   * @param digestMethod
   * @param signatureMethod
   * @param referenceURI
   * @return
   * @throws ParserConfigurationException
   * @throws XMLSignatureException
   * @throws MarshalException
   * @throws GeneralSecurityException
   */
  public static Document sign(
      Document doc,
      Node nodeToBeSigned,
      KeyPair keyPair,
      String digestMethod,
      String signatureMethod,
      String referenceURI,
      X509Certificate x509Certificate)
      throws ParserConfigurationException, GeneralSecurityException, MarshalException,
          XMLSignatureException {
    if (nodeToBeSigned == null) throw logger.nullArgumentError("Node to be signed");

    if (logger.isTraceEnabled()) {
      logger.trace("Document to be signed=" + DocumentUtil.asString(doc));
    }

    Node parentNode = nodeToBeSigned.getParentNode();

    // Let us create a new Document
    Document newDoc = DocumentUtil.createDocument();
    // Import the node
    Node signingNode = newDoc.importNode(nodeToBeSigned, true);
    newDoc.appendChild(signingNode);

    if (!referenceURI.isEmpty()) {
      propagateIDAttributeSetup(nodeToBeSigned, newDoc.getDocumentElement());
    }
    newDoc = sign(newDoc, keyPair, digestMethod, signatureMethod, referenceURI, x509Certificate);

    // if the signed element is a SAMLv2.0 assertion we need to move the signature element to the
    // position
    // specified in the schema (before the assertion subject element).
    if (nodeToBeSigned.getLocalName().equals("Assertion")
        && WSTrustConstants.SAML2_ASSERTION_NS.equals(nodeToBeSigned.getNamespaceURI())) {
      Node signatureNode =
          DocumentUtil.getElement(newDoc, new QName(WSTrustConstants.DSIG_NS, "Signature"));
      Node subjectNode =
          DocumentUtil.getElement(
              newDoc, new QName(WSTrustConstants.SAML2_ASSERTION_NS, "Subject"));
      if (signatureNode != null && subjectNode != null) {
        newDoc.getDocumentElement().removeChild(signatureNode);
        newDoc.getDocumentElement().insertBefore(signatureNode, subjectNode);
      }
    }

    // Now let us import this signed doc into the original document we got in the method call
    Node signedNode = doc.importNode(newDoc.getFirstChild(), true);

    if (!referenceURI.isEmpty()) {
      propagateIDAttributeSetup(newDoc.getDocumentElement(), (Element) signedNode);
    }

    parentNode.replaceChild(signedNode, nodeToBeSigned);
    // doc.getDocumentElement().replaceChild(signedNode, nodeToBeSigned);

    return doc;
  }
Ejemplo n.º 2
0
  public static void clear(String fileName) throws TransformerException {

    XmlHelp.cleanHtml(fileName + ".xml");

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    System.out.println(dbf.getClass().getName());
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      System.out.println(db.getClass().getName());
      File file = new File(fileName + ".xml.temp");
      Document doc = db.parse(file);
      NodeList n1 = doc.getElementsByTagName("div");
      int len = n1.getLength();
      for (int i = 0; i < len; i++) {
        Element eltStu = (Element) n1.item(i);
        if (eltStu == null) {
          break;
        }
        String classStr = eltStu.getAttribute("class");
        if (classStr.equals("content")) {
          Node P = eltStu.getParentNode();
          //					System.out.println(P.getTextContent());
          //					System.out.println(P.getTextContent());
          NamedNodeMap attributes = eltStu.getAttributes();
          Element n = doc.createElement("div");
          for (int j = 0; j < attributes.getLength(); j++) {
            Node attribute = attributes.item(j);
            String attributeName = attribute.getNodeName();
            System.out.println("属性名:" + attributeName);
            String attributeValue = attribute.getNodeValue();
            System.out.println("属性值:" + attributeValue);
            n.setAttribute(attributeName, "content");
          }
          String content = eltStu.getTextContent();
          n.setTextContent(content);
          P.replaceChild(n, eltStu);
          //					break;
        }
      }
      // 保存修改的xml文件
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty("encoding", "GBK");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(new File(fileName + ".final"));
      transformer.transform(source, result);
      XmlHelp.cleanHtml(fileName + ".final");
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 3
0
 /**
  * Transform the DOM tree using the configuration.
  *
  * @param configuration the transformation configuration.
  * @param doc the DOM tree to be updated.
  */
 protected void applyTransformation(XmlConfiguration configuration, Document doc) {
   List<Parameter> parameters = configuration.getParameters();
   for (Parameter parameter : parameters) {
     displayMessageln("\t" + parameter.getKey() + " (mode:" + parameter.getMode() + ")");
     Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
     if (rootXpathNode != null) {
       for (Value value : parameter.getValues()) {
         switch (value.getMode()) {
           case XmlTreeHandler.MODE_INSERT:
             {
               createNewNode(doc, rootXpathNode, value);
             }
             break;
           case XmlTreeHandler.MODE_DELETE:
             {
               Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
               rootXpathNode.removeChild(deletedNode);
             }
             break;
           case XmlTreeHandler.MODE_UPDATE:
             {
               Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
               if (oldNode == null) {
                 createNewNode(doc, rootXpathNode, value);
               } else {
                 if (rootXpathNode.equals(oldNode)) {
                   rootXpathNode = rootXpathNode.getParentNode();
                 }
                 Node newNode = oldNode.cloneNode(true);
                 if (oldNode instanceof Element) {
                   ((Element) newNode).setTextContent(value.getValue());
                   rootXpathNode.replaceChild(newNode, oldNode);
                 } else {
                   ((Attr) newNode).setValue(value.getValue());
                   rootXpathNode.getAttributes().setNamedItem(newNode);
                 }
               }
               break;
             }
         }
       }
     }
   }
 }
Ejemplo n.º 4
0
  /*
   * (non-Javadoc)
   *
   * @see org.eclipse.jst.pagedesigner.actions.link.ILinkCreator#makeLinkElement(org.eclipse.gef.EditPart,
   *      org.eclipse.jst.pagedesigner.viewer.DesignRange)
   */
  public Element makeLinkElement(EditPart part, DesignRange range) {
    if (part instanceof TextEditPart) {
      Text middleNode = LinkUtil.splitDomText(part, range);
      EditPart parent = part.getParent();
      Node parentNode = (Node) parent.getModel();
      Document doc =
          (parentNode instanceof Document)
              ? (Document) parentNode
              : (parentNode.getOwnerDocument());

      Element htmlLink = doc.createElement(IHTMLConstants.TAG_A);
      htmlLink.setAttribute(ICSSPropertyID.ATTR_HREF, ""); // $NON-NLS-1$
      Text text = doc.createTextNode(middleNode.getNodeValue());
      htmlLink.appendChild(text);
      parentNode.replaceChild(htmlLink, middleNode);
      return htmlLink;
    }

    return null;
  }
Ejemplo n.º 5
0
  protected static SOAPElement replaceElementWithSOAPElement(Element element, ElementImpl copy) {

    Iterator eachAttribute = getAllAttributesFrom(element);
    while (eachAttribute.hasNext()) {
      Name name = (Name) eachAttribute.next();
      copy.addAttributeBare(name, getAttributeValueFrom(element, name));
    }

    Iterator eachChild = getChildElementsFrom(element);
    while (eachChild.hasNext()) {
      Node nextChild = (Node) eachChild.next();
      copy.insertBefore(nextChild, null);
    }

    Node parent = element.getParentNode();
    if (parent != null) {
      parent.replaceChild(copy, element);
    } // XXX else throw an exception?

    return copy;
  }
Ejemplo n.º 6
0
  /**
   * 保存挂件参数
   *
   * @param path
   * @param pageId
   * @param params
   */
  public static void save(String path, String pageId, List<Map<String, String>> params) {

    try {

      Document document = paseParamDoc(path);

      // 根据参数Map解析出新的page结点
      Node newPageNode = createPageNode(document, pageId, params);

      Node widgets = document.getFirstChild();
      NodeList nodeList = widgets.getChildNodes(); // 子元素为page结点
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node page = nodeList.item(i);
        if (page.getNodeType() == Node.ELEMENT_NODE) {
          Element pageEl = (Element) page;
          String id = pageEl.getAttribute("id");
          if (id.equals(pageId)) {
            widgets.replaceChild(newPageNode, page);
          }
        }
      }

      TransformerFactory tfactory = TransformerFactory.newInstance();
      Transformer t = tfactory.newTransformer();
      t.setOutputProperty("encoding", "UTF-8");
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.setOutputProperty(OutputKeys.METHOD, "xml");

      FileOutputStream stream = new FileOutputStream(new File(path));
      DOMSource source = new DOMSource(document);
      t.transform(source, new StreamResult(stream));

    } catch (Exception e) {
      e.printStackTrace();
      throw new RuntimeException("save [" + path + "] widget file error");
    }
  }
Ejemplo n.º 7
0
  protected static void checkAndEncryptPasswordSyntax(
      Document doc, boolean encrypt, AMEncryption encryptObj) throws SMSException {
    // Get the node list of all AttributeSchema
    NodeList nl = doc.getElementsByTagName(SMSUtils.SCHEMA_ATTRIBUTE);
    for (int i = 0; i < nl.getLength(); i++) {
      Node node = nl.item(i);
      // Check if the "syntax" attribute is "password"
      String syntax = XMLUtils.getNodeAttributeValue(node, SMSUtils.ATTRIBUTE_SYNTAX);
      if (syntax.equals(AttributeSchema.Syntax.PASSWORD.toString())) {
        if (debug.messageEnabled()) {
          debug.message("ServiceManager: encrypting password syntax");
        }
        // Get the DefaultValues and encrypt then
        Node defaultNode;
        if ((defaultNode = XMLUtils.getChildNode(node, SMSUtils.ATTRIBUTE_DEFAULT_ELEMENT))
            != null) {
          // Get NodeList of "Value" nodes and encrypt them
          for (Iterator items =
                  XMLUtils.getChildNodes(defaultNode, SMSUtils.ATTRIBUTE_VALUE).iterator();
              items.hasNext(); ) {
            Node valueNode = (Node) items.next();
            String value = XMLUtils.getValueOfValueNode(valueNode);
            String encValue;

            if (encrypt) {
              if (encryptObj != null) {
                value = (String) AccessController.doPrivileged(new DecodeAction(value, encryptObj));
                if (value.equals("&amp;#160;")) {
                  try {
                    byte[] b = new byte[1];
                    b[0] = -96;
                    value = new String(b, "ISO-8859-1");
                  } catch (UnsupportedEncodingException e) {
                    // ignore
                  }
                }
              }
              encValue = (String) AccessController.doPrivileged(new EncodeAction(value));
            } else {
              encValue = (String) AccessController.doPrivileged(new DecodeAction(value));

              try {
                // this is catch the whitespace for password
                byte[] b = encValue.getBytes("ISO-8859-1");
                if ((b.length == 1) && (b[0] == -96)) {
                  encValue = "&amp;#160;";
                }
              } catch (UnsupportedEncodingException e) {
                // ignore
              }
              if (encryptObj != null) {
                encValue =
                    (String) AccessController.doPrivileged(new EncodeAction(encValue, encryptObj));
              }
            }

            // Construct the encrypted "Value" node
            StringBuffer sb = new StringBuffer(100);
            sb.append(AttributeSchema.VALUE_BEGIN)
                .append(encValue)
                .append(AttributeSchema.VALUE_END);
            Document newDoc = SMSSchema.getXMLDocument(sb.toString(), false);
            Node newValueNode = XMLUtils.getRootNode(newDoc, SMSUtils.ATTRIBUTE_VALUE);
            // Replace the node
            Node nValueNode = doc.importNode(newValueNode, true);
            defaultNode.replaceChild(nValueNode, valueNode);
          }
        }
      }
    }
  }
Ejemplo n.º 8
0
  public static Object setProperty(Node node, Collection.Key k, Object value, boolean caseSensitive)
      throws PageException {
    Document doc = (node instanceof Document) ? (Document) node : node.getOwnerDocument();

    // Comment
    if (k.equals(XMLCOMMENT)) {
      removeChilds(XMLCaster.toRawNode(node), Node.COMMENT_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc, value)));
    }
    // NS URI
    else if (k.equals(XMLNSURI)) {
      // TODO impl
      throw new ExpressionException("XML NS URI can't be set", "not implemented");
    }
    // Prefix
    else if (k.equals(XMLNSPREFIX)) {
      // TODO impl
      throw new ExpressionException("XML NS Prefix can't be set", "not implemented");
      // node.setPrefix(Caster.toString(value));
    }
    // Root
    else if (k.equals(XMLROOT)) {
      doc.appendChild(XMLCaster.toNode(doc, value));
    }
    // Parent
    else if (k.equals(XMLPARENT)) {
      Node parent = getParentNode(node, caseSensitive);
      Key name = KeyImpl.init(parent.getNodeName());
      parent = getParentNode(parent, caseSensitive);

      if (parent == null)
        throw new ExpressionException(
            "there is no parent element, you are already on the root element");

      return setProperty(parent, name, value, caseSensitive);
    }
    // Name
    else if (k.equals(XMLNAME)) {
      throw new XMLException("You can't assign a new value for the property [xmlname]");
    }
    // Type
    else if (k.equals(XMLTYPE)) {
      throw new XMLException("You can't change type of a xml node [xmltype]");
    }
    // value
    else if (k.equals(XMLVALUE)) {
      node.setNodeValue(Caster.toString(value));
    }
    // Attributes
    else if (k.equals(XMLATTRIBUTES)) {
      Element parent = XMLCaster.toElement(doc, node);
      Attr[] attres = XMLCaster.toAttrArray(doc, value);
      // print.ln("=>"+value);
      for (int i = 0; i < attres.length; i++) {
        if (attres[i] != null) {
          parent.setAttributeNode(attres[i]);
          // print.ln(attres[i].getName()+"=="+attres[i].getValue());
        }
      }
    }
    // Text
    else if (k.equals(XMLTEXT)) {
      removeChilds(XMLCaster.toRawNode(node), Node.TEXT_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc, value)));
    }
    // CData
    else if (k.equals(XMLCDATA)) {
      removeChilds(XMLCaster.toRawNode(node), Node.CDATA_SECTION_NODE, false);
      node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc, value)));
    }
    // Children
    else if (k.equals(XMLCHILDREN)) {
      Node[] nodes = XMLCaster.toNodeArray(doc, value);
      removeChilds(XMLCaster.toRawNode(node), Node.ELEMENT_NODE, false);
      for (int i = 0; i < nodes.length; i++) {
        if (nodes[i] == node) throw new XMLException("can't assign a XML Node to himself");
        if (nodes[i] != null) node.appendChild(XMLCaster.toRawNode(nodes[i]));
      }
    } else {
      Node child = XMLCaster.toNode(doc, value);
      if (!k.getString().equalsIgnoreCase(child.getNodeName())) {
        throw new XMLException(
            "if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name",
            "Property Name is "
                + k.getString()
                + " and XML Element Name is "
                + child.getNodeName());
      }
      NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
      int len = list.getLength();
      Node n;
      for (int i = 0; i < len; i++) {
        n = list.item(i);
        if (nameEqual(n, k.getString(), caseSensitive)) {
          node.replaceChild(XMLCaster.toRawNode(child), XMLCaster.toRawNode(n));
          return value;
        }
      }
      node.appendChild(XMLCaster.toRawNode(child));
    }

    return value;
  }