Пример #1
0
  @Test
  public void testElementGetAPIs() throws Exception {
    //		builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    String xml =
        "<?xml version=\"1.0\"?>"
            + "<t:root xmlns=\"http://void.com/\" xmlns:t=\"http://t.com/\" id=\"stella\" t:type=\"police\">"
            + "<t:item id=\"a\"/>"
            + "<child id=\"1\"/>"
            + "<t:item id=\"b\"/>"
            + "<child id=\"2\"/>"
            + "</t:root>";

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.getBytes()));
    Element root = doc.getDocumentElement();
    Assert.assertEquals("tagName", "t:root", root.getTagName());
    Assert.assertEquals("attribute", "stella", root.getAttribute("id"));
    Assert.assertEquals("attributeNS", "police", root.getAttributeNS("http://t.com/", "type"));
    Assert.assertEquals("attribute(has)", true, root.hasAttribute("id"));
    Assert.assertEquals("attribute(has)", false, root.hasAttribute("__id__"));
    Assert.assertEquals("attributeNS(has)", true, root.hasAttributeNS("http://t.com/", "type"));
    Assert.assertEquals("attributeNS(has)", false, root.hasAttributeNS("http://t.com/", "tipe"));
  }
Пример #2
0
  /** Removes all the unused attributes after a conversion */
  private void removeUndefinedAttrs(MultiTextEdit rootEdit, Element element) {
    ViewElementDescriptor descriptor = getElementDescriptor(mTypeFqcn);
    if (descriptor == null) {
      return;
    }

    Set<String> defined = new HashSet<String>();
    AttributeDescriptor[] layoutAttributes = descriptor.getAttributes();
    for (AttributeDescriptor attribute : layoutAttributes) {
      defined.add(attribute.getXmlLocalName());
    }

    List<Attr> attributes = findAttributes(element);
    for (Attr attribute : attributes) {
      String name = attribute.getLocalName();
      if (!defined.contains(name)) {
        // Remove it
        removeAttribute(rootEdit, element, attribute.getNamespaceURI(), name);
      }
    }

    // Set text attribute if it's defined
    if (defined.contains(ATTR_TEXT) && !element.hasAttributeNS(ANDROID_URI, ATTR_TEXT)) {
      setAttribute(
          rootEdit,
          element,
          ANDROID_URI,
          getAndroidNamespacePrefix(),
          ATTR_TEXT,
          descriptor.getUiName());
    }
  }
Пример #3
0
  private int getApiVersion(Element usesSdk, String attribute, int defaultApiLevel) {
    String valueString = null;
    if (usesSdk.hasAttributeNS(NS_RESOURCES, attribute)) {
      valueString = usesSdk.getAttributeNS(NS_RESOURCES, attribute);
    }

    if (valueString != null) {
      int apiLevel = -1;
      try {
        apiLevel = Integer.valueOf(valueString);
      } catch (NumberFormatException e) {
        // Handle codename
        if (Sdk.getCurrent() != null) {
          IAndroidTarget target =
              Sdk.getCurrent().getTargetFromHashString("android-" + valueString); // $NON-NLS-1$
          if (target != null) {
            // codename future API level is current api + 1
            apiLevel = target.getVersion().getApiLevel() + 1;
          }
        }

        if (usesSdk.getTagName().equals(ATTRIBUTE_MIN_SDK_VERSION)) {
          mMinSdkName = valueString;
        }
      }

      return apiLevel;
    }

    return defaultApiLevel;
  }
Пример #4
0
  private static String generatePrefix(Element contextElem, String baseText) {
    // check possible collision with namespace declarations
    if (!contextElem.hasAttributeNS(BpelConstants.NS_XMLNS, baseText)) return baseText;

    // collision detected, append natural numbers
    StringBuffer prefixBuffer = new StringBuffer(baseText);
    int baseLength = baseText.length();
    for (int i = 1; i < Integer.MAX_VALUE; i++) {
      // append natural number to base text
      String prefix = prefixBuffer.append(i).toString();
      // check possible collision with namespace declarations
      if (!contextElem.hasAttributeNS(BpelConstants.NS_XMLNS, prefix)) return prefix;
      // remove appended number
      prefixBuffer.setLength(baseLength);
    }
    throw new RuntimeException("could not generate prefix");
  }
  /** {@inheritDoc} */
  protected void doParse(Element config, BeanDefinitionBuilder builder) {
    log.info("Parsing configuration for JSP error handler.");
    super.doParse(config, builder);

    if (config.hasAttributeNS(null, "jspPagePath")) {
      builder.addConstructorArgValue(config.getAttributeNS(null, "jspPagePath"));
    } else {
      builder.addConstructorArgValue(config.getAttributeNS(null, "/error.jsp"));
    }
  }
  /**
   * Float the xml:* attributes of the unselected parent nodes to the ciurrent node.
   *
   * @param E
   * @param result
   */
  private void addXmlAttributes(Element E, SortedSet result) {
    /* The processing of an element node E MUST be modified slightly when an
     * XPath node-set is given as input and the element's parent is omitted
     * from the node-set. The method for processing the attribute axis of an
     * element E in the node-set is enhanced. All element nodes along E's
     * ancestor axis are examined for nearest occurrences of attributes in
     * the xml namespace, such as xml:lang and xml:space (whether or not they
     * are in the node-set). From this list of attributes, remove any that are
     * in E's attribute axis (whether or not they are in the node-set). Then,
     * lexicographically merge this attribute list with the nodes of E's
     * attribute axis that are in the node-set. The result of visiting the
     * attribute axis is computed by processing the attribute nodes in this
     * merged attribute list.
     */

    // E is in the node-set
    Node parent = E.getParentNode();
    Map loa = new HashMap();

    if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE) && !isVisible(parent)) {

      // parent element is not in node set
      for (Node ancestor = parent;
          (ancestor != null) && (ancestor.getNodeType() == Node.ELEMENT_NODE);
          ancestor = ancestor.getParentNode()) {
        Element el = ((Element) ancestor);
        if (!el.hasAttributes()) {
          continue;
        }
        // for all ancestor elements
        NamedNodeMap ancestorAttrs = el.getAttributes();

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

          // for all attributes in the ancestor element
          Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);

          if (XML_LANG_URI.equals(currentAncestorAttr.getNamespaceURI())) {

            // do we have an xml:* ?
            if (!E.hasAttributeNS(XML_LANG_URI, currentAncestorAttr.getLocalName())) {

              // the xml:* attr is not in E
              if (!loa.containsKey(currentAncestorAttr.getName())) {
                loa.put(currentAncestorAttr.getName(), currentAncestorAttr);
              }
            }
          }
        }
      }
    }
    result.addAll(loa.values());
  }
