/**
   * @param containingHtmlElement the name of the HTML element containing el. If the HTML element is
   *     contained inside a template construct then this name may differ from el's immediate parent.
   */
  private void inspectElement(JobEnvelope source, Element el, ElKey containingHtmlElement) {
    ElKey elKey = ElKey.forElement(el);

    // Recurse early so that ihtml:dynamic elements have been parsed before we
    // process the attributes element list.
    for (Node child : Nodes.childrenOf(el)) {
      inspect(source, child, elKey);
    }

    // For each attribute allowed on this element type, ensure that
    // (1) If it is not specified, and its default value is not allowed, then
    //     it is added with a known safe value.
    // (2) Its value is rewritten as appropriate.
    // We don't have to worry about disallowed attributes since those will
    // not be present in scriptsPerNode.  The TemplateSanitizer should have
    // stripped those out.  The TemplateSanitizer should also have stripped out
    // disallowed elements.
    if (!htmlSchema.isElementAllowed(elKey)) {
      return;
    }

    HTML.Element elInfo = htmlSchema.lookupElement(elKey);
    List<HTML.Attribute> attrs = elInfo.getAttributes();
    if (attrs != null) {
      for (HTML.Attribute a : attrs) {
        AttribKey attrKey = a.getKey();
        if (!htmlSchema.isAttributeAllowed(attrKey)) {
          continue;
        }
        Attr attr = null;
        String aUri = attrKey.ns.uri;
        String aName = attrKey.localName;
        Attr unsafe = el.getAttributeNodeNS(aUri, aName);
        if (unsafe != null && a.getValueCriterion().accept(unsafe.getValue())) {
          attr = unsafe;
        } else if ((a.getDefaultValue() != null
                && !a.getValueCriterion().accept(a.getDefaultValue()))
            || !a.isOptional()) {
          attr = el.getOwnerDocument().createAttributeNS(aUri, aName);
          String safeValue;
          if (a.getType() == HTML.Attribute.Type.URI) {
            safeValue = "" + Nodes.getFilePositionFor(el).source().getUri();
          } else {
            safeValue = a.getSafeValue();
          }
          if (safeValue == null) {
            mq.addMessage(
                IhtmlMessageType.MISSING_ATTRIB, Nodes.getFilePositionFor(el), elKey, attrKey);
            continue;
          }
          attr.setNodeValue(safeValue);
          el.setAttributeNodeNS(attr);
        }
        if (attr != null) {
          inspectHtmlAttribute(source, attr, a);
        }
      }
    }
    scriptsPerNode.put(el, null);
  }
Beispiel #2
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);
 }
Beispiel #3
0
 @Override
 public void init(Element element) {
   final Element settingsElement = (Element) element.getElementsByTagName("settings").item(0);
   final NamedNodeMap attributes = settingsElement.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     final Node node = attributes.item(i);
     if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
       final Attr attr = (Attr) node;
       this.params.put(attr.getName(), Float.parseFloat(attr.getValue()));
     }
   }
   final float top = this.params.get("top");
   final float left = this.params.get("left");
   final float bottom = this.params.get("bottom");
   final float right = this.params.get("right");
   final float bWidth = this.params.get("blockWidth");
   final float bHeight = this.params.get("blockHeight");
   final List<XYZItem> truc = new LinkedList<XYZItem>();
   for (float x = left; x < right; x += bWidth) {
     for (float y = bottom; y < top; y += bHeight) {
       truc.add(new XYZItem(x, y, getZValue(x, y)));
     }
   }
   this.map = new double[3][truc.size()];
   int i = 0;
   for (XYZItem item : truc) {
     this.map[0][i] = item.getXValue();
     this.map[1][i] = item.getYValue();
     this.map[2][i] = item.getZValue();
     i++;
   }
 }
