Ejemplo n.º 1
0
  // read all defense missile from given defense destructor
  protected void readDefenseDestructorFromGivenDestructor(Element destructor) {
    NamedNodeMap attributes = destructor.getAttributes();
    String id = "";
    String type;

    Attr attr = (Attr) attributes.item(0);

    String name = attr.getNodeName();

    // if it's iron dome
    if (name.equals("id")) {
      id = attr.getNodeValue();

      // update id's in the war
      IdGenerator.updateIronDomeId(id);
      // add to war
      war.addIronDome(id);

      NodeList destructdMissiles = destructor.getElementsByTagName("destructdMissile");
      readDefensDestructoreMissiles(destructdMissiles, id);

      // if it's launcher destructor
    } else {
      if (name.equals("type")) {
        type = attr.getNodeValue();

        // add to war
        id = war.addDefenseLauncherDestructor(type);

        NodeList destructedLanuchers = destructor.getElementsByTagName("destructedLanucher");
        readDefensDestructoreMissiles(destructedLanuchers, id);
      }
    }
  }
  public void testWrite() throws Exception {
    Car car = new Car();
    car.numberOfDoors = 2;
    car.milesPerGallon = 30;
    car.model = "Grand Am";
    car.manufacturer = "Pontiac";
    car.topSpeed = 220;

    Document carDocument = marshaller.objectToXML(car);
    Element root =
        (Element) carDocument.getElementsByTagNameNS("mynamespaceuri", "vehicle").item(0);
    Attr elem = root.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
    String carType = elem.getNodeValue();
    assertTrue(
        "The type field was written incorrectly for the subclass",
        carType.equals("prefix:car-type"));

    Vehicle vehicle = new Vehicle();
    vehicle.model = "Blah Blah";
    vehicle.manufacturer = "Some Place";
    vehicle.topSpeed = 10000;

    Document vehicleDocument = marshaller.objectToXML(vehicle);
    root = (Element) vehicleDocument.getElementsByTagNameNS("mynamespaceuri", "vehicle").item(0);
    elem = root.getAttributeNodeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
    String vehicleType = elem.getNodeValue();
    assertTrue(
        "The type field was written incorrectly for the superclass",
        vehicleType.equals("prefix:vehicle-type"));
  }
  /**
   * @see
   *     com.ibm.sse.editor.extensions.hyperlink.IHyperlinkPartitionRecognizer#recognize(org.eclipse.jface.text.IDocument,
   *     com.ibm.sse.editor.extensions.hyperlink.IHyperlinkRegion)
   */
  public boolean recognize(IDocument document, int offset, IHyperlinkRegion region) {
    StructuredModelWrapper smw = new StructuredModelWrapper();
    smw.init(document);
    try {
      Document xmlDocument = smw.getDocument();
      if (xmlDocument == null) return false;

      Node n = Utils.findNodeForOffset(xmlDocument, offset);
      if (!(n instanceof Attr)) return false;

      IHyperlinkRegion r = getRegion(document, offset);
      if (r == null) return false;

      Attr attr = (Attr) n;
      String attrName = attr.getNodeName();
      if (!"var".equals(attrName) && !"basename".equals(attrName))
        return false; //$NON-NLS-1$ //$NON-NLS-2$

      Element lbTag = attr.getOwnerElement();
      String name = lbTag.getTagName();
      int column = name.indexOf(":"); // $NON-NLS-1$
      if (column == -1) return false;
      String usedPrefix = name.substring(0, column);
      if (usedPrefix == null || usedPrefix.trim().length() == 0) return false;

      String[] prefixes = getLoadBundleTagPrefixes(document, offset);
      if (prefixes == null) return true; // xhtml

      boolean prefixIsAbleToBeUsed = false;
      for (String prefix : prefixes) {
        if (usedPrefix.equals(prefix)) {
          prefixIsAbleToBeUsed = true;
          break;
        }
      }
      if (!prefixIsAbleToBeUsed) return false;

      Attr lbTagVar = lbTag.getAttributeNode("var"); // $NON-NLS-1$
      Attr lbTagBasename = lbTag.getAttributeNode("basename"); // $NON-NLS-1$

      if (lbTagVar == null
          || lbTagVar.getNodeValue() == null
          || lbTagVar.getNodeValue().trim().length() == 0) return false;
      if (lbTagBasename == null
          || lbTagBasename.getNodeValue() == null
          || lbTagBasename.getNodeValue().trim().length() == 0) return false;

      return true;
    } finally {
      smw.dispose();
    }
  }
