XmlNode[] getAttributes() {
   NamedNodeMap attrs = this.dom.getAttributes();
   //    TODO    Or could make callers handle null?
   if (attrs == null) throw new IllegalStateException("Must be element.");
   XmlNode[] rv = new XmlNode[attrs.getLength()];
   for (int i = 0; i < attrs.getLength(); i++) {
     rv[i] = createImpl(attrs.item(i));
   }
   return rv;
 }
  void removeNamespace(Namespace namespace) {
    Namespace current = getNodeNamespace();

    //    Do not remove in-use namespace
    if (namespace.is(current)) return;
    NamedNodeMap attrs = this.dom.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
      XmlNode attr = XmlNode.createImpl(attrs.item(i));
      if (namespace.is(attr.getNodeNamespace())) return;
    }

    //    TODO    I must confess I am not sure I understand the spec fully.  See ECMA357 13.4.4.31
    String existingPrefix = getExistingPrefixFor(namespace);
    if (existingPrefix != null) {
      if (namespace.isUnspecifiedPrefix()) {
        //    we should remove any namespace with this URI from scope; we do this by declaring a
        // namespace with the same
        //    prefix as the existing prefix and setting its URI to the default namespace
        declareNamespace(existingPrefix, getDefaultNamespace().getUri());
      } else {
        if (existingPrefix.equals(namespace.getPrefix())) {
          declareNamespace(existingPrefix, getDefaultNamespace().getUri());
        }
      }
    } else {
      //    the argument namespace is not declared in this scope, so do nothing.
    }
  }
  /**
   * Counts the attributenode for an element (xmlns attributes ignored)
   *
   * @param attributesR attributesMap
   * @return number of attributes
   */
  private int countAttributes(NamedNodeMap attributesR) {
    int cntAttributes = 0;

    for (int i = 0; i < attributesR.getLength(); i++) {
      if (!attributesR.item(i).getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
        cntAttributes++;
      }
    }

    return cntAttributes;
  }
 protected Element copyElementToName(Element element, String tagName) {
   Element newElement = element.getOwnerDocument().createElement(tagName);
   NamedNodeMap attrs = element.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Node attribute = attrs.item(i);
     newElement.setAttribute(attribute.getNodeName(), attribute.getNodeValue());
   }
   for (int i = 0; i < element.getChildNodes().getLength(); i++) {
     newElement.appendChild(element.getChildNodes().item(i).cloneNode(true));
   }
   return newElement;
 }
Exemple #5
0
  public static Map<String, String> getAttrList(Node node) {
    Map<String, String> map = new HashMap<String, String>();

    NamedNodeMap list = node.getAttributes();
    if (list != null)
      for (int i = 0; i < list.getLength(); i++) {
        Attr attr = (Attr) list.item(i);
        map.put(attr.getName(), attr.getValue());
      }

    return map;
  }
 void invalidateNamespacePrefix() {
   if (!(dom instanceof Element)) throw new IllegalStateException();
   String prefix = this.dom.getPrefix();
   QName after = QName.create(this.dom.getNamespaceURI(), this.dom.getLocalName(), null);
   renameNode(after);
   NamedNodeMap attrs = this.dom.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     if (attrs.item(i).getPrefix().equals(prefix)) {
       createImpl(attrs.item(i))
           .renameNode(
               QName.create(attrs.item(i).getNamespaceURI(), attrs.item(i).getLocalName(), null));
     }
   }
 }
  public void validateContent(IProgressMonitor monitor) {
    Element element = getDocumentRoot();
    if (element == null) return;
    String elementName = element.getNodeName();
    if (!"plugin".equals(elementName)
        && !"fragment".equals(elementName)) { // $NON-NLS-1$ //$NON-NLS-2$
      reportIllegalElement(element, CompilerFlags.ERROR);
    } else {
      int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
      if (severity != CompilerFlags.IGNORE) {
        NamedNodeMap attrs = element.getAttributes();
        for (int i = 0; i < attrs.getLength(); i++) {
          reportUnusedAttribute(element, attrs.item(i).getNodeName(), severity);
        }
      }

      NodeList children = element.getChildNodes();
      for (int i = 0; i < children.getLength(); i++) {
        if (monitor.isCanceled()) break;
        Element child = (Element) children.item(i);
        String name = child.getNodeName();
        if (name.equals("extension")) { // $NON-NLS-1$
          validateExtension(child);
        } else if (name.equals("extension-point")) { // $NON-NLS-1$
          validateExtensionPoint(child);
        } else {
          if (!name.equals("runtime") && !name.equals("requires")) { // $NON-NLS-1$ //$NON-NLS-2$
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT);
            if (severity != CompilerFlags.IGNORE) reportIllegalElement(child, severity);
          } else {
            severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED);
            if (severity != CompilerFlags.IGNORE) reportUnusedElement(child, severity);
          }
        }
      }

      IExtensions extensions = fModel.getExtensions();
      if (extensions != null
          && extensions.getExtensions().length == 0
          && extensions.getExtensionPoints().length == 0)
        report(
            MDECoreMessages.Builders_Manifest_useless_file,
            -1,
            IMarker.SEVERITY_WARNING,
            MDEMarkerFactory.P_USELESS_FILE,
            MDEMarkerFactory.CAT_OTHER);
    }
  }
  protected static XmlConfigurator parse(Element root_element) throws java.io.IOException {
    XmlConfigurator configurator = null;
    final LinkedList<ProtocolConfiguration> prot_data = new LinkedList<ProtocolConfiguration>();

    /**
     * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty
     * amateurish... But it seems to work, and it is executed only on startup, so no perf loss on
     * the critical path. If somebody wants to improve this, please be my guest.
     */
    try {
      String root_name = root_element.getNodeName();
      if (!"config".equals(root_name.trim().toLowerCase()))
        throw new IOException("the configuration does not start with a <config> element");

      NodeList prots = root_element.getChildNodes();
      for (int i = 0; i < prots.getLength(); i++) {
        Node node = prots.item(i);
        if (node.getNodeType() != Node.ELEMENT_NODE) continue;

        Element tag = (Element) node;
        String protocol = tag.getTagName();
        Map<String, String> params = new HashMap<String, String>();

        NamedNodeMap attrs = tag.getAttributes();
        int attrLength = attrs.getLength();
        for (int a = 0; a < attrLength; a++) {
          Attr attr = (Attr) attrs.item(a);
          String name = attr.getName();
          String value = attr.getValue();
          params.put(name, value);
        }
        ProtocolConfiguration cfg = new ProtocolConfiguration(protocol, params);
        prot_data.add(cfg);
      }
      configurator = new XmlConfigurator(prot_data);
    } catch (Exception x) {
      if (x instanceof java.io.IOException) throw (java.io.IOException) x;
      else {
        IOException tmp = new IOException();
        tmp.initCause(x);
        throw tmp;
      }
    }
    return configurator;
  }
  // DOM input
  public void declareNamespace(Element element) {
    NamedNodeMap attrs = element.getAttributes();
    int size = attrs.getLength();

    for (int i = 0; i < size; i++) {
      Attr attr = (Attr) attrs.item(i);
      String qName = attr.getName();

      if (qName.startsWith("xmlns:")) {
        String uri = attr.getValue();
        String prefix = qName.substring("xmlns:".length());
        declareNamespace(prefix, uri);
      } else if (qName.startsWith("xmlns")) {
        String uri = attr.getValue();
        declareNamespace("", uri);
      }
    }
  }
 private void validateExistingExtensionAttributes(
     Element element, NamedNodeMap attrs, ISchemaElement schemaElement) {
   for (int i = 0; i < attrs.getLength(); i++) {
     Attr attr = (Attr) attrs.item(i);
     ISchemaAttribute attInfo = schemaElement.getAttribute(attr.getName());
     if (attInfo == null) {
       HashSet allowedElements = new HashSet();
       computeAllowedElements(schemaElement.getType(), allowedElements);
       if (allowedElements.contains(attr.getName())) {
         validateJavaAttribute(element, attr);
       } else {
         int flag = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ATTRIBUTE);
         if (flag != CompilerFlags.IGNORE) reportUnknownAttribute(element, attr.getName(), flag);
       }
     } else {
       validateExtensionAttribute(element, attr, attInfo);
     }
   }
 }