Пример #7
0
  /**
   * This is the work horse for {@link #circumventBug2650}.
   *
   * @param node
   * @see <A HREF="http://nagoya.apache.org/bugzilla/show_bug.cgi?id=2650">Namespace axis resolution
   *     is not XPath compliant </A>
   */
  private static void circumventBug2650internal(Node node) {
    Node parent = null;
    Node sibling = null;
    final String namespaceNs = Constants.NamespaceSpecNS;
    do {
      switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
          Element element = (Element) node;
          if (!element.hasChildNodes()) break;
          if (element.hasAttributes()) {
            NamedNodeMap attributes = element.getAttributes();
            int attributesLength = attributes.getLength();

            for (Node child = element.getFirstChild();
                child != null;
                child = child.getNextSibling()) {

              if (child.getNodeType() != Node.ELEMENT_NODE) {
                continue;
              }
              Element childElement = (Element) child;

              for (int i = 0; i < attributesLength; i++) {
                Attr currentAttr = (Attr) attributes.item(i);
                if (namespaceNs != currentAttr.getNamespaceURI()) continue;
                if (childElement.hasAttributeNS(namespaceNs, currentAttr.getLocalName())) {
                  continue;
                }
                childElement.setAttributeNS(
                    namespaceNs, currentAttr.getName(), currentAttr.getNodeValue());
              }
            }
          }
        case Node.ENTITY_REFERENCE_NODE:
        case Node.DOCUMENT_NODE:
          parent = node;
          sibling = node.getFirstChild();
          break;
      }
      while ((sibling == null) && (parent != null)) {
        sibling = parent.getNextSibling();
        parent = parent.getParentNode();
      }
      ;
      if (sibling == null) {
        return;
      }

      node = sibling;
      sibling = node.getNextSibling();
    } while (true);
  }
  private void addLayoutReplacements(
      @NonNull List<TextEdit> edits,
      @NonNull Element element,
      @NonNull IStructuredDocument document) {
    String tag = element.getTagName();
    if (tag.equals(mOldFqcn)) {
      int start = RefactoringUtil.getTagNameRangeStart(element, document);
      if (start != -1) {
        int end = start + mOldFqcn.length();
        edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
      }
    } else if (tag.equals(VIEW_TAG)) {
      Attr classNode = element.getAttributeNode(ATTR_CLASS);
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    } else if (tag.equals(VIEW_FRAGMENT)) {
      Attr classNode = element.getAttributeNode(ATTR_CLASS);
      if (classNode == null) {
        classNode = element.getAttributeNodeNS(ANDROID_URI, ATTR_NAME);
      }
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    } else if (element.hasAttributeNS(TOOLS_URI, ATTR_CONTEXT)) {
      Attr classNode = element.getAttributeNodeNS(TOOLS_URI, ATTR_CONTEXT);
      if (classNode != null && classNode.getValue().equals(mOldFqcn)) {
        int start = RefactoringUtil.getAttributeValueRangeStart(classNode, document);
        if (start != -1) {
          int end = start + mOldFqcn.length();
          edits.add(new ReplaceEdit(start, end - start, mNewFqcn));
        }
      }
    }

    NodeList children = element.getChildNodes();
    for (int i = 0, n = children.getLength(); i < n; i++) {
      Node child = children.item(i);
      if (child.getNodeType() == Node.ELEMENT_NODE) {
        addLayoutReplacements(edits, (Element) child, document);
      }
    }
  }
 /**
  * Runs the test case.
  *
  * @throws Throwable Any uncaught exception causes test to fail
  */
 public void runTest() throws Throwable {
   Document doc;
   Element element;
   boolean state;
   Attr attribute;
   Attr newAttribute;
   doc = (Document) load("staff", false);
   element = doc.createElementNS("http://www.w3.org/DOM", "elem");
   attribute = doc.createAttributeNS("http://www.w3.org/DOM/Test/createAttributeNS", "attr");
   newAttribute = element.setAttributeNodeNS(attribute);
   element.removeAttributeNS("http://www.w3.org/DOM/Test/createAttributeNS", "attr");
   state = element.hasAttributeNS("http://www.w3.org/DOM/Test/createAttributeNS", "attr");
   assertFalse("elementremoveattributens01", state);
 }
Пример #10
0
  private static void getElementsWithAttribute(
      Element element, String namespaceURI, String localName, String value, Collection elements) {
    if (element.hasAttributeNS(namespaceURI, localName)) {
      String attr = element.getAttributeNS(namespaceURI, localName);
      if (attr.equals(value)) elements.add(element);
    }

    NodeList childs = element.getChildNodes();

    for (int i = 0; i < childs.getLength(); i++) {
      Node node = childs.item(i);
      if (Node.ELEMENT_NODE == node.getNodeType())
        getElementsWithAttribute((Element) node, namespaceURI, localName, value, elements);
    }
  }