Ejemplo n.º 4
0
 /**
  * This method looks at an attribute and stores it, if it is a namespace attribute.
  *
  * @param attribute to examine
  */
 private void storeAttribute(Attr attribute) {
   // examine the attributes in namespace xmlns
   if (attribute.getNamespaceURI() != null
       && attribute.getNamespaceURI().equals(XMLConstants.XMLNS_ATTRIBUTE_NS_URI)) {
     // Default namespace xmlns="uri goes here"
     if (attribute.getNodeName().equals(XMLConstants.XMLNS_ATTRIBUTE)) {
       putInCache(DEFAULT_NS, attribute.getNodeValue());
     } else {
       // The defined prefixes are stored here
       putInCache(attribute.getLocalName(), attribute.getNodeValue());
     }
   }
 }
Ejemplo n.º 5
0
  /**
   * To return an instance of the HomeLayout JavaBean used to construct the home page boxes.
   * Information is retrieved from the user's XML file then each tag is converted into a Box object.
   *
   * @param id
   * @return HomeLayout
   * @throws ParserConfigurationException
   * @throws SAXException
   * @throws IOException
   */
  public HomeLayout getLayout(int id)
      throws ParserConfigurationException, SAXException, IOException {

    // Open the correct file
    String filename =
        "/home/policygrid/apache-tomcat-6.0.18/webapps/ourspaces/users/" + id + ".xml";

    // Initialise the DOM parser
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Document dom;
    DocumentBuilder db = dbf.newDocumentBuilder();

    // Parse the file
    dom = db.parse(filename);

    // Element docEle = dom.getDocumentElement();

    // get all boxes
    NodeList children = dom.getElementsByTagName("box");

    // Iterate through all boxes to get the the attributes
    for (int i = 0; i < children.getLength(); i++) {
      Node node = (Node) children.item(i);
      String name = "";
      int column = 0;
      int status = 0;
      int position = 0;
      NamedNodeMap atts = node.getAttributes();
      for (int j = 0; j < atts.getLength(); j++) {
        Attr attr = (Attr) atts.item(j);
        if (attr.getNodeName().equals("name")) name = attr.getNodeValue();
        if (attr.getNodeName().equals("column")) column = Integer.parseInt(attr.getNodeValue());
        if (attr.getNodeName().equals("status")) status = Integer.parseInt(attr.getNodeValue());
        if (attr.getNodeName().equals("position")) position = Integer.parseInt(attr.getNodeValue());
      }

      Box box = new Box(name, column, status, position);
      setColumn(box);
    }

    // Sort each list in order of position.

    sort(left);
    sort(middle);
    sort(right);

    HomeLayout home = new HomeLayout(left, middle, right);
    return home;
  }
Ejemplo n.º 6
0
  void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes()) {
      return;
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      if (Constants.NamespaceSpecNS != N.getNamespaceURI()) {
        // Not a namespace definition, ignore.
        if (XML_LANG_URI == N.getNamespaceURI()) {
          xmlattrStack.addXmlnsAttr(N);
        }
        continue;
      }

      String NName = N.getLocalName();
      String NValue = N.getNodeValue();
      if (XML.equals(NName) && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
        continue;
      }
      ns.addMapping(NName, NValue, N);
    }
  }
 public String getValue() {
   switch (kind) {
     case KIND_ATTR_TEXT:
     case KIND_ELEMENT_ATTR:
       {
         // note intentional fall-thru!!
         return attribute.getNodeValue();
       }
     case KIND_ELEMENT_CMATTRIBUTE:
       {
         // CS : one would think that we'd just need to return "" here
         // but after editing a item of this kind and giving it value
         // the list of item's doesn't get recomputed.. so we need to trick
         // one of these items to behave like the KIND_ELEMENT_ATTR case
         //
         String value = parent.getAttribute(cmNode.getNodeName());
         return (value != null) ? value : "";
       }
     case KIND_ELEMENT_TEXT:
       {
         return new TreeContentHelper().getElementTextValue(parent);
       }
   }
   return "";
 }