Exemple #11
0
  @Test
  public void testgetAttributesWithNamedNodeMap() throws Exception {
    //		builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml");
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(f);
    Element root = doc.getDocumentElement();
    //		System.out.println("* current impl:  " + doc.getClass().getName());

    // id, class
    Map<String, String> actualMap = new HashMap<String, String>();

    NodeList list = root.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node instanceof Element) {
        Element elem = (Element) node;
        if (elem.getTagName().equals("beans:bean")) {
          //					System.out.println("bean[" + elem.getAttribute("id") + "]");
          NamedNodeMap map = elem.getAttributes();
          String valueId = null;
          String valueClass = null;
          for (int x = 0; x < map.getLength(); x++) {
            Node attr = map.item(x);
            if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue();
            if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue();
          }
          if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass);
        }
      }
    }

    Map<String, String> expected = new HashMap<String, String>();
    expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager");
    expected.put(
        "daoAuthenticationProvider",
        "org.springframework.security.providers.dao.DaoAuthenticationProvider");
    expected.put(
        "loggerListener", "org.springframework.security.event.authentication.LoggerListener");
    Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap);
  }
 private void addNamespaces(Namespaces rv, Element element) {
   if (element == null) throw new RuntimeException("element must not be null");
   String myDefaultNamespace = toUri(element.lookupNamespaceURI(null));
   String parentDefaultNamespace = "";
   if (element.getParentNode() != null) {
     parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null));
   }
   if (!myDefaultNamespace.equals(parentDefaultNamespace)
       || !(element.getParentNode() instanceof Element)) {
     rv.declare(Namespace.create("", myDefaultNamespace));
   }
   NamedNodeMap attributes = element.getAttributes();
   for (int i = 0; i < attributes.getLength(); i++) {
     Attr attr = (Attr) attributes.item(i);
     if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) {
       rv.declare(Namespace.create(attr.getLocalName(), attr.getValue()));
     }
   }
 }
 /**
  * @param node
  * @param indent
  */
 public static String toString(Node node, int indent) {
   StringBuffer str = new StringBuffer();
   for (int i = 0; i < indent; ++i) str.append("    ");
   str.append(node);
   if (node.hasAttributes()) {
     NamedNodeMap attrs = node.getAttributes();
     for (int j = 0; j < attrs.getLength(); ++j) {
       Node attr = attrs.item(j);
       // str.append(toString(attr,indent+2));
       str.append(" ");
       str.append(attr);
     }
   }
   str.append("\n");
   ++indent;
   for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) {
     str.append(toString(child, indent));
     // str.append("\n");
   }
   return str.toString();
 }
 @Override
 protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
   BeanDefinitionBuilder builder =
       BeanDefinitionBuilder.genericBeanDefinition(SpringJolokiaConfigHolder.class);
   Map<String, String> config = new HashMap<String, String>();
   NamedNodeMap attrs = element.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Attr attr = (Attr) attrs.item(i);
     String name = attr.getName();
     if (skipMap.contains(name)) {
       continue;
     }
     config.put(name, attr.getValue());
   }
   builder.addPropertyValue("config", config);
   String order = element.getAttribute("order");
   if (StringUtils.hasText(order)) {
     builder.addPropertyValue("order", Integer.parseInt(order));
   }
   return builder.getBeanDefinition();
 }
Exemple #15
0
  private void processPanelLayout(Session session, Element element, HashMap additionalInformation) {

    String nodeName = element.getNodeName();
    String panelName = nodeName;

    NamedNodeMap tNodeMap = element.getAttributes();
    for (int i = 0; i < tNodeMap.getLength(); i++) {
      Node node = tNodeMap.item(i);
      String name = node.getNodeName();
      if (name.equals("dividerFractions")) {
        String value = node.getNodeValue();
        String[] tokens = value.split(",");
        double[] divs = new double[tokens.length];
        try {
          for (int j = 0; j < tokens.length; j++) {
            divs[j] = Double.parseDouble(tokens[j]);
          }
          session.setDividerFractions(divs);
        } catch (NumberFormatException e) {
          log.error("Error parsing divider locations", e);
        }
      }
    }
  }