Beispiel #4
0
 /*
  * (non-Javadoc) Method declared in IMemento.
  */
 public String getString(String key) {
   Attr attr = element.getAttributeNode(key);
   if (attr == null) {
     return null;
   }
   return attr.getValue();
 }
  private void gatherNamespaces(Element element, List<URI> namespaceSources) throws SAXException {
    NamedNodeMap attributes = element.getAttributes();
    int attributeCount = attributes.getLength();

    for (int i = 0; i < attributeCount; i++) {
      Attr attribute = (Attr) attributes.item(i);
      String namespace = attribute.getNamespaceURI();

      if (XMLConstants.XMLNS_ATTRIBUTE_NS_URI.equals(namespace)) {
        try {
          namespaceSources.add(new URI(attribute.getValue()));
        } catch (URISyntaxException e) {
          throw new SAXException(
              "Cannot validate this document with this class.  Namespaces must be valid URIs.  Found Namespace: '"
                  + attribute.getValue()
                  + "'.",
              e);
        }
      }
    }

    NodeList childNodes = element.getChildNodes();
    int childCount = childNodes.getLength();
    for (int i = 0; i < childCount; i++) {
      Node child = childNodes.item(i);

      if (child.getNodeType() == Node.ELEMENT_NODE) {
        gatherNamespaces((Element) child, namespaceSources);
      }
    }
  }
Beispiel #6
0
    Node create(Node parent, Document doc) throws ThinklabException {

      Node ret = doc.createElement(tag);

      if (attrs != null)
        for (Pair<String, String> a : attrs) {
          Attr attr = doc.createAttribute(a.getFirst());
          attr.setValue(a.getSecond());
          ((Element) ret).setAttributeNode(attr);
        }

      for (Object o : contents) {

        if (o instanceof String) {
          String text = (String) o;
          XMLDocument.setTextContent(doc, ret, text);
        } else if (o instanceof Collection<?>) {
          for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) {
            Object no = it.next();
            if (!(no instanceof XmlNode)) {
              throw new ThinklabValidationException("XML.node: collections must be of XmlNode");
            }
            ret.appendChild(((XmlNode) no).create(ret, doc));
          }
        } else if (o instanceof XmlNode) {
          ret.appendChild(((XmlNode) o).create(ret, doc));
        }
      }

      return ret;
    }
Beispiel #7
0
  void _serializeString(String key, String value) {
    NodeList elements = stringElements.getElementsByTagName(ENTRY_FLAG);

    final int size = elements.getLength();

    for (int i = 0; i < size; ++i) {
      Element e = (Element) elements.item(i);
      Attr nameAttr = e.getAttributeNode(KEY_FLAG);
      if (nameAttr == null) {
        throw newMalformedKeyAttrException(Repository.STRING);
      }
      if (key.equals(nameAttr.getValue())) {
        Attr valueAttr = e.getAttributeNode(VALUE_FLAG);
        if (valueAttr == null) {
          throw newMalformedValueAttrException(key, Repository.STRING);
        }
        valueAttr.setValue(value);
        return;
      }
    }

    // no existing element found
    Element element = xmlDoc.createElement(ENTRY_FLAG);
    element.setAttribute(KEY_FLAG, key);
    element.setAttribute(VALUE_FLAG, value);
    stringElements.appendChild(element);
  }
Beispiel #8
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);
    }
  }