Ejemplo n.º 8
0
  protected void handleParent(Element e, NameSpaceSymbTable ns) {
    if (!e.hasAttributes() && e.getNamespaceURI() == null) {
      return;
    }
    xmlattrStack.push(-1);
    NamedNodeMap attrs = e.getAttributes();
    int attrsLength = attrs.getLength();
    for (int i = 0; i < attrsLength; i++) {
      Attr attribute = (Attr) attrs.item(i);
      String NName = attribute.getLocalName();
      String NValue = attribute.getNodeValue();

      if (Constants.NamespaceSpecNS.equals(attribute.getNamespaceURI())) {
        if (!XML.equals(NName) || !Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
          ns.addMapping(NName, NValue, attribute);
        }
      } else if (!"id".equals(NName) && XML_LANG_URI.equals(attribute.getNamespaceURI())) {
        xmlattrStack.addXmlnsAttr(attribute);
      }
    }
    if (e.getNamespaceURI() != null) {
      String NName = e.getPrefix();
      String NValue = e.getNamespaceURI();
      String Name;
      if (NName == null || NName.equals("")) {
        NName = "xmlns";
        Name = "xmlns";
      } else {
        Name = "xmlns:" + NName;
      }
      Attr n = e.getOwnerDocument().createAttributeNS("http://www.w3.org/2000/xmlns/", Name);
      n.setValue(NValue);
      ns.addMapping(NName, NValue, n);
    }
  }