Exemple #16
0
 private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception {
   Object object = null;
   currentType = null;
   currentNode = node;
   currentName = node.getNodeName();
   boolean isNull = false;
   NamedNodeMap attrs = node.getAttributes();
   String arrayType = null;
   for (int i = 0; i < attrs.getLength(); i++) {
     String nodeName = attrs.item(i).getNodeName();
     String nodeValue = attrs.item(i).getNodeValue();
     if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE))
       currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(
         NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE))
       arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString();
     else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null"))
       isNull = nodeValue.equals("true");
   }
   Class cls = null;
   if (currentType != null) cls = getXsdTypeClass(currentType);
   // Handle array, Vector, ArrayList, LinkedList, Hashtable,
   // Properties, and HashMap data types
   if ((cls != null)
       && ((cls == java.lang.reflect.Array.class)
           || (cls == Vector.class)
           || (cls == ArrayList.class)
           || (cls == LinkedList.class)
           || (cls == Hashtable.class)
           || (cls == Properties.class)
           || (cls == HashMap.class)
           || (cls == SortedMap.class))) {
     parentNode = currentNode;
     String name = node.getNodeName();
     // Handle arrays
     if (cls == java.lang.reflect.Array.class) {
       int a = arrayType.indexOf("[");
       int b = arrayType.indexOf("]");
       String s = arrayType.substring(a + 1, b);
       int arrayLen = Integer.valueOf(s).intValue();
       arrayType = arrayType.substring(0, a);
       // check if the array element is a standard Java class
       Class arrayClass = getXsdTypeClass(arrayType);
       // otherwise try to get the class of the bean
       if (arrayClass == null)
         arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType);
       object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen);
     } else {
       // Construct the list or map type
       Constructor ct = cls.getConstructor((Class[]) null);
       object = ct.newInstance((Object[]) null);
     }
     // deserialize the elements of the array, list, or map
     NodeList childNodes = node.getChildNodes();
     int arrayIndex = -1;
     Node childNode = null;
     Object nodeObj = null;
     for (int i = 0; i < childNodes.getLength(); i++) {
       childNode = childNodes.item(i);
       if (childNode.getNodeType() == Node.ELEMENT_NODE) {
         if ((cls == java.lang.reflect.Array.class)
             || (cls == Vector.class)
             || (cls == ArrayList.class)
             || (cls == LinkedList.class)) {
           nodeObj = deserialize(childNode, false, true);
           if (nodeObj != null) {
             if (cls == java.lang.reflect.Array.class)
               java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj);
             else ((List) object).add(nodeObj);
           }
         } else if ((cls == Hashtable.class)
             || (cls == Properties.class)
             || (cls == HashMap.class)
             || (cls == SortedMap.class)) {
           if (childNode.getLocalName().equals("item")) {
             NodeList htNodes = childNode.getChildNodes();
             if (htNodes.getLength() == 2) {
               Object hashKey = deserialize(htNodes.item(0), false, false);
               Object hashValue = deserialize(htNodes.item(1), false, true);
               ((Map) object).put(hashKey, hashValue);
             }
           }
         }
       }
     }
     setBeanProperty(name, object);
     // Handle everything else (primitives & POJOs)
   } else {
     // recurse on each of the child nodes
     NodeList childNodes = node.getChildNodes();
     if ((childNodes != null) && (childNodes.getLength() > 0)) {
       for (int i = 0; i < childNodes.getLength(); i++) {
         Node childNode = childNodes.item(i);
         if (childNode.getNodeType() == Node.ELEMENT_NODE) {
           if (currentType != null)
             createObject(
                 node,
                 currentName,
                 currentPackage,
                 currentType,
                 childNode.getNodeValue(),
                 setProperty);
           parentNode = node;
           object = deserialize(childNode, true, true);
         } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) {
           object =
               createObject(
                   node,
                   currentName,
                   currentPackage,
                   currentType,
                   childNode.getNodeValue(),
                   setProperty);
         }
         currentType = null;
       }
     } else {
       if (!isNull)
         object = createObject(node, currentName, currentPackage, currentType, null, setProperty);
     }
     if (node.getParentNode() != parentNode) {
       parentNode = node.getParentNode();
       if (popBean) {
         Object bean = popBeanOffStack();
         if (bean != null) object = bean;
       }
     }
   }
   return object;
 }
