Example #1
0
  /** Returns a sorted list of attributes. */
  protected Attr[] sortAttributes(NamedNodeMap attrs) {

    int len = (attrs != null) ? attrs.getLength() : 0;
    Attr array[] = new Attr[len];
    for (int i = 0; i < len; i++) {
      array[i] = (Attr) attrs.item(i);
    }
    for (int i = 0; i < len - 1; i++) {
      String name = array[i].getNodeName();
      int index = i;
      for (int j = i + 1; j < len; j++) {
        String curName = array[j].getNodeName();
        if (curName.compareTo(name) < 0) {
          name = curName;
          index = j;
        }
      }
      if (index != i) {
        Attr temp = array[i];
        array[i] = array[index];
        array[index] = temp;
      }
    }

    return (array);
  } // sortAttributes(NamedNodeMap):Attr[]
Example #2
0
 /**
  * Get a list of the names for all of the attributes for this node.
  *
  * @webref xml:method
  * @brief Returns a list of names of all attributes as an array
  */
 public String[] listAttributes() {
   NamedNodeMap nnm = node.getAttributes();
   String[] outgoing = new String[nnm.getLength()];
   for (int i = 0; i < outgoing.length; i++) {
     outgoing[i] = nnm.item(i).getNodeName();
   }
   return outgoing;
 }
 public String getAtributo(Node nodo, String nombreAtributo) {
   NamedNodeMap atts;
   atts = nodo.getAttributes();
   if (atts == null) return null;
   for (int i = 0; i < atts.getLength(); i++) {
     Node atributo = atts.item(i);
     if (atributo.getNodeName().equalsIgnoreCase(nombreAtributo)) return atributo.getNodeValue();
   }
   return null;
 }
Example #4
0
 public String getString(String name, String defaultValue) {
   NamedNodeMap attrs = node.getAttributes();
   if (attrs != null) {
     Node attr = attrs.getNamedItem(name);
     if (attr != null) {
       return attr.getNodeValue();
     }
   }
   return defaultValue;
 }
Example #5
0
    /** Возвращает имя метода. */
    public String getName() {

      /** Получаем атрибуты узла метода. */
      NamedNodeMap attributes = node.getAttributes();

      /** Получаем узел аттрибута. */
      Node nameAttrib = attributes.getNamedItem("name");

      /** Возвращаем значение атрибута. */
      return nameAttrib.getNodeValue();
    }
Example #6
0
 // dump and element
 public void dump(Element e) throws Exception {
   System.out.println("Element " + e.getNodeName());
   NamedNodeMap attrs = e.getAttributes();
   for (int i = 0; i < attrs.getLength(); i++) {
     Attr attr = (Attr) attrs.item(i);
     System.out.println("  " + attr.getName() + "=" + attr.getValue());
   }
   NodeList nodes = e.getChildNodes();
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     if (node instanceof Element) dump((Element) node);
   }
 }
Example #7
0
  /**
   * Retrieves default values from xml.
   *
   * @param list the configuration list
   */
  private static void parseDefaults(NodeList list) {
    for (int i = 0; i < list.getLength(); ++i) {
      NamedNodeMap mapping = list.item(i).getAttributes();
      String attribute = mapping.getNamedItem("attribute").getNodeValue();
      String value = mapping.getNamedItem("value").getNodeValue();

      try {
        Default field = Default.fromString(attribute);
        DEFAULTS.put(field, value);
      } catch (IllegalArgumentException exc) {
        logger.warn("Unrecognized default attribute: " + attribute);
      }
    }
  }