Ejemplo n.º 9
0
 private static Condition parse(Element element, LogHeaderDefinition definition) {
   String name = element.getTagName();
   if ("message".equals(name))
     try {
       return new MessageCondition(Pattern.compile(element.getTextContent()));
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in message element", ex);
     }
   else if ("field".equals(name)) {
     Attr attr = element.getAttributeNode("name");
     if (attr == null)
       throw new IllegalArgumentException("[LogFilter] name attribute missing in field element");
     int index = Arrays.asList(definition.groupNames).indexOf(attr.getNodeValue());
     try {
       Pattern pattern = Pattern.compile(element.getTextContent());
       return new FieldCondition(pattern, index);
     } catch (PatternSyntaxException ex) {
       throw new RuntimeException(
           "[LogFilter] invalid regex " + element.getTextContent() + " in field element", ex);
     }
   } else if ("and".equals(name)) return new AndCondition(getChildConditions(element, definition));
   else if ("or".equals(name)) return new OrCondition(getChildConditions(element, definition));
   else if ("not".equals(name)) {
     return new NotCondition(getChildConditions(element, definition)[0]);
   } else if ("index".equals(name)) {
     return new IndexCondition(Integer.parseInt(element.getTextContent()));
   } else if ("following".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new FollowingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else if ("preceding".equals(name)) {
     boolean includeSelf = Boolean.parseBoolean(element.getAttribute("includeSelf"));
     return new PrecedingCondition(getChildConditions(element, definition)[0], includeSelf);
   } else throw new RuntimeException("[LogFilter] invalid element " + name);
 }
Ejemplo n.º 10
0
  @Override
  public XMLSignatureInput engineResolveURI(ResourceResolverContext context)
      throws ResourceResolverException {

    final Attr uriAttr = context.attr;
    final String baseUriString = context.baseUri;
    String documentUri = uriAttr.getNodeValue();
    documentUri = decodeUrl(documentUri);
    final DSSDocument document = getDocument(documentUri);
    if (document != null) {

      // The input stream is closed automatically by XMLSignatureInput class

      // TODO-Bob (05/09/2014):  There is an error concerning the input streams base64 encoded. Some
      // extra bytes are added within the santuario which breaks the HASH.
      // TODO-Vin (05/09/2014): Can you create an isolated test-case JIRA DSS-?
      InputStream inputStream = document.openStream();
      //			final byte[] bytes = DSSUtils.toByteArray(inputStream);
      //			final String string = new String(bytes);
      //			inputStream = DSSUtils.toInputStream(bytes);
      final XMLSignatureInput result = new XMLSignatureInput(inputStream);
      result.setSourceURI(documentUri);
      final MimeType mimeType = document.getMimeType();
      if (mimeType != null) {
        result.setMIMEType(mimeType.getMimeTypeString());
      }
      return result;
    } else {

      Object exArgs[] = {"The uriNodeValue " + documentUri + " is not configured for offline work"};
      throw new ResourceResolverException(
          "generic.EmptyMessage", exArgs, documentUri, baseUriString);
    }
  }
Ejemplo n.º 11
0
  public static String getAttr(Node node, String name) throws ESException {
    Attr attr = ((Element) node).getAttributeNode(name);
    if (attr == null)
      throw new ESException(
          "Attribute \"" + name + "\" not " + "found in \"" + node.getNodeName() + "\"");

    return attr.getNodeValue();
  }
Ejemplo n.º 12
0
 private void replaceLinkAttributes(final Element pushcontent) {
   for (final String attName : new String[] {ATTRIBUTE_NAME_HREF, ATTRIBUTE_NAME_CONREF}) {
     final Attr att = pushcontent.getAttributeNode(attName);
     if (att != null) {
       att.setNodeValue(replaceURL(att.getNodeValue()));
     }
   }
 }
Ejemplo n.º 13
0
 public static Map<String, Object> loadAttributes(Element e) {
   Map<String, Object> map = new HashMap<String, Object>();
   NamedNodeMap nm = e.getAttributes();
   for (int j = 0; j < nm.getLength(); j++) {
     Node n = nm.item(j);
     if (n instanceof Attr) {
       Attr attr = (Attr) n;
       map.put(attr.getName(), attr.getNodeValue());
     }
   }
   return map;
 }
Ejemplo n.º 14
0
 private static boolean compareElementAttrs(Element e1, Element e2) {
   NamedNodeMap at1 = e1.getAttributes();
   NamedNodeMap at2 = e2.getAttributes();
   if (at1.getLength() != at2.getLength()) {
     System.out.println("Different number of attributes");
   }
   for (int i = 0; i < at1.getLength(); i++) {
     Attr attr1 = (Attr) at1.item(i);
     Attr attr2 = (Attr) at2.getNamedItemNS(attr1.getNamespaceURI(), attr1.getLocalName());
     if (attr2 == null) {
       System.out.println("Attribute " + attr1.getNodeName() + " not found");
       return false;
     }
     if (!compareStrings(attr1.getNodeValue(), attr2.getNodeValue())) {
       System.out.println(
           "Different attributes " + attr1.getNodeName() + " and " + attr2.getNodeName());
       return false;
     }
   }
   return true;
 }
 /**
  * Receive notification of a node.
  *
  * @param node The Node to be added to the document
  * @param namespaceResolver The NamespaceResolver can be used to resolve the namespace URI/prefix
  *     of the node
  */
 public void node(
     Node node, NamespaceResolver namespaceResolver, String newNamespace, String newName) {
   if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
     Attr attr = (Attr) node;
     String resolverPfx = null;
     if (getNamespaceResolver() != null) {
       resolverPfx = this.getNamespaceResolver().resolveNamespaceURI(attr.getNamespaceURI());
     }
     String namespaceURI = attr.getNamespaceURI();
     // If the namespace resolver contains a prefix for the attribute's URI,
     // use it instead of what is set on the attribute
     if (resolverPfx != null) {
       attribute(
           attr.getNamespaceURI(),
           Constants.EMPTY_STRING,
           resolverPfx + Constants.COLON + attr.getLocalName(),
           attr.getNodeValue());
     } else {
       attribute(
           attr.getNamespaceURI(), Constants.EMPTY_STRING, attr.getName(), attr.getNodeValue());
       // May need to declare the URI locally
       if (attr.getNamespaceURI() != null) {
         namespaceDeclaration(attr.getPrefix(), attr.getNamespaceURI());
         this.getNamespaceResolver().put(attr.getPrefix(), attr.getNamespaceURI());
       }
     }
   } else if (node.getNodeType() == Node.TEXT_NODE) {
     characters(node.getNodeValue());
   } else {
     try {
       WriterRecordContentHandler wrcHandler = new WriterRecordContentHandler();
       XMLFragmentReader xfragReader = new XMLFragmentReader(namespaceResolver);
       xfragReader.setContentHandler(wrcHandler);
       xfragReader.setProperty("http://xml.org/sax/properties/lexical-handler", wrcHandler);
       xfragReader.parse(node, newNamespace, newName);
     } catch (SAXException sex) {
       throw XMLMarshalException.marshalException(sex);
     }
   }
 }