Exemple #17
0
 private Object createObject(
     Node node, String name, String classPackage, String type, String value, boolean setProperty) {
   Bean parentBean = null;
   if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek();
   Object object = null;
   // param is either an XSD type or a bean,
   // check if it can be converted to an XSD type
   XSDatatype dt = null;
   try {
     dt = DatatypeFactory.getTypeByName(type);
   } catch (DatatypeException dte) {
     // the type is not a valid XSD data type
   }
   // convert null value to default
   if ((dt != null) && (value == null)) {
     Class objType = dt.getJavaObjectType();
     if (objType == String.class) value = "";
     else if ((objType == java.math.BigInteger.class)
         || (objType == Long.class)
         || (objType == Integer.class)
         || (objType == Short.class)
         || (objType == Byte.class)) value = "0";
     else if ((objType == java.math.BigDecimal.class)
         || (objType == Double.class)
         || (objType == Float.class)) value = "0.0";
     else if (objType == Boolean.class) value = "false";
     else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate();
     else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime();
   }
   //  check whether the type was converted to an XSD datatype
   if ((dt != null) && dt.isValid(value, null)) {
     // create and return an XSD Java object (e.g. String, Integer, Boolean, etc)
     object = dt.createJavaObject(value, null);
     if (object instanceof java.util.Calendar) {
       // check that the object is truly a Calendar
       // because DatatypeFactory converts xsd:date
       // types to GregorianCalendar instead of Date.
       if (type.equals("date")) {
         java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd");
         try {
           object = df.parse(value);
         } catch (java.text.ParseException pe) {
           object = new java.util.Date();
         }
       }
     }
   } else {
     // Create a bean object
     if (topLevelBean == null) topLevelBean = parentBean;
     object = pushBeanOnStack(classPackage, type);
     // Check fields to see if this property is the 'value' for the object
     Field[] fields = object.getClass().getDeclaredFields();
     for (int i = 0; i < fields.length; i++) {
       if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) {
         try {
           StringBuffer fieldName = new StringBuffer(fields[i].getName());
           char c = fieldName.charAt(0);
           if (c >= 'a' && c <= 'z') {
             c += 'A' - 'a';
           }
           fieldName.setCharAt(0, c);
           fieldName.insert(0, "set");
           Method method =
               object
                   .getClass()
                   .getMethod(fieldName.toString(), new Class[] {fields[i].getType()});
           method.invoke(object, value);
           break;
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
     NamedNodeMap nodeAttrs = node.getAttributes();
     // iterate attributes and set field values for property attributes
     for (int i = 0; i < nodeAttrs.getLength(); i++) {
       String nodePrefix = nodeAttrs.item(i).getPrefix();
       if (nodePrefix.equals(nsPrefix)) {
         String nodeName = nodeAttrs.item(i).getLocalName();
         String nodeValue = nodeAttrs.item(i).getNodeValue();
         try {
           Field field = object.getClass().getDeclaredField(nodeName);
           if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) {
             StringBuffer fieldName = new StringBuffer(field.getName());
             char c = fieldName.charAt(0);
             if (c >= 'a' && c <= 'z') {
               c += 'A' - 'a';
             }
             fieldName.setCharAt(0, c);
             fieldName.insert(0, "set");
             Method method =
                 object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()});
             if (field.getType() == String.class) method.invoke(object, nodeValue);
             else if (field.getType() == Boolean.TYPE)
               method.invoke(object, StringUtils.strToBool(nodeValue, "true"));
             else if (field.getType() == Byte.TYPE)
               method.invoke(object, Byte.valueOf(nodeValue).byteValue());
             else if (field.getType() == Character.TYPE)
               method.invoke(object, Character.valueOf(nodeValue.charAt(0)));
             else if (field.getType() == Double.TYPE)
               method.invoke(object, Double.valueOf(nodeValue).doubleValue());
             else if (field.getType() == Float.TYPE)
               method.invoke(object, Float.valueOf(nodeValue).floatValue());
             else if (field.getType() == Integer.TYPE)
               method.invoke(object, Integer.valueOf(nodeValue).intValue());
             else if (field.getType() == Long.TYPE)
               method.invoke(object, Long.valueOf(nodeValue).longValue());
             else if (field.getType() == Short.TYPE)
               method.invoke(object, Short.valueOf(nodeValue).shortValue());
           }
         } catch (Exception e) {
           System.err.println(e.getMessage());
         }
       }
     }
   }
   if ((parentBean != null) && (setProperty)) {
     parentBean.setProperty(name, object);
   }
   return object;
 }
Exemple #18
0
  /**
   * Process a track element. This should return a single track, but could return multiple tracks
   * since the uniqueness of the track id is not enforced.
   *
   * @param session
   * @param element
   * @param additionalInformation
   * @return
   */
  private List<Track> processTrack(
      Session session, Element element, HashMap additionalInformation) {

    String id = getAttribute(element, SessionAttribute.ID.getText());

    // TODo -- put in utility method, extacts attributes from element **Definitely need to do this
    HashMap<String, String> tAttributes = new HashMap();
    HashMap<String, String> drAttributes = null;

    NamedNodeMap tNodeMap = element.getAttributes();
    for (int i = 0; i < tNodeMap.getLength(); i++) {
      Node node = tNodeMap.item(i);
      String value = node.getNodeValue();
      if (value != null && value.length() > 0) {
        tAttributes.put(node.getNodeName(), value);
      }
    }

    if (element.hasChildNodes()) {
      drAttributes = new HashMap();
      Node childNode = element.getFirstChild();
      Node sibNode = childNode.getNextSibling();
      String sibName = sibNode.getNodeName();
      if (sibName.equals(SessionElement.DATA_RANGE.getText())) {
        NamedNodeMap drNodeMap = sibNode.getAttributes();
        for (int i = 0; i < drNodeMap.getLength(); i++) {
          Node node = drNodeMap.item(i);
          String value = node.getNodeValue();
          if (value != null && value.length() > 0) {
            drAttributes.put(node.getNodeName(), value);
          }
        }
      }
    }

    // Get matching tracks.
    List<Track> matchedTracks = trackDictionary.get(id);

    if (matchedTracks == null) {
      log.info("Warning.  No tracks were found with id: " + id + " in session file");
    } else {
      for (final Track track : matchedTracks) {

        // Special case for sequence & gene tracks,  they need to be removed before being placed.
        if (version >= 4 && track == geneTrack || track == seqTrack) {
          igv.removeTracks(Arrays.asList(track));
        }

        track.restorePersistentState(tAttributes);
        if (drAttributes != null) {
          DataRange dr = track.getDataRange();
          dr.restorePersistentState(drAttributes);
          track.setDataRange(dr);
        }
      }
      trackDictionary.remove(id);
    }

    NodeList elements = element.getChildNodes();
    process(session, elements, additionalInformation);

    return matchedTracks;
  }
  /**
   * Constructs an attribute designator element from an existing XML block.
   *
   * @param element representing a DOM tree element.
   * @exception SAMLException if that there is an error in the sender or in the element definition.
   */
  public AttributeDesignator(Element element) throws SAMLException {
    // make sure that the input xml block is not null
    if (element == null) {
      SAMLUtilsCommon.debug.message("AttributeDesignator: Input is null.");
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    // Make sure this is an AttributeDesignator.
    String tag = null;
    tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("AttributeDesignator"))) {
      SAMLUtilsCommon.debug.message("AttributeDesignator: wrong input");
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput"));
    }

    // handle attributes
    int i = 0;
    NamedNodeMap atts = ((Node) element).getAttributes();
    int attrCount = atts.getLength();
    for (i = 0; i < attrCount; i++) {
      Node att = atts.item(i);
      if (att.getNodeType() == Node.ATTRIBUTE_NODE) {
        String attName = att.getLocalName();
        if (attName == null || attName.length() == 0) {
          if (SAMLUtilsCommon.debug.messageEnabled()) {
            SAMLUtilsCommon.debug.message(
                "AttributeDesignator:" + "Attribute Name is either null or empty.");
          }
          throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
        }
        if (attName.equals("AttributeName")) {
          _attributeName = ((Attr) att).getValue().trim();
        } else if (attName.equals("AttributeNamespace")) {
          _attributeNameSpace = ((Attr) att).getValue().trim();
        }
      }
    }
    // AttributeName is required
    if (_attributeName == null || _attributeName.length() == 0) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message(
            "AttributeDesignator: " + "AttributeName is required attribute");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute"));
    }

    // AttributeNamespace is required
    if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message(
            "AttributeDesignator: " + "AttributeNamespace is required attribute");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute"));
    }

    // handle the children of AttributeDesignator element
    // Since AttributeDesignator does not have any child element_node,
    // we will throw exception if we found any such child.
    NodeList nodes = element.getChildNodes();
    int nodeCount = nodes.getLength();
    if (nodeCount > 0) {
      for (i = 0; i < nodeCount; i++) {
        Node currentNode = nodes.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
          if (SAMLUtilsCommon.debug.messageEnabled()) {
            SAMLUtilsCommon.debug.message("AttributeDesignator: illegal input!");
          }
          throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput"));
        }
      }
    }
  }