Beispiel #9
0
  /**
   * Recurse through a node and its children and make all gml:ids unique
   *
   * @param node The node to examine
   */
  public static void makeGmlIdsUnique(final Node node, final Map<String, Integer> foundIds) {
    // check this node's attributes
    final NamedNodeMap attributes = node.getAttributes();
    final String nodeNamespace = node.getNamespaceURI();
    if (attributes != null) {
      for (int i = 0, len = attributes.getLength(); i < len; i++) {
        final Attr attr = (Attr) attributes.item(i);
        if (attr.getLocalName().equals(GmlConstants.AN_ID)) {
          if (checkAttributeForGmlId(attr, nodeNamespace)) {
            final String gmlId = attr.getValue();
            if (foundIds.containsKey(gmlId)) {
              /*
               * id has already been found, suffix this one with
               * the found count for this id
               */
              attr.setValue(gmlId + foundIds.get(gmlId));
              // increment the found count for this id
              foundIds.put(gmlId, foundIds.get(gmlId) + 1);
            } else {
              // id is new, add it to the foundIds map
              foundIds.put(gmlId, 1);
            }
          }
        }
      }
    }

    // recurse this node's children
    final NodeList children = node.getChildNodes();
    if (children != null) {
      for (int i = 0, len = children.getLength(); i < len; i++) {
        makeGmlIdsUnique(children.item(i), foundIds);
      }
    }
  }
  public Document export(Document doc, Element root, Customer cus, List<CardBean> cards) {
    Element customer = doc.createElement("Kunde");
    root.appendChild(customer);

    Attr cusNum = doc.createAttribute("Kundennummer");
    cusNum.setValue(cus.getCustomernumber());
    customer.setAttributeNode(cusNum);

    Element cusName = doc.createElement("Name");
    cusName.appendChild(doc.createTextNode(cus.getName()));
    customer.appendChild(cusName);

    Iterator<CardBean> it = cards.iterator();
    while (it.hasNext()) {
      CardBean card = it.next();

      Element cusCard = doc.createElement("Karte");
      customer.appendChild(cusCard);

      Attr cardNum = doc.createAttribute("Kartennummer");
      cardNum.setValue(card.getCardNumber());
      cusCard.setAttributeNode(cardNum);

      Element telFirst = doc.createElement("Telefonnummer");
      telFirst.appendChild(doc.createTextNode(card.getPhoneString()));
      cusCard.appendChild(telFirst);
    }

    return doc;
  }
  protected void transferAttributes(
      Element source, Element result, java.util.List nonTransferList) {
    boolean debug = false;
    NamedNodeMap sourceAttrNodeMap = source.getAttributes();
    if (sourceAttrNodeMap == null) return;

    NamedNodeMap resultAttrNodeMap = result.getAttributes();

    for (int index = 0; index < sourceAttrNodeMap.getLength(); index++) {
      Node sourceAttrNode = sourceAttrNodeMap.item(index);
      if (!this.canTransferAttribute(sourceAttrNode.getNodeName(), nonTransferList)) continue;
      if (!isValidAttributeToTransfer(
          sourceAttrNode.getNodeName(), getAttributeListForElement(result.getTagName()))) continue;
      if (resultAttrNodeMap == null) {
        Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
        addAttr.setValue(sourceAttrNode.getNodeValue());
        result.setAttributeNode(addAttr);
      } else {
        Node resultAttrNode = resultAttrNodeMap.getNamedItem(sourceAttrNode.getNodeName());
        if (resultAttrNode != null) {
          resultAttrNode.setNodeValue(sourceAttrNode.getNodeValue());
          // result.setAttributeNode((Attr)resultAttrNode);
        } else {
          Attr addAttr = result.getOwnerDocument().createAttribute(sourceAttrNode.getNodeName());
          addAttr.setValue(sourceAttrNode.getNodeValue());
          result.setAttributeNode(addAttr);
        }
      }
    }
  }
  /**
   * Creates 'wsu:Id' attribute for wsu:Timestamp needed for signature.
   *
   * @param message
   * @return
   * @throws ParserException
   */
  private String createTimestampUuid(SoapMessage message) throws ParserException {

    NodeList timestampList =
        message
            .getHeader()
            .getOwnerDocument()
            .getElementsByTagNameNS(WSU_NAMESPACE, WSU_TIMESTAMP_LOCAL_NAME);

    assert timestampList.getLength() <= 1;

    if (timestampList.getLength() == 1) {
      assert timestampList.item(0).getNodeType() == Node.ELEMENT_NODE;

      Element timestamp = (Element) timestampList.item(0);
      String timestampId = Util.randomNCNameUUID();

      Attr wsuId = timestamp.getOwnerDocument().createAttributeNS(WSU_NAMESPACE, WSU_ID_LOCAL_NAME);
      wsuId.setPrefix(timestamp.getPrefix());

      wsuId.setValue(timestampId);
      timestamp.setAttributeNodeNS(wsuId);
      timestamp.setIdAttributeNode(wsuId, true);

      log.trace("Created wsu:Id for wsu:Timestamp: " + timestampId);

      return timestampId;
    }

    log.trace("Timestamp element not found in the message");

    return null;
  }