Ejemplo n.º 16
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);
  }
Ejemplo n.º 17
0
  public String getAttributeValue(String ns, String local) {
    Attr at;
    if (ns == null || ns.equals("")) {
      at = getCurrentElement().getAttributeNode(local);
    } else {
      at = getCurrentElement().getAttributeNodeNS(ns, local);
    }

    if (at == null) {
      return null;
    }
    return at.getNodeValue();
  }
Ejemplo n.º 18
0
  /**
   * Returns the Attr[]s to be outputted for the given element. <br>
   * The code of this method is a copy of {@link #handleAttributes(Element, NameSpaceSymbTable)},
   * whereas it takes into account that subtree-c14n is -- well -- subtree-based. So if the element
   * in question isRoot of c14n, it's parent is not in the node set, as well as all other ancestors.
   *
   * @param E
   * @param ns
   * @return the Attr[]s to be outputted
   * @throws CanonicalizationException
   */
  Iterator handleAttributesSubtree(Element E, NameSpaceSymbTable ns)
      throws CanonicalizationException {
    if (!E.hasAttributes() && !firstCall) {
      return null;
    }
    // result will contain the attrs which have to be outputted
    final SortedSet result = this.result;
    result.clear();
    NamedNodeMap attrs = E.getAttributes();
    int attrsLength = attrs.getLength();

    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      String NUri = N.getNamespaceURI();

      if (XMLNS_URI != NUri) {
        // It's not a namespace attr node. Add to the result and continue.
        result.add(N);
        continue;
      }

      String NName = N.getLocalName();
      String NValue = N.getValue();
      if (XML.equals(NName) && XML_LANG_URI.equals(NValue)) {
        // The default mapping for xml must not be output.
        continue;
      }

      Node n = ns.addMappingAndRender(NName, NValue, N);

      if (n != null) {
        // Render the ns definition
        result.add(n);
        if (C14nHelper.namespaceIsRelative(N)) {
          Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()};
          throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace", exArgs);
        }
      }
    }

    if (firstCall) {
      // It is the first node of the subtree
      // Obtain all the namespaces defined in the parents, and added to the output.
      ns.getUnrenderedNodes(result);
      // output the attributes in the xml namespace.
      xmlattrStack.getXmlnsAttr(result);
      firstCall = false;
    }

    return result.iterator();
  }
Ejemplo n.º 19
0
 /**
  * adds a tag to the existing word. Only adds the current tag and not its children
  *
  * @param tag
  */
 public void addTag(Element tag) {
   Element e = XMLParser.xmlDocument.createElement(tag.getNodeName());
   NamedNodeMap attributes = tag.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     Attr attribute = (Attr) attributes.item(i);
     e.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
   }
   tags.add(e);
   if (tag.hasChildNodes()) {
     if (tag.getFirstChild().getNodeType() == Element.ELEMENT_NODE) {
       addTag((Element) tag.getFirstChild());
     }
   }
 }
  /**
   * Adds to ns the definitons from the parent elements of el
   *
   * @param el
   * @param ns
   */
  static final void getParentNameSpaces(Element el, NameSpaceSymbTable ns) {
    List parents = new ArrayList();
    Node n1 = el.getParentNode();
    if (!(n1 instanceof Element)) {
      return;
    }
    // Obtain all the parents of the elemnt
    Element parent = (Element) el.getParentNode();
    while (parent != null) {
      parents.add(parent);
      Node n = parent.getParentNode();
      if (!(n instanceof Element)) {
        break;
      }
      parent = (Element) n;
    }
    // Visit them in reverse order.
    ListIterator it = parents.listIterator(parents.size());
    while (it.hasPrevious()) {
      Element ele = (Element) it.previous();
      if (!ele.hasAttributes()) {
        continue;
      }
      NamedNodeMap attrs = ele.getAttributes();
      int attrsLength = attrs.getLength();
      for (int i = 0; i < attrsLength; i++) {
        Attr N = (Attr) attrs.item(i);
        if (!Constants.NamespaceSpecNS.equals(N.getNamespaceURI())) {
          // Not a namespace definition, ignore.
          continue;
        }

        String NName = N.getLocalName();
        String NValue = N.getNodeValue();
        if (XML.equals(NName) && Constants.XML_LANG_SPACE_SpecNS.equals(NValue)) {
          continue;
        }
        ns.addMapping(NName, NValue, N);
      }
    }
    Attr nsprefix;
    if (((nsprefix = ns.getMappingWithoutRendered("xmlns")) != null)
        && "".equals(nsprefix.getValue())) {
      ns.addMappingAndRender("xmlns", "", nullNode);
    }
  }
  /** @inheritDoc */
  public XMLSignatureInput engineResolve(Attr uri, String baseURI)
      throws ResourceResolverException {
    try {
      // calculate new URI
      URI uriNew = getNewURI(uri.getNodeValue(), baseURI);

      String fileName = ResolverLocalFilesystem.translateUriToFilename(uriNew.toString());
      FileInputStream inputStream = new FileInputStream(fileName);
      XMLSignatureInput result = new XMLSignatureInput(inputStream);

      result.setSourceURI(uriNew.toString());

      return result;
    } catch (Exception e) {
      throw new ResourceResolverException("generic.EmptyMessage", e, uri, baseURI);
    }
  }