Exemple #20
0
 public static int size(NamedNodeMap namedNodeMap) {
   return namedNodeMap.getLength();
 }
Exemple #21
0
  /**
   * Reads an XML element into a bean property by first locating the XML element corresponding to
   * this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readProperty(Object ob, PropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if the attribute name matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());
        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }

        return;
      }
    }

    int numNodes = nodes.getLength();

    Vector arrayBuild = null;

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // If this node isn't an element, skip it
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if the tag name matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the method used to set this property
        Method setter = desc.getWriteMethod();

        // If this object has no setter, don't bother writing it
        if (setter == null) continue;

        // Get the value of the property
        Object obValue = getObjectValue(desc, element);

        // 070201 MAW: Modified from change submitted by Steve Poulson
        if (setter.getParameterTypes()[0].isArray()) {
          if (arrayBuild == null) {
            arrayBuild = new Vector();
          }
          arrayBuild.addElement(obValue);

          // 070201 MAW: Go ahead and read through the rest of the nodes in case
          //             another one matches the array. This has the effect of skipping
          //             over the "return" statement down below
          continue;
        }

        if (obValue != null) {
          try {
            // Set the property value
            setter.invoke(ob, new Object[] {obValue});
          } catch (InvocationTargetException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          } catch (IllegalAccessException exc) {
            throw new IOException(
                "Error setting property " + desc.getName() + ": " + exc.toString());
          }
        }
        return;
      }
    }

    // If we build a vector of array members, convert the vector into
    // an array and save it in the property
    if (arrayBuild != null) {
      // Get the method used to set this property
      Method setter = desc.getWriteMethod();

      if (setter == null) return;

      Object[] obValues = (Object[]) Array.newInstance(desc.getPropertyType(), arrayBuild.size());

      arrayBuild.copyInto(obValues);

      try {
        setter.invoke(ob, new Object[] {obValues});
      } catch (InvocationTargetException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      } catch (IllegalAccessException exc) {
        throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
      }

      return;
    }
  }
  /**
   * Handle element node.
   *
   * @param received
   * @param source
   * @param validationContext
   */
  private void doElement(
      Node received,
      Node source,
      XmlMessageValidationContext validationContext,
      NamespaceContext namespaceContext,
      TestContext context) {

    doElementNameValidation(received, source);

    doElementNamespaceValidation(received, source);

    // check if element is ignored either by xpath or by ignore placeholder in source message
    if (XmlValidationUtils.isElementIgnored(
        source, received, validationContext.getIgnoreExpressions(), namespaceContext)) {
      return;
    }

    // work on attributes
    if (log.isDebugEnabled()) {
      log.debug("Validating attributes for element: " + received.getLocalName());
    }
    NamedNodeMap receivedAttr = received.getAttributes();
    NamedNodeMap sourceAttr = source.getAttributes();

    Assert.isTrue(
        countAttributes(receivedAttr) == countAttributes(sourceAttr),
        ValidationUtils.buildValueMismatchErrorMessage(
            "Number of attributes not equal for element '" + received.getLocalName() + "'",
            countAttributes(sourceAttr),
            countAttributes(receivedAttr)));

    for (int i = 0; i < receivedAttr.getLength(); i++) {
      doAttribute(
          received, receivedAttr.item(i), source, validationContext, namespaceContext, context);
    }

    // check if validation matcher on element is specified
    if (isValidationMatcherExpression(source)) {
      ValidationMatcherUtils.resolveValidationMatcher(
          source.getNodeName(),
          received.getFirstChild().getNodeValue().trim(),
          source.getFirstChild().getNodeValue().trim(),
          context);
      return;
    }

    // work on child nodes
    NodeList receivedChilds = received.getChildNodes();
    NodeList sourceChilds = source.getChildNodes();

    Assert.isTrue(
        receivedChilds.getLength() == sourceChilds.getLength(),
        ValidationUtils.buildValueMismatchErrorMessage(
            "Number of child elements not equal for element '" + received.getLocalName() + "'",
            sourceChilds.getLength(),
            receivedChilds.getLength()));

    for (int i = 0; i < receivedChilds.getLength(); i++) {
      this.validateXmlTree(
          receivedChilds.item(i),
          sourceChilds.item(i),
          validationContext,
          namespaceContext,
          context);
    }

    if (log.isDebugEnabled()) {
      log.debug(
          "Validation successful for element: "
              + received.getLocalName()
              + " ("
              + received.getNamespaceURI()
              + ")");
    }
  }