Пример #11
0
  /**
   * Returns the value of an attribute for an element.
   *
   * @param element the element to check
   * @param definition the definition of the attribute to retrieve from the element
   * @return the defined attribute value, or <tt>null</tt> if the attribute was not found on the
   *     element
   */
  public static String getAttribute(Element element, XmlNode definition) {
    if (element == null) {
      return null;
    }

    if (definition.isNamespaceAware()) {
      if (element.hasAttributeNS(definition.getNamespace(), definition.getLocalName())) {
        return element.getAttributeNS(definition.getNamespace(), definition.getLocalName());
      }
    } else {
      if (element.hasAttribute(definition.getLocalName())) {
        return element.getAttribute(definition.getLocalName());
      }
    }
    return null;
  }
  /**
   * Float the xml:* attributes of the parent nodes to the root node of c14n
   *
   * @param E the root node.
   * @param result the xml:* attributes to output.
   */
  private void addXmlAttributesSubtree(Element E, SortedSet result) {
    // E is in the node-set
    Node parent = E.getParentNode();
    Map loa = new HashMap();

    if ((parent != null) && (parent.getNodeType() == Node.ELEMENT_NODE)) {

      // parent element is not in node set
      for (Node ancestor = parent;
          (ancestor != null) && (ancestor.getNodeType() == Node.ELEMENT_NODE);
          ancestor = ancestor.getParentNode()) {
        Element el = ((Element) ancestor);
        if (!el.hasAttributes()) {
          continue;
        }
        // for all ancestor elements
        NamedNodeMap ancestorAttrs = el.getAttributes();

        for (int i = 0; i < ancestorAttrs.getLength(); i++) {
          // for all attributes in the ancestor element
          Attr currentAncestorAttr = (Attr) ancestorAttrs.item(i);

          if (XML_LANG_URI.equals(currentAncestorAttr.getNamespaceURI())) {

            // do we have an xml:* ?
            if (!E.hasAttributeNS(XML_LANG_URI, currentAncestorAttr.getLocalName())) {

              // the xml:* attr is not in E
              if (!loa.containsKey(currentAncestorAttr.getName())) {
                loa.put(currentAncestorAttr.getName(), currentAncestorAttr);
              }
            }
          }
        }
      }
    }

    result.addAll(loa.values());
  }
 private void changerTexte(final String s) {
   final AffichageFormulaire affP = premierAffichage.chercherAffichage(parent);
   if (noeud instanceof Element) {
     final AffichageFormulaire aff = affP.chercherAffichage(noeud);
     Node noeudTexte = noeud.getFirstChild();
     if (aff == null && !"".equals(s)) recreerElement();
     else if (noeudTexte != null) noeudTexte.setNodeValue(s);
     else {
       noeudTexte = noeud.getOwnerDocument().createTextNode(s);
       noeud.appendChild(noeudTexte);
     }
     affP.majPanel(null);
   } else { // attribut
     final Element elparent = (Element) parent;
     if (!elparent.hasAttributeNS(noeud.getNamespaceURI(), noeud.getLocalName()))
       elparent.setAttributeNodeNS((Attr) noeud);
     noeud.setNodeValue(s);
     affP.majPanel(null);
   }
   final AffichageFormulaire affAj = affP.chercherAffichage(noeud);
   if (affAj != null && affAj.comp != null) affAj.comp.requestFocusInWindow();
 }
 /**
  * INTERNAL: When using the DOM Platform during unmarshal operations. Use the element to determine
  * if the element represents a null value. @ param element
  *
  * @return true if based on the element it represents a null value, else false.
  */
 public boolean valueIsNull(Element element) {
   // Check Nillable: Ignore any other attributes that are in addition to xsi:nil
   if (null == element) {
     return true;
   } else {
     if (isNullRepresentedByXsiNil()
         && element.hasAttributeNS(
             javax.xml.XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI,
             Constants.SCHEMA_NIL_ATTRIBUTE)) {
       return true;
     } else {
       // EMPTY_NODE - Required
       // Verify no attributes and no child nodes on the DOM element
       if (isNullRepresentedByEmptyNode()
           && !element.hasAttributes()
           && (element.getChildNodes().getLength() == 0)) {
         return true;
       } else {
         return false;
       }
     }
   }
 }
Пример #15
0
  private static String getAttributeValueFrom(
      Element element, String uri, String localName, String prefix, String qualifiedName) {

    String nonzeroLengthUri = (uri == null || uri.length() == 0) ? null : uri;

    boolean mustUseGetAttributeNodeNS = (nonzeroLengthUri != null);

    if (mustUseGetAttributeNodeNS) {

      if (!element.hasAttributeNS(uri, localName)) {
        return null;
      }

      String attrValue = element.getAttributeNS(nonzeroLengthUri, localName);

      return attrValue;
    }

    Attr attribute = null;
    attribute = element.getAttributeNode(qualifiedName);

    return attribute == null ? null : attribute.getValue();
  }
Пример #16
0
 public static Map<String, String> getTitleInfo(String pid, FedoraAccess fedoraAccess)
     throws XPathExpressionException, IOException {
   Map<String, String> map = new HashMap<String, String>();
   Document biblioMods = fedoraAccess.getBiblioMods(pid);
   XPath xpath = FACTORY.newXPath();
   xpath.setNamespaceContext(new FedoraNamespaceContext());
   XPathExpression expr = xpath.compile("//mods:titleInfo/mods:title");
   NodeList set = (NodeList) expr.evaluate(biblioMods, XPathConstants.NODESET);
   for (int i = 0, ll = set.getLength(); i < ll; i++) {
     Node node = set.item(i);
     if (node.getNodeType() == Node.ELEMENT_NODE) {
       Element elm = (Element) node;
       if (elm.hasAttributeNS(FedoraNamespaces.BIBILO_MODS_URI, "type")) {
         String type = elm.getAttributeNS(FedoraNamespaces.BIBILO_MODS_URI, "type");
         map.put(type, elm.getTextContent().trim());
       } else {
         if (!map.containsKey("default")) {
           map.put("default", elm.getTextContent().trim());
         }
       }
     }
   }
   return map;
 }