Ejemplo n.º 22
0
  /**
   * @param element The DOM Element.
   * @param exclude the list of exclude strings.
   * @return A string representation of the element's attributes excluding exclude.
   */
  public static String getElementAttributes(Element element, List<String> exclude) {
    StringBuffer buffer = new StringBuffer();

    if (element != null) {
      NamedNodeMap attributes = element.getAttributes();
      if (attributes != null) {
        for (int i = 0; i < attributes.getLength(); i++) {
          Attr attr = (Attr) attributes.item(i);
          if (!exclude.contains(attr.getNodeName())) {
            buffer.append(attr.getNodeName() + "=");
            buffer.append(attr.getNodeValue() + " ");
          }
        }
      }
    }

    return buffer.toString().trim();
  }
  @Override
  public boolean engineCanResolveURI(final ResourceResolverContext context) {

    final Attr uriAttr = context.attr;
    final String uri = uriAttr.getNodeValue();
    final boolean xPointerQuery = isXPointerQuery(uri, false);
    if (LOG.isDebugEnabled()) {

      LOG.debug(
          "I state that I "
              + (xPointerQuery ? "can" : "cannot")
              + " resolve Uri/Base Uri:'"
              + uri
              + "/"
              + context.baseUri
              + "'");
    }
    return xPointerQuery;
  }
Ejemplo n.º 24
0
  /**
   * @param frame the frame element.
   * @return the name or id of this element if they are present, otherwise null.
   */
  public static String getFrameIdentification(Element frame) {

    Attr attr = frame.getAttributeNode("id");
    if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) {
      return attr.getNodeValue();
    }

    attr = frame.getAttributeNode("name");
    if (attr != null && attr.getNodeValue() != null && !attr.getNodeValue().equals("")) {
      return attr.getNodeValue();
    }

    return null;
  }