Exemple #23
0
  /**
   * Reads XML element(s) into an indexed bean property by first locating the XML element(s)
   * corresponding to this property.
   *
   * @param ob The bean whose property is being set
   * @param desc The property that will be set
   * @param nodes The list of XML items that may contain the property
   * @throws IOException If there is an error reading the document
   */
  public void readIndexedProperty(
      Object ob, IndexedPropertyDescriptor desc, NodeList nodes, NamedNodeMap attrs)
      throws IOException {
    // Create a vector to hold the property values
    Vector v = new Vector();

    int numAttrs = attrs.getLength();

    for (int i = 0; i < numAttrs; i++) {
      // See if this attribute matches the property name
      if (namesMatch(desc.getName(), attrs.item(i).getNodeName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, attrs.item(i).getNodeValue());

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    int numNodes = nodes.getLength();

    for (int i = 0; i < numNodes; i++) {
      Node node = nodes.item(i);

      // Skip non-element nodes
      if (!(node instanceof Element)) continue;

      Element element = (Element) node;

      // See if this element tag matches the property name
      if (namesMatch(desc.getName(), element.getTagName())) {
        // Get the property value
        Object obValue = getObjectValue(desc, element);

        if (obValue != null) {
          // Add the value to the list of values to be set
          v.addElement(obValue);
        }
      }
    }

    // Get the method used to set the property value
    Method setter = desc.getWriteMethod();

    // If this property has no setter, don't write it
    if (setter == null) return;

    // Create a new array of property values
    Object propArray = Array.newInstance(desc.getPropertyType().getComponentType(), v.size());

    // Copy the vector into the array
    v.copyInto((Object[]) propArray);

    try {
      // Store the array of property values
      setter.invoke(ob, new Object[] {propArray});
    } catch (InvocationTargetException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    } catch (IllegalAccessException exc) {
      throw new IOException("Error setting property " + desc.getName() + ": " + exc.toString());
    }
  }
  protected void validateExtensionPoint(Element element) {
    if (assertAttributeDefined(element, "id", CompilerFlags.ERROR)) { // $NON-NLS-1$
      Attr idAttr = element.getAttributeNode("id"); // $NON-NLS-1$
      double schemaVersion = getSchemaVersion();
      String message = null;
      if (schemaVersion < 3.2 && !IdUtil.isValidSimpleID(idAttr.getValue()))
        message = NLS.bind(MDECoreMessages.Builders_Manifest_simpleID, idAttr.getValue());
      else if (schemaVersion >= 3.2) {
        if (!IdUtil.isValidCompositeID(idAttr.getValue())) {
          message = NLS.bind(MDECoreMessages.Builders_Manifest_compositeID, idAttr.getValue());
        }
      }

      if (message != null)
        report(
            message,
            getLine(element, idAttr.getName()),
            CompilerFlags.WARNING,
            MDEMarkerFactory.CAT_OTHER);
    }

    assertAttributeDefined(element, "name", CompilerFlags.ERROR); // $NON-NLS-1$

    int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ATTRIBUTE);
    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
      Attr attr = (Attr) attrs.item(i);
      String name = attr.getName();
      if ("name".equals(name)) { // $NON-NLS-1$
        validateTranslatableString(element, attr, true);
      } else if (!"id".equals(name)
          && !"schema".equals(name)
          && severity != CompilerFlags.IGNORE) { // $NON-NLS-1$ //$NON-NLS-2$
        reportUnknownAttribute(element, name, severity);
      }
    }

    severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT);
    if (severity != CompilerFlags.IGNORE) {
      NodeList children = element.getChildNodes();
      for (int i = 0; i < children.getLength(); i++)
        reportIllegalElement((Element) children.item(i), severity);
    }

    // Validate the "schema" attribute of the extension point
    Attr attr = element.getAttributeNode(IMonitorExtensionPoint.P_SCHEMA);
    // Only validate the attribute if it was defined
    if (attr != null) {
      String schemaValue = attr.getValue();
      IResource res = getFile().getProject().findMember(schemaValue);
      String errorMessage = null;
      // Check to see if the value specified is an extension point schema and it exists
      if (!(res instanceof IFile
          && (res.getName().endsWith(".exsd")
              || //$NON-NLS-1$
              res.getName().endsWith(".mxsd")))) // $NON-NLS-1$
      errorMessage = MDECoreMessages.ExtensionsErrorReporter_InvalidSchema;
      // Report an error if one was found
      if (errorMessage != null) {
        severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_RESOURCE);
        if (severity != CompilerFlags.IGNORE)
          report(
              NLS.bind(errorMessage, schemaValue),
              getLine(element),
              severity,
              MDEMarkerFactory.CAT_OTHER);
      }
    }
  }