Example #8
0
 /**
  * Populates LOCALES list with contents of xml.
  *
  * @param list the configuration list
  */
 private static void parseLocales(NodeList list) {
   for (int i = 0; i < list.getLength(); ++i) {
     Node node = list.item(i);
     NamedNodeMap attributes = node.getAttributes();
     String label = ((Attr) attributes.getNamedItem("label")).getValue();
     String code = ((Attr) attributes.getNamedItem("isoCode")).getValue();
     String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue();
     try {
       LOCALES.add(new Locale(label, code, new URL(dictLocation)));
     } catch (MalformedURLException exc) {
       logger.warn(
           "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc);
     }
   }
 }
 /**
  * @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();
 }
  private void addRunConfigurationFromXMLTree(Element treeTop, String runManagerName) {
    NodeList list = treeTop.getChildNodes();

    for (int i = 0; i < list.getLength(); i++) {
      NamedNodeMap nodeMap = list.item(i).getAttributes();
      if (nodeMap != null && nodeMap.getNamedItem("name") != null) {
        if (!runManagerName.equals(nodeMap.getNamedItem("name").getNodeValue())) {
          continue;
        }
        NodeList configList = list.item(i).getChildNodes();
        for (int j = 0; j < configList.getLength(); j++) {
          NamedNodeMap configNodeMap = configList.item(j).getAttributes();
          if (configNodeMap != null
              && configNodeMap.getNamedItem("default") != null
              && configNodeMap.getNamedItem("default").getNodeValue() != null
              && configNodeMap.getNamedItem("default").getNodeValue().equals("false")) {
            try {
              runConfigurations.add(new ASIdeaRunConfiguration(configList.item(j)));
            } catch (ASExternalImporterException e) {
              // Ignore
            }
          }
        }
      }
    }
  }
Example #11
0
  public static void dumpElement(Element element, String indent) {
    System.out.println(indent + "Element: " + element.getNodeName());
    NamedNodeMap attributes = element.getAttributes();

    if ((attributes != null) && (attributes.getLength() > 0)) {
      System.out.println(indent + "Attributes:");
      for (int i = 0; i < attributes.getLength(); i++) {
        Node attr = attributes.item(i);
        System.out.println(indent + "  " + attr.getNodeName() + "=" + attr.getNodeValue());
      }
    }

    NodeList children = element.getChildNodes();

    for (int i = 0; i < children.getLength(); i++) {
      Node n = children.item(i);

      if (n instanceof Element) {
        dumpElement((Element) n, indent + "    ");
      } else if (n instanceof CharacterData) {
        System.out.println(indent + "    " + ((CharacterData) n).getData());
      }
    }
  }
Example #12
0
  /**
   * Metodo per la lettura e il salvataggio in DB dei dati relativi alla prima configurazione del
   * cinema multisala
   *
   * @throws Exception
   */
  public static void readInitialConfig() throws Exception {
    // Lettura del file config.xml
    MySQLAccess msa = new MySQLAccess();
    msa.readDB();
    Document config = loadDocument(CONFIG_FILE);

    // Creazione della lista di sale
    NodeList cinemaHalls = findCinemaHall(config);
    for (int i = 0; i < cinemaHalls.getLength(); i++) {
      NamedNodeMap attr = cinemaHalls.item(i).getAttributes();
      String[] s = attr.getNamedItem("id").toString().split("\"");
      // ID della sala i
      char id = s[1].toCharArray()[0];
      s = attr.getNamedItem("name").toString().split("\"");
      // Nome sala i
      String name = s[1];
      s = attr.getNamedItem("specialseat").toString().split("\"");
      // Numero posti speciali
      int specialSeats = Integer.parseInt(s[1]);
      NodeList rows = readRows((Element) cinemaHalls.item(i));
      // Numero file della sala i
      int n_rows = rows.getLength();

      // Numero posti totali
      int seats = 0;
      for (int j = 0; j < n_rows; j++) {
        // Numero posti della fila j
        int r_seats = Integer.parseInt(rows.item(j).getTextContent().toString().trim());
        seats += r_seats;
      }

      // Invoca l'inserimento in DB
      msa.insertCinemaHall(id, name, n_rows, seats, specialSeats);

      for (int j = 0; j < n_rows; j++) {
        NamedNodeMap r_attr = rows.item(j).getAttributes();
        s = r_attr.getNamedItem("number").toString().split("\"");
        int number = Integer.parseInt(s[1]);
        // Numero posti della fila j
        int r_seats = Integer.parseInt(rows.item(j).getTextContent().toString().trim());
        msa.insertRow(id, number, r_seats);
      }
    }
    msa.closeDB();
  }
 /**
  * @param list
  * @param parent
  * @exception NumberFormatException
  * @exception DicomException
  */
 void addAttributesFromNodeToList(AttributeList list, Node parent)
     throws NumberFormatException, DicomException {
   if (parent != null) {
     Node node = parent.getFirstChild();
     while (node != null) {
       String elementName = node.getNodeName();
       NamedNodeMap attributes = node.getAttributes();
       if (attributes != null) {
         Node vrNode = attributes.getNamedItem("vr");
         Node groupNode = attributes.getNamedItem("group");
         Node elementNode = attributes.getNamedItem("element");
         if (vrNode != null && groupNode != null && elementNode != null) {
           String vrString = vrNode.getNodeValue();
           String groupString = groupNode.getNodeValue();
           String elementString = elementNode.getNodeValue();
           if (vrString != null && groupString != null && elementString != null) {
             byte[] vr = vrString.getBytes();
             int group = Integer.parseInt(groupString, 16);
             int element = Integer.parseInt(elementString, 16);
             AttributeTag tag = new AttributeTag(group, element);
             if ((group % 2 == 0 && element == 0)
                 || (group == 0x0008 && element == 0x0001)
                 || (group == 0xfffc && element == 0xfffc)) {
               // System.err.println("ignoring group length or length to end or dataset trailing
               // padding "+tag);
             } else {
               if (vrString.equals("SQ")) {
                 SequenceAttribute a = new SequenceAttribute(tag);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("Item")) {
                       // should check item number, but ignore for now :(
                       // System.err.println("Adding item to sequence");
                       AttributeList itemList = new AttributeList();
                       addAttributesFromNodeToList(itemList, childNode);
                       a.addItem(itemList);
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Sequence Attribute is "+a);
                 list.put(tag, a);
               } else {
                 Attribute a = AttributeFactory.newAttribute(tag, vr);
                 // System.err.println("Created "+a);
                 if (node.hasChildNodes()) {
                   Node childNode = node.getFirstChild();
                   while (childNode != null) {
                     String childNodeName = childNode.getNodeName();
                     // System.err.println("childNodeName = "+childNodeName);
                     if (childNodeName != null && childNodeName.equals("value")) {
                       // should check value number, but ignore for now :(
                       String value = childNode.getTextContent();
                       // System.err.println("Value value = "+value);
                       if (value != null) {
                         value =
                             StringUtilities.removeLeadingOrTrailingWhitespaceOrISOControl(
                                 value); // just in case
                         a.addValue(value);
                       }
                     }
                     // else may be a #text element in between
                     childNode = childNode.getNextSibling();
                   }
                 }
                 // System.err.println("Attribute is "+a);
                 list.put(tag, a);
               }
             }
           }
         }
       }
       node = node.getNextSibling();
     }
   }
 }
Example #14
0
  public void serializeNode(Node node, Writer writer, String indentLevel) throws IOException {
    // Determine action based on node type
    switch (node.getNodeType()) {
      case Node.DOCUMENT_NODE:
        writer.write("<?xml version = '1.0'?>"); // "<xml version=\"1.0\">");
        writer.write(lineSeparator);
        // recurse on each child
        NodeList nodes = node.getChildNodes();
        if (nodes != null) {
          for (int i = 0; i < nodes.getLength(); i++) {
            serializeNode(nodes.item(i), writer, "");
          }
        }

        /*
         *  Document doc = (Document)node;
         *  serializeNode(doc.getDocumentElement( ), writer, " ");
         */
        break;
      case Node.ELEMENT_NODE:
        String name = node.getNodeName();
        writer.write(indentLevel + "<" + name);
        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
          Node current = attributes.item(i);
          writer.write(" " + current.getNodeName() + "=\"" + current.getNodeValue() + "\"");
        }
        writer.write(">");
        // recurse on each child
        NodeList children = node.getChildNodes();
        if (children != null) {
          if ((children.item(0) != null) && (children.item(0).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(lineSeparator);
          }
          for (int i = 0; i < children.getLength(); i++) {
            serializeNode(children.item(i), writer, indentLevel + indent);
          }
          if ((children.item(0) != null)
              && (children.item(children.getLength() - 1).getNodeType() == Node.ELEMENT_NODE)) {
            writer.write(indentLevel);
          }
        }
        writer.write("</" + name + ">");
        writer.write(lineSeparator);
        break;
      case Node.TEXT_NODE:
        writer.write(node.getNodeValue());
        break;
      case Node.CDATA_SECTION_NODE:
        writer.write("<![CDATA[" + node.getNodeValue() + "]]>");
        break;
      case Node.COMMENT_NODE:
        writer.write(indentLevel + "<!-- " + node.getNodeValue() + " -->");
        writer.write(lineSeparator);
        break;
      case Node.PROCESSING_INSTRUCTION_NODE:
        writer.write("<?" + node.getNodeName() + " " + node.getNodeValue() + "?>");
        writer.write(lineSeparator);
        break;
      case Node.ENTITY_REFERENCE_NODE:
        writer.write("&" + node.getNodeName() + ";");
        break;
      case Node.DOCUMENT_TYPE_NODE:
        DocumentType docType = (DocumentType) node;
        writer.write("<!DOCTYPE " + docType.getName());
        if (docType.getPublicId() != null) {
          System.out.print(" PUBLIC \"" + docType.getPublicId() + "\" ");
        } else {
          writer.write(" SYSTEM ");
        }
        writer.write("\"" + docType.getSystemId() + "\">");
        writer.write(lineSeparator);
        break;
    }
  }
  protected void locateModules() throws ASExternalImporterException {
    modules.clear();

    File f;
    String fDescription;
    // Both .ipr and modules.xml files have the same structure
    if (projectType == ProjectType.IPR) {
      f = iprFile;
      fDescription = "project";
    } else if (projectType == ProjectType.IDEA) {
      f = new File(ideaDir.getPath() + File.separator + "modules.xml");
      fDescription = "modules";
    } else {
      // Unreachable
      throw new ASExternalImporterException("Project type was not determined");
    }

    BufferedReader reader;
    try {
      reader = new BufferedReader(new FileReader(f));
    } catch (FileNotFoundException e) {
      // Unreachable
      throw new ASExternalImporterException("Cannot find " + fDescription + " file " + f.getPath());
    }

    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    Document doc;
    try {
      doc = fact.newDocumentBuilder().parse(new InputSource(reader));
    } catch (Exception e) {
      throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath());
    }

    Element el = doc.getDocumentElement();
    if (el == null) {
      throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath());
    }

    NodeList list = el.getChildNodes();
    Node moduleNode = null;

    for (int i = 0; i < list.getLength(); i++) {
      NamedNodeMap nodeMap = list.item(i).getAttributes();
      if (nodeMap != null && nodeMap.getNamedItem("name") != null) {
        if ("ProjectModuleManager".equals(nodeMap.getNamedItem("name").getNodeValue())) {
          moduleNode = list.item(i);
          break;
        }
      }
    }

    if (moduleNode == null) {
      throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath());
    }

    NodeList moduleNodeList = null;
    for (int i = 0; i < moduleNode.getChildNodes().getLength(); i++) {
      if ("modules".equals(moduleNode.getChildNodes().item(i).getNodeName())) {
        moduleNodeList = moduleNode.getChildNodes().item(i).getChildNodes();
        break;
      }
    }

    if (moduleNodeList == null) {
      throw new ASExternalImporterException("Corrupted " + fDescription + " file " + f.getPath());
    }

    for (int i = 0; i < moduleNodeList.getLength(); i++) {
      NamedNodeMap nodeMap = moduleNodeList.item(i).getAttributes();
      if (nodeMap != null && nodeMap.getNamedItem("filepath") != null) {
        modules.add(
            new ASIdeaModule(
                nodeMap
                    .getNamedItem("filepath")
                    .getNodeValue()
                    .replace("$PROJECT_DIR$", projectPath)));
      }
    }

    resolveModuleDependencies();
  }
Example #16
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;
    }
  }
Example #17
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());
    }
  }