Ejemplo n.º 25
0
  @Override
  public void unmarshal(Element root) throws ParseException {
    // attributes
    NamedNodeMap attrs = root.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
      Attr attr = (Attr) attrs.item(i);
      String name = attr.getName();
      String value = attr.getNodeValue();
      if (name.equals("version")) {
        version = value;
        break;
      }
    }

    // elements
    ArrayList<Element> children = (ArrayList<Element>) DOMHelp.getChildElements(root);
    for (Element child : children) {
      String localName = child.getLocalName();
      if (localName.equals("event")) {
        PremisEvent ev = new PremisEvent();
        ev.unmarshal(child);
        getEvent().add(ev);
      } else if (localName.equals("object")) {
        String typeString = child.getAttributeNS(NS.XSI.ns(), "type").replaceAll("^\\w+:", "");
        PremisObjectType type = PremisObject.PremisObjectType.valueOf(typeString);
        if (type == null) {
          continue;
        }
        PremisObject obj = new PremisObject(type);
        obj.unmarshal(child);
        getObject().add(obj);
      } else if (localName.equals("agent")) {
        PremisAgent agent = new PremisAgent();
        agent.unmarshal(child);
        getAgent().add(agent);
      } else if (localName.equals("rights")) {
        PremisRights r = new PremisRights();
        r.unmarshal(child);
        getRights().add(r);
      }
    }
  }
  /**
   * Method getInstance
   *
   * @param uri
   * @param baseURI
   * @param secureValidation
   * @return the instance
   * @throws ResourceResolverException
   */
  public static final ResourceResolver getInstance(
      Attr uri, String baseURI, boolean secureValidation) throws ResourceResolverException {
    synchronized (resolverList) {
      for (ResourceResolver resolver : resolverList) {
        ResourceResolver resolverTmp = resolver;
        if (!resolver.resolverSpi.engineIsThreadSafe()) {
          try {
            resolverTmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance());
          } catch (InstantiationException e) {
            throw new ResourceResolverException("", e, uri, baseURI);
          } catch (IllegalAccessException e) {
            throw new ResourceResolverException("", e, uri, baseURI);
          }
        }

        if (log.isLoggable(java.util.logging.Level.FINE)) {
          log.log(
              java.util.logging.Level.FINE,
              "check resolvability by class " + resolverTmp.getClass().getName());
        }

        resolverTmp.resolverSpi.secureValidation = secureValidation;
        if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) {
          // Check to see whether the Resolver is allowed
          if (secureValidation
              && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem
                  || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) {
            Object exArgs[] = {resolverTmp.resolverSpi.getClass().getName()};
            throw new ResourceResolverException(
                "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI);
          }
          return resolverTmp;
        }
      }
    }

    Object exArgs[] = {((uri != null) ? uri.getNodeValue() : "null"), baseURI};

    throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI);
  }
Ejemplo n.º 27
0
  public String getNamespacePrefix(String uri) {

    NamespaceContextIterator eachNamespace = getNamespaceContextNodes();
    while (eachNamespace.hasNext()) {
      org.w3c.dom.Attr namespaceDecl = eachNamespace.nextNamespaceAttr();
      if (namespaceDecl.getNodeValue().equals(uri)) {
        String candidatePrefix = namespaceDecl.getLocalName();
        if ("xmlns".equals(candidatePrefix)) return "";
        else return candidatePrefix;
      }
    }

    // Find if any of the ancestors' name has this uri
    org.w3c.dom.Node currentAncestor = this;
    while (currentAncestor != null && !(currentAncestor instanceof Document)) {

      if (uri.equals(currentAncestor.getNamespaceURI())) return currentAncestor.getPrefix();
      currentAncestor = currentAncestor.getParentNode();
    }

    return null;
  }