Пример #17
0
  /**
   * Determines the target node of the "bindings" element by using the inherited target node, then
   * put the result into the "result" map.
   */
  private void buildTargetNodeMap(
      Element bindings, Node inheritedTarget, Map<Element, Node> result) {
    // start by the inherited target
    Node target = inheritedTarget;

    validate(bindings); // validate this node

    // look for @wsdlLocation
    if (isTopLevelBinding(bindings)) {
      String wsdlLocation;
      if (bindings.getAttributeNode("wsdlLocation") != null) {
        wsdlLocation = bindings.getAttribute("wsdlLocation");

        try {
          // absolutize this URI.
          // TODO: use the URI class
          // TODO: honor xml:base
          wsdlLocation =
              new URL(new URL(forest.getSystemId(bindings.getOwnerDocument())), wsdlLocation)
                  .toExternalForm();
        } catch (MalformedURLException e) {
          wsdlLocation = JAXWSUtils.absolutize(JAXWSUtils.getFileOrURLName(wsdlLocation));
        }
      } else {
        // the node does not have
        wsdlLocation = forest.getFirstRootDocument();
      }
      target = forest.get(wsdlLocation);

      if (target == null) {
        reportError(
            bindings,
            WsdlMessages.INTERNALIZER_INCORRECT_SCHEMA_REFERENCE(
                wsdlLocation, EditDistance.findNearest(wsdlLocation, forest.listSystemIDs())));
        return; // abort processing this <JAXWS:bindings>
      }
    }

    // if the target node is xs:schema, declare the jaxb version on it as latter on it will be
    // required by the inlined schema bindings

    Element element = DOMUtil.getFirstElementChild(target);
    if (element != null
        && element.getNamespaceURI().equals(Constants.NS_WSDL)
        && element.getLocalName().equals("definitions")) {
      // get all schema elements
      Element type = DOMUtils.getFirstChildElement(element, Constants.NS_WSDL, "types");
      if (type != null) {
        for (Element schemaElement : DOMUtils.getChildElements(type, Constants.NS_XSD, "schema")) {
          if (!schemaElement.hasAttributeNS(Constants.NS_XMLNS, "jaxb")) {
            schemaElement.setAttributeNS(
                Constants.NS_XMLNS, "xmlns:jaxb", JAXWSBindingsConstants.NS_JAXB_BINDINGS);
          }

          // add jaxb:bindings version info. Lets put it to 1.0, may need to change latter
          if (!schemaElement.hasAttributeNS(JAXWSBindingsConstants.NS_JAXB_BINDINGS, "version")) {
            schemaElement.setAttributeNS(
                JAXWSBindingsConstants.NS_JAXB_BINDINGS,
                "jaxb:version",
                JAXWSBindingsConstants.JAXB_BINDING_VERSION);
          }
        }
      }
    }

    boolean hasNode = true;
    if ((isJAXWSBindings(bindings) || isJAXBBindings(bindings))
        && bindings.getAttributeNode("node") != null) {
      target =
          evaluateXPathNode(
              bindings, target, bindings.getAttribute("node"), new NamespaceContextImpl(bindings));
    } else if (isJAXWSBindings(bindings)
        && (bindings.getAttributeNode("node") == null)
        && !isTopLevelBinding(bindings)) {
      hasNode = false;
    } else if (isGlobalBinding(bindings)
        && !isWSDLDefinition(target)
        && isTopLevelBinding(bindings.getParentNode())) {
      target = getWSDLDefintionNode(bindings, target);
    }

    // if target is null it means the xpath evaluation has some problem,
    // just return
    if (target == null) return;

    // update the result map
    if (hasNode) result.put(bindings, target);

    // look for child <JAXWS:bindings> and process them recursively
    Element[] children = getChildElements(bindings);
    for (Element child : children) buildTargetNodeMap(child, target, result);
  }
 private boolean hasAttr(@NonNull String key) {
   return mNode.hasAttributeNS(ANDROID_URI, key);
 }