Exemple #25
0
  /**
   * Constructs an attribute element from an existing XML block.
   *
   * @param element representing a DOM tree element.
   * @exception SAMLException if there is an error in the sender or in the element definition.
   */
  public Attribute(Element element) throws SAMLException {
    // make sure that the input xml block is not null
    if (element == null) {
      SAMLUtilsCommon.debug.message("Attribute: Input is null.");
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
    }
    // Make sure this is an Attribute.
    String tag = null;
    tag = element.getLocalName();
    if ((tag == null) || (!tag.equals("Attribute"))) {
      SAMLUtilsCommon.debug.message("Attribute: wrong input");
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput"));
    }
    int i = 0;
    // handle attributes
    NamedNodeMap atts = element.getAttributes();
    int attrCount = atts.getLength();
    for (i = 0; i < attrCount; i++) {
      Node att = atts.item(i);
      if (att.getNodeType() == Node.ATTRIBUTE_NODE) {
        String attName = att.getLocalName();
        if (attName == null) {
          attName = att.getNodeName();
        }
        if (attName == null || attName.length() == 0) {
          if (SAMLUtilsCommon.debug.messageEnabled()) {
            SAMLUtilsCommon.debug.message("Attribute:" + "Attribute Name is either null or empty.");
          }
          continue;
          // throw new SAMLRequesterException(
          //  SAMLUtilsCommon.bundle.getString("nullInput"));
        }
        if (attName.equals("AttributeName")) {
          this._attributeName = ((Attr) att).getValue().trim();
        } else if (attName.equals("AttributeNamespace")) {
          this._attributeNameSpace = ((Attr) att).getValue().trim();
        }
      }
    }
    // AttributeName is required
    if (_attributeName == null || _attributeName.length() == 0) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("Attribute: " + "AttributeName is required attribute");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute"));
    }

    // AttributeNamespace is required
    if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message("Attribute: " + "AttributeNamespace is required attribute");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute"));
    }

    // handle the children of Attribute element
    NodeList nodes = element.getChildNodes();
    int nodeCount = nodes.getLength();
    if (nodeCount > 0) {
      for (i = 0; i < nodeCount; i++) {
        Node currentNode = nodes.item(i);
        if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
          String tagName = currentNode.getLocalName();
          String tagNS = currentNode.getNamespaceURI();
          if ((tagName == null) || tagName.length() == 0 || tagNS == null || tagNS.length() == 0) {
            if (SAMLUtilsCommon.debug.messageEnabled()) {
              SAMLUtilsCommon.debug.message(
                  "Attribute:"
                      + " The tag name or tag namespace of child"
                      + " element is either null or empty.");
            }
            throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput"));
          }
          if (tagName.equals("AttributeValue")
              && tagNS.equals(SAMLConstants.assertionSAMLNameSpaceURI)) {
            if (_attributeValue == null) {
              _attributeValue = new ArrayList();
            }
            if (!(_attributeValue.add((Element) currentNode))) {
              if (SAMLUtilsCommon.debug.messageEnabled()) {
                SAMLUtilsCommon.debug.message(
                    "Attribute: failed to " + "add to the attribute value list.");
              }
              throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError"));
            }
          } else {
            if (SAMLUtilsCommon.debug.messageEnabled()) {
              SAMLUtilsCommon.debug.message("Attribute:" + "wrong element:" + tagName);
            }
            throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput"));
          }
        } // end of if (currentNode.getNodeType() == Node.ELEMENT_NODE)
      } // end of for loop
    } // end of if (nodeCount > 0)

    if (_attributeValue == null || _attributeValue.isEmpty()) {
      if (SAMLUtilsCommon.debug.messageEnabled()) {
        SAMLUtilsCommon.debug.message(
            "Attribute: " + "should contain at least one AttributeValue.");
      }
      throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingElement"));
    }
  }
  /**
   * creates a new image
   *
   * @param svgHandle a svg handle
   * @param resourceId the id of the resource from which the image will be created
   */
  protected void createNewImage(SVGHandle svgHandle, String resourceId) {

    if (svgHandle != null && resourceId != null && !resourceId.equals("")) {

      Element resourceElement = null;

      resourceElement =
          svgHandle.getScrollPane().getSVGCanvas().getDocument().getElementById(resourceId);

      final String fresourceId = resourceId;

      if (resourceElement != null) {

        final SVGHandle fhandle = svgHandle;

        // creating the canvas and setting its properties
        final JSVGCanvas canvas =
            new JSVGCanvas() {

              @Override
              public void dispose() {

                removeKeyListener(listener);
                removeMouseMotionListener(listener);
                removeMouseListener(listener);
                disableInteractions = true;
                selectableText = false;
                userAgent = null;

                bridgeContext.dispose();
                super.dispose();
              }
            };

        // the element to be added
        Element elementToAdd = null;

        canvas.setDocumentState(JSVGComponent.ALWAYS_STATIC);
        canvas.setDisableInteractions(true);

        // creating the new document
        final String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
        final SVGDocument doc = (SVGDocument) resourceElement.getOwnerDocument().cloneNode(false);

        // creating the root element
        final Element root =
            (Element)
                doc.importNode(resourceElement.getOwnerDocument().getDocumentElement(), false);
        doc.appendChild(root);

        // removing all the attributes of the root element
        NamedNodeMap attributes = doc.getDocumentElement().getAttributes();

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

          if (attributes.item(i) != null) {

            doc.getDocumentElement().removeAttribute(attributes.item(i).getNodeName());
          }
        }

        // adding the new attributes for the root
        root.setAttributeNS(null, "width", imageSize.width + "");
        root.setAttributeNS(null, "height", imageSize.height + "");
        root.setAttributeNS(null, "viewBox", "0 0 " + imageSize.width + " " + imageSize.height);

        // the defs element that will contain the cloned resource node
        final Element defs = (Element) doc.importNode(resourceElement.getParentNode(), true);
        root.appendChild(defs);

        if (resourceElement.getNodeName().equals("linearGradient")
            || resourceElement.getNodeName().equals("radialGradient")
            || resourceElement.getNodeName().equals("pattern")) {

          // the rectangle that will be drawn
          final Element rect = doc.createElementNS(svgNS, "rect");
          rect.setAttributeNS(null, "x", "0");
          rect.setAttributeNS(null, "y", "0");
          rect.setAttributeNS(null, "width", imageSize.width + "");
          rect.setAttributeNS(null, "height", imageSize.height + "");

          elementToAdd = rect;

          // setting that the rectangle uses the resource
          String id = resourceElement.getAttribute("id");

          if (id == null) {

            id = "";
          }

          rect.setAttributeNS(null, "style", "fill:url(#" + id + ");");

          // getting the cloned resource node
          Node cur = null;
          Element clonedResourceElement = null;
          String id2 = "";

          for (cur = defs.getFirstChild(); cur != null; cur = cur.getNextSibling()) {

            if (cur instanceof Element) {

              id2 = ((Element) cur).getAttribute("id");

              if (id2 != null && id.equals(id2)) {

                clonedResourceElement = (Element) cur;
              }
            }
          }

          if (clonedResourceElement != null) {

            // getting the root element of the initial resource
            // element
            Element initialRoot = resourceElement.getOwnerDocument().getDocumentElement();

            // getting the width and height of the initial root
            // element
            double initialWidth = 0, initialHeight = 0;

            try {
              initialWidth =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "width"));
              initialHeight =
                  EditorToolkit.getPixelledNumber(initialRoot.getAttributeNS(null, "height"));
            } catch (DOMException ex) {
              ex.printStackTrace();
            }

            if (resourceElement.getNodeName().equals("linearGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double x1 = 0, y1 = 0, x2 = 0, y2 = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  x1 = Double.parseDouble(resourceElement.getAttributeNS(null, "x1"));
                  y1 = Double.parseDouble(resourceElement.getAttributeNS(null, "y1"));
                  x2 = Double.parseDouble(resourceElement.getAttributeNS(null, "x2"));
                  y2 = Double.parseDouble(resourceElement.getAttributeNS(null, "y2"));

                  x1 = x1 / initialWidth * imageSize.width;
                  y1 = y1 / initialHeight * imageSize.height;
                  x2 = x2 / initialWidth * imageSize.width;
                  y2 = y2 / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x1", format.format(x1));
                clonedResourceElement.setAttributeNS(null, "y1", format.format(y1));
                clonedResourceElement.setAttributeNS(null, "x2", format.format(x2));
                clonedResourceElement.setAttributeNS(null, "y2", format.format(y2));
              }

            } else if (resourceElement.getNodeName().equals("radialGradient")) {

              if (resourceElement.getAttributeNS(null, "gradientUnits").equals("userSpaceOnUse")) {

                double cx = 0, cy = 0, r = 0, fx = 0, fy = 0;

                // normalizing the values for the circle to fit
                // the rectangle
                try {
                  cx = Double.parseDouble(resourceElement.getAttributeNS(null, "cx"));
                  cy = Double.parseDouble(resourceElement.getAttributeNS(null, "cy"));
                  r = Double.parseDouble(resourceElement.getAttributeNS(null, "r"));
                  fx = Double.parseDouble(resourceElement.getAttributeNS(null, "fx"));
                  fy = Double.parseDouble(resourceElement.getAttributeNS(null, "fy"));

                  cx = cx / initialWidth * imageSize.width;
                  cy = cy / initialHeight * imageSize.height;

                  r =
                      r
                          / (Math.abs(
                              Math.sqrt(Math.pow(initialWidth, 2) + Math.pow(initialHeight, 2))))
                          * Math.abs(
                              Math.sqrt(
                                  Math.pow(imageSize.width, 2) + Math.pow(imageSize.width, 2)));

                  fx = fx / initialWidth * imageSize.width;
                  fy = fy / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "cx", format.format(cx));
                clonedResourceElement.setAttributeNS(null, "cy", format.format(cy));
                clonedResourceElement.setAttributeNS(null, "r", format.format(r));
                clonedResourceElement.setAttributeNS(null, "fx", format.format(fx));
                clonedResourceElement.setAttributeNS(null, "fy", format.format(fy));
              }

            } else if (resourceElement.getNodeName().equals("pattern")) {

              if (resourceElement.getAttributeNS(null, "patternUnits").equals("userSpaceOnUse")) {

                double x = 0, y = 0, w = 0, h = 0;

                // normalizing the values for the vector to fit
                // the rectangle
                try {
                  String xString = resourceElement.getAttributeNS(null, "x");
                  if (!xString.equals("")) {
                    x = Double.parseDouble(xString);
                  }
                  String yString = resourceElement.getAttributeNS(null, "y");
                  if (!yString.equals("")) {
                    y = Double.parseDouble(yString);
                  }
                  String wString = resourceElement.getAttributeNS(null, "w");
                  if (!wString.equals("")) {
                    w = Double.parseDouble(wString);
                  }
                  String hString = resourceElement.getAttributeNS(null, "h");
                  if (!hString.equals("")) {
                    h = Double.parseDouble(hString);
                  }

                  x = x / initialWidth * imageSize.width;
                  y = y / initialHeight * imageSize.height;
                  w = w / initialWidth * imageSize.width;
                  h = h / initialHeight * imageSize.height;
                } catch (NumberFormatException | DOMException ex) {
                  ex.printStackTrace();
                }

                clonedResourceElement.setAttributeNS(null, "x", format.format(x));
                clonedResourceElement.setAttributeNS(null, "y", format.format(y));
                clonedResourceElement.setAttributeNS(null, "width", format.format(w));
                clonedResourceElement.setAttributeNS(null, "height", format.format(h));
              }
            }
          }

        } else if (resourceElement.getNodeName().equals("marker")) {

          // the line that will be drawn
          final Element line = doc.createElementNS(svgNS, "line");
          line.setAttributeNS(null, "x1", (((double) imageSize.width) / 2) + "");
          line.setAttributeNS(null, "y1", (((double) imageSize.height) / 2) + "");
          line.setAttributeNS(null, "x2", ((double) imageSize.width / 2) + "");
          line.setAttributeNS(null, "y2", imageSize.height + "");

          elementToAdd = line;

          // setting that the line uses the resource
          String id = resourceElement.getAttribute("id");
          if (id == null) id = "";
          line.setAttributeNS(
              null, "style", "stroke:none;fill:none;marker-start:url(#" + id + ");");
        }

        root.appendChild(elementToAdd);

        // adding a rendering listener to the canvas
        GVTTreeRendererAdapter gVTTreeRendererAdapter =
            new GVTTreeRendererAdapter() {

              @Override
              public void gvtRenderingCompleted(GVTTreeRendererEvent evt) {

                Image bufferedImage = canvas.getOffScreen();

                if (bufferedImage != null) {

                  Graphics g = bufferedImage.getGraphics();
                  Color borderColor = MetalLookAndFeel.getSeparatorForeground();

                  g.setColor(borderColor);
                  g.drawRect(0, 0, imageSize.width - 1, imageSize.height - 1);
                }

                setImage(fhandle, fresourceId, bufferedImage);

                // refreshing the panels that have been created when no
                // image was available for them
                Image image = null;

                for (ResourceRepresentation resourceRepresentation :
                    new LinkedList<ResourceRepresentation>(resourceRepresentationList)) {

                  if (resourceRepresentation != null) {

                    resourceRepresentation.refreshRepresentation();
                    image = resourceRepresentation.getImage();

                    if (image != null) {

                      resourceRepresentationList.remove(resourceRepresentation);
                    }
                  }
                }

                canvas.removeGVTTreeRendererListener(this);
                canvas.stopProcessing();
                canvas.dispose();
              }
            };

        canvas.addGVTTreeRendererListener(gVTTreeRendererAdapter);

        // setting the document for the canvas
        canvas.setSVGDocument(doc);

        canvas.setBackground(Color.white);
        canvas.setBounds(1, 1, imageSize.width, imageSize.height);
      }
    }
  }