Ejemplo n.º 28
0
  @Override
  public boolean engineCanResolveURI(final ResourceResolverContext context) {

    final Attr uriAttr = context.attr;
    final String baseUriString = context.baseUri;

    String documentUri = uriAttr.getNodeValue();
    documentUri = decodeUrl(documentUri);
    if (documentUri.equals("") || documentUri.startsWith("#")) {
      return false;
    }
    try {

      if (isKnown(documentUri) != null) {

        LOG.debug(
            "I state that I can resolve '" + documentUri.toString() + "' (external document)");
        return true;
      }
      final URI baseUri = new URI(baseUriString);
      URI uriNew = new URI(baseUri, documentUri);
      if (uriNew.getScheme().equals("http")) {

        LOG.debug("I state that I can resolve '" + uriNew.toString() + "'");
        return true;
      }
      LOG.debug("I state that I can't resolve '" + uriNew.toString() + "'");
    } catch (URI.MalformedURIException ex) {
      if (documents == null || documents.size() == 0) {
        LOG.warn("OfflineResolver: WARNING: ", ex);
      }
    }
    if (doesContainOnlyOneDocument()) {

      return true;
    }
    return false;
  }
  /** @inheritDoc */
  public boolean engineCanResolve(Attr uri, String baseURI) {
    if (uri == null) {
      return false;
    }

    String uriNodeValue = uri.getNodeValue();

    if (uriNodeValue.equals("")
        || (uriNodeValue.charAt(0) == '#')
        || uriNodeValue.startsWith("http:")) {
      return false;
    }

    try {
      if (log.isDebugEnabled()) {
        log.debug("I was asked whether I can resolve " + uriNodeValue);
      }

      if (uriNodeValue.startsWith("file:") || baseURI.startsWith("file:")) {
        if (log.isDebugEnabled()) {
          log.debug("I state that I can resolve " + uriNodeValue);
        }
        return true;
      }
    } catch (Exception e) {
      if (log.isDebugEnabled()) {
        log.debug(e);
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("But I can't");
    }

    return false;
  }
Ejemplo n.º 30
0
  /**
   * Returns the Attr[]s to be outputted for the given element. <br>
   * IMPORTANT: This method expects to work on a modified DOM tree, i.e. a DOM which has been
   * prepared using {@link
   * com.sun.org.apache.xml.internal.security.utils.XMLUtils#circumventBug2650(
   * org.w3c.dom.Document)}.
   *
   * @param E
   * @param ns
   * @return the Attr[]s to be outputted
   * @throws CanonicalizationException
   */
  Iterator handleAttributes(Element E, NameSpaceSymbTable ns) throws CanonicalizationException {
    // result will contain the attrs which have to be outputted
    xmlattrStack.push(ns.getLevel());
    boolean isRealVisible = isVisibleDO(E, ns.getLevel()) == 1;
    NamedNodeMap attrs = null;
    int attrsLength = 0;
    if (E.hasAttributes()) {
      attrs = E.getAttributes();
      attrsLength = attrs.getLength();
    }

    SortedSet result = this.result;
    result.clear();

    for (int i = 0; i < attrsLength; i++) {
      Attr N = (Attr) attrs.item(i);
      String NUri = N.getNamespaceURI();

      if (XMLNS_URI != NUri) {
        // A non namespace definition node.
        if (XML_LANG_URI == NUri) {
          xmlattrStack.addXmlnsAttr(N);
        } else if (isRealVisible) {
          // The node is visible add the attribute to the list of output attributes.
          result.add(N);
        }
        // keep working
        continue;
      }

      String NName = N.getLocalName();
      String NValue = N.getValue();
      if ("xml".equals(NName) && XML_LANG_URI.equals(NValue)) {
        /* except omit namespace node with local name xml, which defines
         * the xml prefix, if its string value is http://www.w3.org/XML/1998/namespace.
         */
        continue;
      }
      // add the prefix binding to the ns symb table.
      // ns.addInclusiveMapping(NName,NValue,N,isRealVisible);
      if (isVisible(N)) {
        if (!isRealVisible && ns.removeMappingIfRender(NName)) {
          continue;
        }
        // The xpath select this node output it if needed.
        // Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible);
        Node n = ns.addMappingAndRender(NName, NValue, N);
        if (n != null) {
          result.add(n);
          if (C14nHelper.namespaceIsRelative(N)) {
            Object exArgs[] = {E.getTagName(), NName, N.getNodeValue()};
            throw new CanonicalizationException("c14n.Canonicalizer.RelativeNamespace", exArgs);
          }
        }
      } else {
        if (isRealVisible && NName != XMLNS) {
          ns.removeMapping(NName);
        } else {
          ns.addMapping(NName, NValue, N);
        }
      }
    }
    if (isRealVisible) {
      // The element is visible, handle the xmlns definition
      Attr xmlns = E.getAttributeNodeNS(XMLNS_URI, XMLNS);
      Node n = null;
      if (xmlns == null) {
        // No xmlns def just get the already defined.
        n = ns.getMapping(XMLNS);
      } else if (!isVisible(xmlns)) {
        // There is a definition but the xmlns is not selected by the xpath.
        // then xmlns=""
        n = ns.addMappingAndRender(XMLNS, "", nullNode);
      }
      // output the xmlns def if needed.
      if (n != null) {
        result.add(n);
      }
      // Float all xml:* attributes of the unselected parent elements to this one.
      // addXmlAttributes(E,result);
      xmlattrStack.getXmlnsAttr(result);
      ns.getUnrenderedNodes(result);
    }

    return result.iterator();
  }