Пример #19
0
  // CHECKSTYLE:OFF
  @org.junit.Test
  public void testSAMLinWSSecToOtherRealm() throws Exception {
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = IssueUnitTest.class.getResource("cxf-client.xml");

    Bus bus = bf.createBus(busFile.toString());
    SpringBusFactory.setDefaultBus(bus);
    SpringBusFactory.setThreadDefaultBus(bus);

    Crypto crypto = CryptoFactory.getInstance(getEncryptionProperties());
    CallbackHandler callbackHandler = new CommonCallbackHandler();

    // Create SAML token
    Element samlToken =
        createSAMLAssertion(
            WSConstants.WSS_SAML2_TOKEN_TYPE,
            crypto,
            "mystskey",
            callbackHandler,
            null,
            "alice",
            "a-issuer");

    String id = null;
    QName elName = DOMUtils.getElementQName(samlToken);
    if (elName.equals(new QName(WSConstants.SAML_NS, "Assertion"))
        && samlToken.hasAttributeNS(null, "AssertionID")) {
      id = samlToken.getAttributeNS(null, "AssertionID");
    } else if (elName.equals(new QName(WSConstants.SAML2_NS, "Assertion"))
        && samlToken.hasAttributeNS(null, "ID")) {
      id = samlToken.getAttributeNS(null, "ID");
    }
    if (id == null) {
      id = samlToken.getAttributeNS(WSConstants.WSU_NS, "Id");
    }

    SecurityToken wstoken = new SecurityToken(id, samlToken, null, null);
    Map<String, Object> properties = new HashMap<String, Object>();
    properties.put(SecurityConstants.TOKEN, wstoken);
    properties.put(SecurityConstants.TOKEN_ID, wstoken.getId());

    // Get a token

    SecurityToken token =
        requestSecurityToken(
            SAML2_TOKEN_TYPE,
            BEARER_KEYTYPE,
            null,
            bus,
            DEFAULT_ADDRESS,
            null,
            properties,
            "b-issuer",
            "Transport_SAML_Port");

    /*
    SecurityToken token =
            requestSecurityToken(SAML2_TOKEN_TYPE, BEARER_KEYTYPE, null,
                    bus, DEFAULT_ADDRESS, null, properties, "b-issuer", null);
                    */
    assertTrue(SAML2_TOKEN_TYPE.equals(token.getTokenType()));
    assertTrue(token.getToken() != null);

    List<WSSecurityEngineResult> results = processToken(token);
    assertTrue(results != null && results.size() == 1);
    SamlAssertionWrapper assertion =
        (SamlAssertionWrapper) results.get(0).get(WSSecurityEngineResult.TAG_SAML_ASSERTION);
    assertTrue(assertion != null);
    assertTrue(assertion.isSigned());

    List<String> methods = assertion.getConfirmationMethods();
    String confirmMethod = null;
    if (methods != null && methods.size() > 0) {
      confirmMethod = methods.get(0);
    }
    assertTrue(confirmMethod.contains("bearer"));

    assertTrue("b-issuer".equals(assertion.getIssuerString()));
    String subjectName = assertion.getSaml2().getSubject().getNameID().getValue();
    assertTrue("Subject must be ALICE instead of " + subjectName, "ALICE".equals(subjectName));
  }
  // Checkstyle: CyclomaticComplexity OFF
  @Override
  protected void doNativeParse(
      Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {
    super.doNativeParse(element, parserContext, builder);

    if (element.hasAttributeNS(null, "cacheDuration")) {
      log.error(
          "{}: cacheDuration is not supported",
          parserContext.getReaderContext().getResource().getDescription());
      throw new BeanDefinitionParsingException(
          new Problem(
              "cacheDuration is not supported",
              new Location(parserContext.getReaderContext().getResource())));
    }

    if (element.hasAttributeNS(null, "maintainExpiredMetadata")) {
      log.error(
          "{}: maintainExpiredMetadata is not supported",
          parserContext.getReaderContext().getResource().getDescription());
      throw new BeanDefinitionParsingException(
          new Problem(
              "maintainExpiredMetadata is not supported",
              new Location(parserContext.getReaderContext().getResource())));
    }

    boolean haveTLSTrustEngine = false;
    if (element.hasAttributeNS(null, "tlsTrustEngineRef")) {
      builder.addPropertyReference(
          "tLSTrustEngine",
          StringSupport.trimOrNull(element.getAttributeNS(null, "tlsTrustEngineRef")));
      haveTLSTrustEngine = true;
    } else {
      BeanDefinition tlsTrustEngine = parseTLSTrustEngine(element, parserContext);
      if (tlsTrustEngine != null) {
        builder.addPropertyValue("tLSTrustEngine", tlsTrustEngine);
        haveTLSTrustEngine = true;
      }
    }

    if (element.hasAttributeNS(null, "httpClientRef")) {
      builder.addConstructorArgReference(
          StringSupport.trimOrNull(element.getAttributeNS(null, "httpClientRef")));
      if (element.hasAttributeNS(null, "requestTimeout")
          || element.hasAttributeNS(null, "disregardSslCertificate")
          || element.hasAttributeNS(null, "disregardTLSCertificate")
          || element.hasAttributeNS(null, "proxyHost")
          || element.hasAttributeNS(null, "proxyPort")
          || element.hasAttributeNS(null, "proxyUser")
          || element.hasAttributeNS(null, "proxyPassword")) {
        log.warn(
            "httpClientRef overrides settings for requestTimeout, disregardSslCertificate, "
                + "disregardTLSCertificate, proxyHost, proxyPort, proxyUser and proxyPassword");
      }
    } else {
      builder.addConstructorArgValue(buildHttpClient(element, parserContext, haveTLSTrustEngine));
    }
    builder.addConstructorArgValue(
        StringSupport.trimOrNull(element.getAttributeNS(null, METADATA_URL)));

    if (element.hasAttributeNS(null, BASIC_AUTH_USER)
        || element.hasAttributeNS(null, BASIC_AUTH_PASSWORD)) {
      builder.addPropertyValue("basicCredentials", buildBasicCredentials(element));
    }
  }
  // Checkstyle: CyclomaticComplexity OFF
  // Checkstyle: MethodLength OFF
  private BeanDefinition buildHttpClient(
      Element element, ParserContext parserContext, boolean haveTLSTrustEngine) {
    String caching = DEFAULT_CACHING;
    if (element.hasAttributeNS(null, "httpCaching")) {
      caching = StringSupport.trimOrNull(element.getAttributeNS(null, "httpCaching"));
    }

    BeanDefinitionBuilder clientBuilder = null;
    switch (caching) {
      case "none":
        clientBuilder = BeanDefinitionBuilder.genericBeanDefinition(HttpClientFactoryBean.class);
        break;
      case "file":
        clientBuilder =
            BeanDefinitionBuilder.genericBeanDefinition(FileCachingHttpClientFactoryBean.class);
        if (element.hasAttributeNS(null, "httpCacheDirectory")) {
          clientBuilder.addPropertyValue(
              "cacheDirectory",
              StringSupport.trimOrNull(element.getAttributeNS(null, "httpCacheDirectory")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
          clientBuilder.addPropertyValue(
              "maxCacheEntries",
              StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntries")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
          clientBuilder.addPropertyValue(
              "maxCacheEntrySize",
              StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntrySize")));
        }
        break;
      case "memory":
        clientBuilder =
            BeanDefinitionBuilder.genericBeanDefinition(InMemoryCachingHttpClientFactoryBean.class);
        if (element.hasAttributeNS(null, "httpMaxCacheEntries")) {
          clientBuilder.addPropertyValue(
              "maxCacheEntries",
              StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntries")));
        }
        if (element.hasAttributeNS(null, "httpMaxCacheEntrySize")) {
          clientBuilder.addPropertyValue(
              "maxCacheEntrySize",
              StringSupport.trimOrNull(element.getAttributeNS(null, "httpMaxCacheEntrySize")));
        }
        break;
      default:
        throw new BeanDefinitionParsingException(
            new Problem(
                String.format("Caching value '%s' is unsupported", caching),
                new Location(parserContext.getReaderContext().getResource())));
    }

    clientBuilder.setLazyInit(true);

    if (element.hasAttributeNS(null, "requestTimeout")) {
      clientBuilder.addPropertyValue(
          "connectionTimeout",
          StringSupport.trimOrNull(element.getAttributeNS(null, "requestTimeout")));
    }

    if (haveTLSTrustEngine) {
      clientBuilder.addPropertyValue(
          "tLSSocketFactory",
          new SecurityEnhancedTLSSocketFactory(
              HttpClientSupport.buildNoTrustTLSSocketFactory(), new StrictHostnameVerifier()));
    }

    if (element.hasAttributeNS(null, "disregardTLSCertificate")) {
      clientBuilder.addPropertyValue(
          "connectionDisregardTLSCertificate",
          StringSupport.trimOrNull(element.getAttributeNS(null, "disregardTLSCertificate")));
    } else if (element.hasAttributeNS(null, "disregardSslCertificate")) {
      log.warn("disregardSslCertificate is deprecated, please switch to disregardTLSCertificate");
      clientBuilder.addPropertyValue(
          "connectionDisregardTLSCertificate",
          StringSupport.trimOrNull(element.getAttributeNS(null, "disregardSslCertificate")));
    }

    if (element.hasAttributeNS(null, "proxyHost")) {
      clientBuilder.addPropertyValue(
          "connectionProxyHost",
          StringSupport.trimOrNull(element.getAttributeNS(null, "proxyHost")));
    }

    if (element.hasAttributeNS(null, "proxyPort")) {
      clientBuilder.addPropertyValue(
          "connectionProxyPort",
          StringSupport.trimOrNull(element.getAttributeNS(null, "proxyPort")));
    }

    if (element.hasAttributeNS(null, "proxyUser")) {
      clientBuilder.addPropertyValue(
          "connectionProxyUsername",
          StringSupport.trimOrNull(element.getAttributeNS(null, "proxyUser")));
    }

    if (element.hasAttributeNS(null, "proxyPassword")) {
      clientBuilder.addPropertyValue(
          "connectionProxyPassword", element.getAttributeNS(null, "proxyPassword"));
    }

    return clientBuilder.getBeanDefinition();
  }
Пример #22
0
  /**
   * Ensure that the package, theme and activity maps are initialized and up to date with respect to
   * the manifest file
   */
  private void sync() {
    // Since each of the accessors call sync(), allow a bunch of immediate
    // accessors to all bypass the file stat() below
    long now = System.currentTimeMillis();
    if (now - mLastChecked < 50 && mManifestFile != null) {
      return;
    }
    mLastChecked = now;

    if (mManifestFile == null) {
      IFolderWrapper projectFolder = new IFolderWrapper(mProject);
      mManifestFile = AndroidManifest.getManifest(projectFolder);
      if (mManifestFile == null) {
        return;
      }
    }

    // Check to see if our data is up to date
    long fileModified = mManifestFile.getModificationStamp();
    if (fileModified == mLastModified) {
      // Already have up to date data
      return;
    }
    mLastModified = fileModified;

    mActivityThemes = new HashMap<String, String>();
    mManifestTheme = null;
    mTargetSdk = 1; // Default when not specified
    mMinSdk = 1; // Default when not specified
    mMinSdkName = ""; // Default when not specified
    mPackage = ""; // $NON-NLS-1$
    mApplicationIcon = null;
    mApplicationLabel = null;

    Document document = null;
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      InputSource is = new InputSource(mManifestFile.getContents());

      factory.setNamespaceAware(true);
      factory.setValidating(false);
      DocumentBuilder builder = factory.newDocumentBuilder();
      document = builder.parse(is);

      Element root = document.getDocumentElement();
      mPackage = root.getAttribute(ATTRIBUTE_PACKAGE);
      NodeList activities = document.getElementsByTagName(NODE_ACTIVITY);
      for (int i = 0, n = activities.getLength(); i < n; i++) {
        Element activity = (Element) activities.item(i);
        String theme = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_THEME);
        if (theme != null && theme.length() > 0) {
          String name = activity.getAttributeNS(NS_RESOURCES, ATTRIBUTE_NAME);
          if (name.startsWith(".") // $NON-NLS-1$
              && mPackage != null
              && mPackage.length() > 0) {
            name = mPackage + name;
          }
          mActivityThemes.put(name, theme);
        }
      }

      NodeList applications = root.getElementsByTagName(AndroidManifest.NODE_APPLICATION);
      if (applications.getLength() > 0) {
        assert applications.getLength() == 1;
        Element application = (Element) applications.item(0);
        if (application.hasAttributeNS(NS_RESOURCES, ATTRIBUTE_ICON)) {
          mApplicationIcon = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_ICON);
        }
        if (application.hasAttributeNS(NS_RESOURCES, ATTRIBUTE_LABEL)) {
          mApplicationLabel = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_LABEL);
        }

        String defaultTheme = application.getAttributeNS(NS_RESOURCES, ATTRIBUTE_THEME);
        if (defaultTheme != null && !defaultTheme.isEmpty()) {
          // From manifest theme documentation:
          // "If that attribute is also not set, the default system theme is used."
          mManifestTheme = defaultTheme;
        }
      }

      // Look up target SDK
      NodeList usesSdks = root.getElementsByTagName(NODE_USES_SDK);
      if (usesSdks.getLength() > 0) {
        Element usesSdk = (Element) usesSdks.item(0);
        mMinSdk = getApiVersion(usesSdk, ATTRIBUTE_MIN_SDK_VERSION, 1);
        mTargetSdk = getApiVersion(usesSdk, ATTRIBUTE_TARGET_SDK_VERSION, mMinSdk);
      }

    } catch (SAXException e) {
      AdtPlugin.log(e, "Malformed manifest");
    } catch (Exception e) {
      AdtPlugin.log(e, "Could not read Manifest data");
    }
  }
Пример #23
0
  /**
   * Moves the "decl" node under the "target" node.
   *
   * @param decl A JAXWS customization element (e.g., &lt;JAXWS:class>)
   * @param target XML wsdl element under which the declaration should move. For example,
   *     &lt;xs:element>
   */
  private void moveUnder(Element decl, Element target) {

    // if there is @node on decl and has a child element jaxb:bindings, move it under the target
    // Element jaxb = getJAXBBindingElement(decl);
    if (isJAXBBindingElement(decl)) {
      // add jaxb namespace declaration
      if (!target.hasAttributeNS(Constants.NS_XMLNS, "jaxb")) {
        target.setAttributeNS(
            Constants.NS_XMLNS, "xmlns:jaxb", JAXWSBindingsConstants.NS_JAXB_BINDINGS);
      }

      // add jaxb:bindings version info. Lets put it to 1.0, may need to change latter
      if (!target.hasAttributeNS(JAXWSBindingsConstants.NS_JAXB_BINDINGS, "version")) {
        target.setAttributeNS(
            JAXWSBindingsConstants.NS_JAXB_BINDINGS,
            "jaxb:version",
            JAXWSBindingsConstants.JAXB_BINDING_VERSION);
      }

      // HACK: allow XJC extension all the time. This allows people to specify
      // the <xjc:someExtension> in the external bindings. Otherwise users lack the ability
      // to specify jaxb:extensionBindingPrefixes, so it won't work.
      //
      // the current workaround is still problematic in the sense that
      // it can't support user-defined extensions. This needs more careful thought.

      // JAXB doesn't allow writing jaxb:extensionbindingPrefix anywhere other than root element so
      // lets write only on <xs:schema>
      if (target.getLocalName().equals("schema")
          && target.getNamespaceURI().equals(Constants.NS_XSD)
          && !target.hasAttributeNS(
              JAXWSBindingsConstants.NS_JAXB_BINDINGS, "extensionBindingPrefixes")) {
        target.setAttributeNS(
            JAXWSBindingsConstants.NS_JAXB_BINDINGS, "jaxb:extensionBindingPrefixes", "xjc");
        target.setAttributeNS(
            Constants.NS_XMLNS, "xmlns:xjc", JAXWSBindingsConstants.NS_XJC_BINDINGS);
      }

      // insert xs:annotation/xs:appinfo where in jaxb:binding will be put
      target = refineSchemaTarget(target);
      copyInscopeNSAttributes(decl);
    } else if (isJAXWSBindingElement(decl)) {
      // add jaxb namespace declaration
      if (!target.hasAttributeNS(Constants.NS_XMLNS, "JAXWS")) {
        target.setAttributeNS(
            Constants.NS_XMLNS, "xmlns:JAXWS", JAXWSBindingsConstants.NS_JAXWS_BINDINGS);
      }

      // insert xs:annotation/xs:appinfo where in jaxb:binding will be put
      target = refineWSDLTarget(target);
      copyInscopeNSAttributes(decl);
    } else {
      return;
    }

    // finally move the declaration to the target node.
    if (target.getOwnerDocument() != decl.getOwnerDocument()) {
      // if they belong to different DOM documents, we need to clone them
      decl = (Element) target.getOwnerDocument().importNode(decl, true);
    }

    target.appendChild(decl);
  }
Пример #24
0
  /**
   * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String,
   *     java.lang.String, org.xml.sax.Attributes)
   */
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
      throws SAXException {
    // save accumulated character content
    if (inModification && charBuf.length() > 0) {
      //            String normalized = charBuf.toString();
      final String normalized =
          preserveWhitespace
              ? charBuf.toString()
              : charBuf.getNormalizedString(FastStringBuffer.SUPPRESS_BOTH);

      if (normalized.length() > 0) {
        final Text text = doc.createTextNode(charBuf.toString());
        if (stack.isEmpty()) {
          // LOG.debug("appending text to fragment: " + text.getData());
          contents.add(text);
        } else {
          final Element last = stack.peek();
          last.appendChild(text);
        }
      }
      charBuf.setLength(0);
    }
    if (namespaceURI.equals(XUPDATE_NS)) {
      String select = null;
      if (localName.equals(MODIFICATIONS)) {
        startModifications(atts);
        return;
      } else if (localName.equals(VARIABLE)) {
        // variable declaration
        startVariableDecl(atts);
        return;
      } else if (IF.equals(localName)) {
        if (inModification) {
          throw new SAXException("xupdate:if is not allowed inside a modification");
        }
        select = atts.getValue("test");
        final Conditional cond =
            new Conditional(broker, documentSet, select, namespaces, variables);
        cond.setAccessContext(accessCtx);
        conditionals.push(cond);
        return;
      } else if (VALUE_OF.equals(localName)) {
        if (!inModification) {
          throw new SAXException("xupdate:value-of is not allowed outside a modification");
        }

      } else if (APPEND.equals(localName)
          || INSERT_BEFORE.equals(localName)
          || INSERT_AFTER.equals(localName)
          || REMOVE.equals(localName)
          || RENAME.equals(localName)
          || UPDATE.equals(localName)
          || REPLACE.equals(localName)) {
        if (inModification) {
          throw new SAXException("nested modifications are not allowed");
        }
        select = atts.getValue("select");
        if (select == null) {
          throw new SAXException(localName + " requires a select attribute");
        }
        doc = builder.newDocument();
        contents = new NodeListImpl();
        inModification = true;
      } else if ((ELEMENT.equals(localName)
          || ATTRIBUTE.equals(localName)
          || TEXT.equals(localName)
          || PROCESSING_INSTRUCTION.equals(localName)
          || COMMENT.equals(localName))) {
        if (!inModification) {
          throw new SAXException("creation elements are only allowed inside " + "a modification");
        }
        charBuf.setLength(0);
      } else {
        throw new SAXException("Unknown XUpdate element: " + qName);
      }

      // start a new modification section
      if (APPEND.equals(localName)) {
        final String child = atts.getValue("child");
        modification = new Append(broker, documentSet, select, child, namespaces, variables);
      } else if (UPDATE.equals(localName)) {
        modification = new Update(broker, documentSet, select, namespaces, variables);
      } else if (INSERT_BEFORE.equals(localName)) {
        modification =
            new Insert(broker, documentSet, select, Insert.INSERT_BEFORE, namespaces, variables);
      } else if (INSERT_AFTER.equals(localName)) {
        modification =
            new Insert(broker, documentSet, select, Insert.INSERT_AFTER, namespaces, variables);
      } else if (REMOVE.equals(localName)) {
        modification = new Remove(broker, documentSet, select, namespaces, variables);
      } else if (RENAME.equals(localName)) {
        modification = new Rename(broker, documentSet, select, namespaces, variables);
      } else if (REPLACE.equals(localName)) {
        modification = new Replace(broker, documentSet, select, namespaces, variables);
      }

      // process commands for node creation
      else if (ELEMENT.equals(localName)) {
        String name = atts.getValue("name");
        if (name == null) {
          throw new SAXException("element requires a name attribute");
        }
        final int p = name.indexOf(':');
        String namespace = null;
        String prefix = "";
        if (p != Constants.STRING_NOT_FOUND) {
          prefix = name.substring(0, p);
          if (name.length() == p + 1) {
            throw new SAXException("illegal prefix in qname: " + name);
          }
          name = name.substring(p + 1);
          namespace = atts.getValue("namespace");
          if (namespace == null) {
            namespace = (String) namespaces.get(prefix);
          }
          if (namespace == null) {
            throw new SAXException("no namespace defined for prefix " + prefix);
          }
        }
        Element elem;
        if (namespace != null && namespace.length() > 0) {
          elem = doc.createElementNS(namespace, name);
          elem.setPrefix(prefix);
        } else {
          elem = doc.createElement(name);
        }

        if (stack.isEmpty()) {
          contents.add(elem);
        } else {
          final Element last = stack.peek();
          last.appendChild(elem);
        }
        this.setWhitespaceHandling((Element) stack.push(elem));
      } else if (ATTRIBUTE.equals(localName)) {
        final String name = atts.getValue("name");
        if (name == null) {
          throw new SAXException("attribute requires a name attribute");
        }
        final int p = name.indexOf(':');
        String namespace = null;
        if (p != Constants.STRING_NOT_FOUND) {
          final String prefix = name.substring(0, p);
          if (name.length() == p + 1) {
            throw new SAXException("illegal prefix in qname: " + name);
          }
          namespace = atts.getValue("namespace");
          if (namespace == null) {
            namespace = (String) namespaces.get(prefix);
          }
          if (namespace == null) {
            throw new SAXException("no namespace defined for prefix " + prefix);
          }
        }
        Attr attrib =
            namespace != null && namespace.length() > 0
                ? doc.createAttributeNS(namespace, name)
                : doc.createAttribute(name);
        if (stack.isEmpty()) {
          for (int i = 0; i < contents.getLength(); i++) {
            final Node n = contents.item(i);
            String ns = n.getNamespaceURI();
            final String nname = ns == null ? n.getNodeName() : n.getLocalName();
            if (ns == null) {
              ns = "";
            }
            // check for duplicate attributes
            if (n.getNodeType() == Node.ATTRIBUTE_NODE
                && nname.equals(name)
                && ns.equals(namespace)) {
              throw new SAXException(
                  "The attribute " + attrib.getNodeName() + " cannot be specified twice");
            }
          }
          contents.add(attrib);
        } else {
          final Element last = (Element) stack.peek();
          if (namespace != null && last.hasAttributeNS(namespace, name)
              || namespace == null && last.hasAttribute(name)) {
            throw new SAXException(
                "The attribute "
                    + attrib.getNodeName()
                    + " cannot be specified "
                    + "twice on the same element");
          }
          if (namespace != null) {
            last.setAttributeNodeNS(attrib);
          } else {
            last.setAttributeNode(attrib);
          }
        }
        inAttribute = true;
        currentNode = attrib;

        // process value-of
      } else if (VALUE_OF.equals(localName)) {
        select = atts.getValue("select");
        if (select == null) {
          throw new SAXException("value-of requires a select attribute");
        }
        final Sequence seq = processQuery(select);
        if (LOG.isDebugEnabled()) {
          LOG.debug("Found " + seq.getItemCount() + " items for value-of");
        }
        Item item;
        try {
          for (final SequenceIterator i = seq.iterate(); i.hasNext(); ) {
            item = i.nextItem();
            if (Type.subTypeOf(item.getType(), Type.NODE)) {
              final Node node = NodeSetHelper.copyNode(doc, ((NodeValue) item).getNode());
              if (stack.isEmpty()) {
                contents.add(node);
              } else {
                final Element last = (Element) stack.peek();
                last.appendChild(node);
              }
            } else {
              final String value = item.getStringValue();
              characters(value.toCharArray(), 0, value.length());
            }
          }
        } catch (final XPathException e) {
          throw new SAXException(e.getMessage(), e);
        }
      }
    } else if (inModification) {
      final Element elem =
          namespaceURI != null && namespaceURI.length() > 0
              ? doc.createElementNS(namespaceURI, qName)
              : doc.createElement(qName);
      Attr a;
      for (int i = 0; i < atts.getLength(); i++) {
        final String name = atts.getQName(i);
        final String nsURI = atts.getURI(i);
        if (name.startsWith("xmlns")) {
          // Why are these showing up? They are supposed to be stripped out?
        } else {
          a = nsURI != null ? doc.createAttributeNS(nsURI, name) : doc.createAttribute(name);
          a.setValue(atts.getValue(i));
          if (nsURI != null) {
            elem.setAttributeNodeNS(a);
          } else {
            elem.setAttributeNode(a);
          }
        }
      }
      if (stack.isEmpty()) {
        contents.add(elem);
      } else {
        final Element last = (Element) stack.peek();
        last.appendChild(elem);
      }
      this.setWhitespaceHandling((Element) stack.push(elem));
    }
  }
 @Kroll.method
 public boolean hasAttributeNS(String namespaceURI, String localName) throws DOMException {
   return element.hasAttributeNS(namespaceURI, localName);
 }