Beispiel #13
0
  private void writeXMLAttributes(Element node, XmlSerializer serializer, Long recordId) {
    try {
      String nodeName = node.getNodeName();
      if (mySQLiteHelper.tableExists(nodeName)) {
        Cursor cursor = retrieveDatabaseRecordForNode(nodeName, recordId);

        if (cursor.moveToFirst()) {
          // get a map containing the attributes of this node
          NamedNodeMap attributes = node.getAttributes();

          // get the number of nodes in this map
          int numAttrs = attributes.getLength();

          for (int i = 0; i < numAttrs; i++) {
            Attr attr = (Attr) attributes.item(i);
            String attrName = attr.getNodeName();
            try {
              // setting attribute to element
              if (cursor.getColumnIndex(attrName) != -1) {
                serializer.attribute(
                    "", attrName, cursor.getString(cursor.getColumnIndex(attrName)));
              }
            } catch (Exception doNothing) {
              doNothing.printStackTrace();
            }
          }
          cursor.close();
        }
      }

    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
 @Override
 public void apply(Element e) {
   if (e.getTagName().equals("property")) {
     Element parent = (Element) e.getParentNode();
     if (parent != null && parent.getTagName().equals("ndbx")) {
       Attr name = e.getAttributeNode("name");
       Attr value = e.getAttributeNode("value");
       if (name != null && name.getValue().equals("oscPort")) {
         if (value != null) {
           Element device = e.getOwnerDocument().createElement("device");
           device.setAttribute("name", "osc1");
           device.setAttribute("type", "osc");
           Element portProperty = e.getOwnerDocument().createElement("property");
           portProperty.setAttribute("name", "port");
           portProperty.setAttribute("value", value.getValue());
           device.appendChild(portProperty);
           Element autostartProperty = e.getOwnerDocument().createElement("property");
           autostartProperty.setAttribute("name", "autostart");
           autostartProperty.setAttribute("value", "true");
           device.appendChild(autostartProperty);
           parent.replaceChild(device, e);
         } else {
           parent.removeChild(e);
         }
       }
     }
   }
 }
Beispiel #15
0
  @Override
  public void relink_namespace(ThreadContext context) {
    Element e = (Element) node;

    e.getOwnerDocument().renameNode(e, e.lookupNamespaceURI(e.getPrefix()), e.getNodeName());

    if (e.hasAttributes()) {
      NamedNodeMap attrs = e.getAttributes();

      for (int i = 0; i < attrs.getLength(); i++) {
        Attr attr = (Attr) attrs.item(i);
        String nsUri = "";
        String prefix = attr.getPrefix();
        String nodeName = attr.getNodeName();
        if ("xml".equals(prefix)) {
          nsUri = "http://www.w3.org/XML/1998/namespace";
        } else if ("xmlns".equals(prefix) || nodeName.equals("xmlns")) {
          nsUri = "http://www.w3.org/2000/xmlns/";
        } else {
          nsUri = attr.lookupNamespaceURI(nodeName);
        }

        e.getOwnerDocument().renameNode(attr, nsUri, nodeName);
      }
    }

    if (e.hasChildNodes()) {
      ((XmlNodeSet) children(context)).relink_namespace(context);
    }
  }
Beispiel #16
0
  private void store_data(Location loc) {

    Element trkpt = gpx_document.createElement("trkpt");

    Attr longitude = gpx_document.createAttribute("lon");
    Attr latitude = gpx_document.createAttribute("lat");
    longitude.setValue(Double.toString(currentLongitude));
    latitude.setValue(Double.toString(currentLatitude));

    trkpt.setAttributeNode(longitude);
    trkpt.setAttributeNode(latitude);

    Element elevation = gpx_document.createElement("ele");
    String altitude = Double.toString(loc.getAltitude());
    elevation.appendChild(gpx_document.createTextNode(altitude));
    trkpt.appendChild(elevation);

    Element timestamp = gpx_document.createElement("time");
    String time = Long.toString(loc.getTime());
    timestamp.appendChild(gpx_document.createTextNode(time));
    trkpt.appendChild(timestamp);

    Element type = gpx_document.createElement("type");
    String difficulty = currentDifficulty.getDifficulty();
    type.appendChild(gpx_document.createTextNode(difficulty));
    trkpt.appendChild(type);

    trackSegment.appendChild(trkpt);

    update_screen_info(altitude, difficulty);
  }
  //
  // Marshaller's private methods
  //
  private Element marshallConfiguration(ComponentConfigurationImpl config) throws Exception {
    // get ComponentConfigurationImpl Object data
    String configPid = config.getPid();
    Map<String, Object> configProperty = config.getConfigurationProperties();
    Tocd configOCD = config.getDefinition();

    // create configuration element
    Element configurationElement =
        mashallDoc.createElement(ESF_NAMESPACE + ":" + CONFIGURATIONS_CONFIGURATION);
    Attr propertiesAttribute = mashallDoc.createAttribute(CONFIGURATION_PID);
    propertiesAttribute.setNodeValue(configPid);
    configurationElement.setAttributeNode(propertiesAttribute);

    // Add OCD node and marshall definitions
    if (configOCD != null) {
      Element ocd = new XmlJavaMetadataMapper().marshal(mashallDoc, configOCD);
      configurationElement.appendChild(ocd);
    }

    // Add properties Node and marshall properties
    if (configProperty != null) {
      Element properties = mashallDoc.createElement(ESF_NAMESPACE + ":" + PROPERTIES);
      marshallProperties(configProperty, properties);
      configurationElement.appendChild(properties);
    }

    return configurationElement;
  }
    @Override
    public Object invokeXpathProjection(
        final InvocationContext invocationContext, final Object proxy, final Object[] args)
        throws Throwable {

      //            try {
      //                if (ReflectionHelper.mayProvideParameterNames()) {
      //                    xPath.setXPathVariableResolver(new MethodParamVariableResolver(method,
      // args, xPath.getXPathVariableResolver()));
      //               }

      final XPathExpression expression = invocationContext.getxPathExpression();
      NodeList nodes = (NodeList) expression.evaluate(node, XPathConstants.NODESET);
      int count = 0;
      for (int i = 0; i < nodes.getLength(); ++i) {
        if (Node.ATTRIBUTE_NODE == nodes.item(i).getNodeType()) {
          Attr attr = (Attr) nodes.item(i);
          attr.getOwnerElement().removeAttributeNode(attr);
          ++count;
          continue;
        }
        Node parentNode = nodes.item(i).getParentNode();
        if (parentNode == null) {
          continue;
        }
        parentNode.removeChild(nodes.item(i));
        ++count;
      }
      return getProxyReturnValueForMethod(proxy, method, Integer.valueOf(count));
      //            } finally {
      //                xPath.reset();
      //            }
    }
Beispiel #19
0
    void define(Node self, Document doc) throws ThinklabException {

      if (attrs != null)
        for (Pair<String, String> a : attrs) {
          Attr attr = doc.createAttribute(a.getFirst());
          attr.setValue(a.getSecond());
          ((Element) self).setAttributeNode(attr);
        }

      for (Object o : contents) {

        if (o instanceof String) {
          String text = (String) o;
          XMLDocument.setTextContent(doc, self, text);
        } else if (o instanceof Collection<?>) {
          for (Iterator<?> it = ((Collection<?>) o).iterator(); it.hasNext(); ) {
            Object no = it.next();
            if (no instanceof XmlNode) {
              self.appendChild(((XmlNode) no).create(self, doc));
            } else if (no instanceof Polylist) {
              self.appendChild(((Polylist) no).createXmlNode().create(self, doc));
            } else {
              throw new ThinklabValidationException(
                  "XML.node: collections must be of XmlNode or Polylist");
            }
          }
        } else if (o instanceof XmlNode) {
          self.appendChild(((XmlNode) o).create(self, doc));
        } else if (o instanceof Polylist) {
          self.appendChild(((Polylist) o).createXmlNode().create(self, doc));
        }
      }
    }
 /** @param element */
 private void validatePlugins(Element parent) {
   NodeList list = getChildrenByName(parent, "plugin"); // $NON-NLS-1$
   for (int i = 0; i < list.getLength(); i++) {
     if (fMonitor.isCanceled()) return;
     Element plugin = (Element) list.item(i);
     assertAttributeDefined(plugin, "id", CompilerFlags.ERROR); // $NON-NLS-1$
     assertAttributeDefined(plugin, "version", CompilerFlags.ERROR); // $NON-NLS-1$
     NamedNodeMap attributes = plugin.getAttributes();
     boolean isFragment =
         plugin.getAttribute("fragment").equals("true"); // $NON-NLS-1$ //$NON-NLS-2$
     for (int j = 0; j < attributes.getLength(); j++) {
       Attr attr = (Attr) attributes.item(j);
       String name = attr.getName();
       if (name.equals("id")) { // $NON-NLS-1$
         validatePluginID(plugin, attr, isFragment);
       } else if (name.equals("version")) { // $NON-NLS-1$
         validateVersionAttribute(plugin, attr);
         validateVersion(plugin, attr);
       } else if (name.equals("fragment") || name.equals("unpack")) { // $NON-NLS-1$ //$NON-NLS-2$
         validateBoolean(plugin, attr);
       } else if (!name.equals("os")
           && !name.equals("ws")
           && !name.equals("nl") // $NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
           && !name.equals("arch")
           && !name.equals("download-size") // $NON-NLS-1$ //$NON-NLS-2$
           && !name.equals("install-size")
           && !name.equals("filter")) { // $NON-NLS-1$ //$NON-NLS-2$
         reportUnknownAttribute(plugin, name, CompilerFlags.ERROR);
       }
     }
     validateUnpack(plugin);
   }
 }
  /**
   * Runs the test case.
   *
   * @throws Throwable Any uncaught exception causes test to fail
   */
  @TestTargetNew(
      level = TestLevel.COMPLETE,
      notes = "",
      method = "getNamespaceURI",
      args = {})
  public void testGetNamespaceURI() throws Throwable {
    Document doc;
    Element element;
    Element elementNS;
    Attr attr;
    Attr attrNS;
    String elemNSURI;
    String elemNSURINull;
    String attrNSURI;
    String attrNSURINull;
    String nullNS = null;

    doc = (Document) load("staff", builder);
    element = doc.createElementNS(nullNS, "elem");
    elementNS = doc.createElementNS("http://www.w3.org/DOM/Test/elem", "qual:qelem");
    attr = doc.createAttributeNS(nullNS, "attr");
    attrNS = doc.createAttributeNS("http://www.w3.org/DOM/Test/attr", "qual:qattr");
    elemNSURI = elementNS.getNamespaceURI();
    elemNSURINull = element.getNamespaceURI();
    attrNSURI = attrNS.getNamespaceURI();
    attrNSURINull = attr.getNamespaceURI();
    assertEquals("nodegetnamespaceuri03_elemNSURI", "http://www.w3.org/DOM/Test/elem", elemNSURI);
    assertNull("nodegetnamespaceuri03_1", elemNSURINull);
    assertEquals("nodegetnamespaceuri03_attrNSURI", "http://www.w3.org/DOM/Test/attr", attrNSURI);
    assertNull("nodegetnamespaceuri03_2", attrNSURINull);
  }
Beispiel #22
0
 private void moveNSDeclarationToRoot(BpelEntity entity, Map<String, String> prefixMap) {
   if (!(entity instanceof BpelEntityImpl)) {
     return;
   }
   Element element = ((BpelEntityImpl) entity).getPeer();
   NamedNodeMap map = element.getAttributes();
   for (int i = 0; i < map.getLength(); i++) {
     Node node = map.item(i);
     assert node instanceof Attr;
     Attr attr = (Attr) node;
     if (attr.getValue() == null) {
       continue;
     }
     try {
       if (XMLNS.equals(attr.getName()) || (XMLNS.equals(attr.getPrefix()))) {
         SingletonMap pMap = moveNsDeclaration(entity, attr);
         if (!pMap.keyEqualsValue()) {
           prefixMap.put(pMap.getKey(), pMap.getValue());
         }
       }
     } catch (InvalidNamespaceException e) {
       // This is the case
       // when namespace was originally incorrect and we do not move it
       // to root. We don't do anything.
     }
   }
   /*
    *  we need to update prefixes for those declarations that changed
    *  its perfix after lifing up decl.
    */
   updatePrefixes(entity, prefixMap);
   for (BpelEntity child : entity.getChildren()) {
     moveNSDeclarationToRoot(child, prefixMap);
   }
 }
Beispiel #23
0
 /** @since 3.4 */
 public Boolean getBoolean(String key) {
   Attr attr = element.getAttributeNode(key);
   if (attr == null) {
     return null;
   }
   return Boolean.valueOf(attr.getValue());
 }
  /** 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());
    }
  }
Beispiel #25
0
    Shuttle(Shuttle cp, Element e) {
      this.node = e;
      this.g = cp.g;
      this.svgRoot = cp.svgRoot;
      this.shape = cp.shape;
      this.clip = cp.clip;
      this.fontSize = cp.fontSize;
      this.fontFamily = cp.fontFamily;
      this.stroke = cp.stroke;
      this.fill = cp.fill;
      this.strokeWidth = cp.strokeWidth;
      this.transform = new AffineTransform(cp.transform);
      this.opacity = cp.opacity;
      if (e.hasAttributes()) {
        NamedNodeMap atts = e.getAttributes();
        for (int i = 0; i < atts.getLength(); ++i) {

          Attr att = Attr.class.cast(atts.item(i));
          if (att.getNamespaceURI() != null) continue;
          String s = att.getName();
          String value = att.getValue();
          if (s.equals("style")) {
            for (String styles : value.split("[;]+")) {
              int j = styles.indexOf(':');
              if (j != -1) {
                applyStyle(styles.substring(0, j).trim(), styles.substring(j + 1).trim());
              }
            }

          } else {
            applyStyle(s, att.getValue());
          }
        }
      }
    }
 private void addAttribute(Element e, String attributeName, String value) {
   if (value != null) {
     Attr attr = e.getOwnerDocument().createAttribute(attributeName);
     attr.setNodeValue(value);
     e.setAttributeNode(attr);
   }
 }
Beispiel #27
0
  // Walk the tree from a specified element,
  // inserting data from a DicomObject where required.
  private static String getElementText(Element element, DicomObject dicomObject) {

    if (dicomTag(element)) return getDicomElementText(element, dicomObject);

    if (element.getTagName().equals("block")) return getBlockText(element, dicomObject);

    StringBuffer sb = new StringBuffer();
    sb.append("<" + element.getTagName());
    NamedNodeMap attributes = element.getAttributes();
    Attr attr;
    for (int i = 0; i < attributes.getLength(); i++) {
      attr = (Attr) attributes.item(i);
      String attrValue = attr.getValue().trim();
      if (dicomTag(attrValue)) {
        attrValue = getDicomElementText(attrValue, dicomObject);
      }
      sb.append(" " + attr.getName() + "=\"" + attrValue + "\"");
    }
    sb.append(">");
    if (element.getTagName().equals("table")) sb.append(getTableText(element, dicomObject));
    else if (element.getTagName().equals("publication-date")) sb.append(StringUtil.getDate());
    else sb.append(getChildrenText(element, dicomObject));
    sb.append("</" + element.getTagName() + ">");
    return sb.toString();
  }
Beispiel #28
0
  /**
   * Copy in-scope namespace declarations of the decl node to the decl node itself so that this move
   * won't change the in-scope namespace bindings.
   */
  private void copyInscopeNSAttributes(Element e) {
    Element p = e;
    Set<String> inscopes = new HashSet<String>();
    while (true) {
      NamedNodeMap atts = p.getAttributes();
      for (int i = 0; i < atts.getLength(); i++) {
        Attr a = (Attr) atts.item(i);
        if (Constants.NS_XMLNS.equals(a.getNamespaceURI())) {
          String prefix;
          if (a.getName().indexOf(':') == -1) prefix = "";
          else prefix = a.getLocalName();

          if (inscopes.add(prefix) && p != e) {
            // if this is the first time we see this namespace bindings,
            // copy the declaration.
            // if p==decl, there's no need to. Note that
            // we want to add prefix to inscopes even if p==Decl

            e.setAttributeNodeNS((Attr) a.cloneNode(true));
          }
        }
      }

      if (p.getParentNode() instanceof Document) break;

      p = (Element) p.getParentNode();
    }

    if (!inscopes.contains("")) {
      // if the default namespace was undeclared in the context of decl,
      // it must be explicitly set to "" since the new environment might
      // have a different default namespace URI.
      e.setAttributeNS(Constants.NS_XMLNS, "xmlns", "");
    }
  }
Beispiel #29
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);
    }
  }
 protected void validateTranslatableString(Element element, Attr attr, boolean shouldTranslate) {
   if (!shouldTranslate) return;
   int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_NOT_EXTERNALIZED);
   if (severity == CompilerFlags.IGNORE) return;
   String value = attr.getValue();
   if (!value.startsWith("%")) { // $NON-NLS-1$
     report(
         NLS.bind(MDECoreMessages.Builders_Manifest_non_ext_attribute, attr.getName()),
         getLine(element, attr.getName()),
         severity,
         MDEMarkerFactory.P_UNTRANSLATED_NODE,
         element,
         attr.getName(),
         MDEMarkerFactory.CAT_NLS);
   } else if (fModel instanceof AbstractNLModel) {
     NLResourceHelper helper = ((AbstractNLModel) fModel).getNLResourceHelper();
     if (helper == null || !helper.resourceExists(value)) {
       report(
           NLS.bind(MDECoreMessages.Builders_Manifest_key_not_found, value.substring(1)),
           getLine(element, attr.getName()),
           severity,
           MDEMarkerFactory.CAT_NLS);
     }
   }
 }