Exemple #1
0
  private LinkedHashMap[] obtenerMapeos(CliGol cliGol, NodeList variables, String[] excluye) {

    LinkedHashMap<String, Object> mapa = new LinkedHashMap<String, Object>();

    LinkedHashMap<String, String> puntos = new LinkedHashMap<String, String>();

    List<String> ex = Arrays.asList(excluye);

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

      String nom = variables.item(i).getNodeName();

      if (!ex.contains(nom)) {

        String golMapdijo = GolMap.xmlGol(nom);

        String val = null;
        if (golMapdijo != null) {
          val = buscaValEnCli(golMapdijo, cliGol);
          mapa.put(nom, val);

          puntos.put(nom, variables.item(i).getTextContent());
        }
      }
    }

    return new LinkedHashMap[] {mapa, puntos};
  }
  public ArrayList<String> parseXML() throws Exception {
    ArrayList<String> ret = new ArrayList<String>();

    handshake();

    URL url =
        new URL(
            "http://mangaonweb.com/page.do?cdn="
                + cdn
                + "&cpn=book.xml&crcod="
                + crcod
                + "&rid="
                + (int) (Math.random() * 10000));
    String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies);

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    InputSource is = new InputSource(new StringReader(page));
    Document d = builder.parse(is);
    Element doc = d.getDocumentElement();

    NodeList pages = doc.getElementsByTagName("page");
    total = pages.getLength();
    for (int i = 0; i < pages.getLength(); i++) {
      Element e = (Element) pages.item(i);
      ret.add(e.getAttribute("path"));
    }

    return (ret);
  }
Exemple #3
0
 public static void traverseAMLforObjectNames(
     HashMap partialMap, Node currentNode, HashMap ObjDef_LinkId, HashMap ModelId_ModelType) {
   if (currentNode.hasChildNodes()) {
     for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
       Node currentChild = currentNode.getChildNodes().item(i);
       if (currentChild.getNodeName().equals("Group")) {
         traverseAMLforObjectNames(partialMap, currentChild, ObjDef_LinkId, ModelId_ModelType);
       }
       if (currentChild.getNodeName().equals("Model")) {
         if (currentChild.hasAttributes()) {
           String mid = currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue();
           String type = currentChild.getAttributes().getNamedItem("Model.Type").getNodeValue();
           ModelId_ModelType.put(mid, type);
         }
         // traverseAMLforObjectNames(partialMap, currentChild,
         // ObjDef_LinkId);
       }
       if (currentChild.getNodeName().equals("ObjDef")) {
         String id = currentChild.getAttributes().getNamedItem("ObjDef.ID").getNodeValue();
         NodeList currentChildren = currentChild.getChildNodes();
         String ObjName = "";
         for (int k = 0; k < currentChildren.getLength(); k++) {
           Node Child = currentChildren.item(k);
           if (!Child.getNodeName().equals("AttrDef")) {
             continue;
           } else if (!Child.getAttributes()
               .getNamedItem("AttrDef.Type")
               .getNodeValue()
               .equals("AT_NAME")) {
             continue;
           } else if (Child.hasChildNodes()) {
             for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
               if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                 continue;
               } else {
                 ObjName = getTextContent(Child.getChildNodes().item(l));
                 ObjName = ObjName.replaceAll("\n", "\\\\n");
                 break;
               }
             }
           }
         }
         partialMap.put(id, ObjName);
         for (int j = 0; j < currentChild.getAttributes().getLength(); j++) {
           if (currentChild.getAttributes().item(j).getNodeName().equals("LinkedModels.IdRefs")) {
             String links =
                 currentChild.getAttributes().getNamedItem("LinkedModels.IdRefs").getNodeValue();
             /*
              * if (links.indexOf(" ") > -1) {
              * Message.add("yes, yes, yes"); links =
              * links.substring(0, links.indexOf(" ")); }
              */
             ObjDef_LinkId.put(id, links);
           }
         }
       }
     }
   }
 }
 private Element getElement(String eltName) {
   NodeList nodeList = docElt.getElementsByTagName(eltName);
   if (nodeList.getLength() != 0) {
     Node node = nodeList.item(0);
     if (node instanceof Element) return (Element) node;
   }
   return null;
 }
Exemple #5
0
 public static String[] allTextFromImmediateChildElements(
     Element parent, String tagName, boolean trim) throws DOMException {
   NodeList nl = immediateChildElementsByTagName(parent, tagName);
   int len = nl.getLength();
   String[] out = new String[len];
   for (int i = 0; i < len; ++i) out[i] = allText((Element) nl.item(i), trim);
   return out;
 }
Exemple #6
0
 /**
  * Honey, can you just check on the kids? Thanks.
  *
  * <p>Internal function; not included in reference.
  */
 protected void checkChildren() {
   if (children == null) {
     NodeList kids = node.getChildNodes();
     int childCount = kids.getLength();
     children = new XML[childCount];
     for (int i = 0; i < childCount; i++) {
       children[i] = new XML(this, kids.item(i));
     }
   }
 }
Exemple #7
0
 /** @deprecated use uniqueChild(Element elem, String childTagName) */
 public static Element uniqueChildByTagName(Element elem, String childTagName)
     throws DOMException {
   NodeList nl = elem.getElementsByTagName(childTagName);
   int len = nl.getLength();
   if (DEBUG)
     DebugUtils.myAssert(
         len <= 1,
         "There is more than one (" + len + ") child with tag name: " + childTagName + "!!!");
   return (len == 1 ? (Element) nl.item(0) : null);
 }
Exemple #8
0
  /**
   * ** Gets a virtual DBRecord from the specified remote service ** @param servReq The remote web
   * service ** @return The virtual DBRecord (cannot be saved or reloaded)
   */
  @SuppressWarnings("unchecked")
  public gDBR getVirtualDBRecord(final ServiceRequest servReq) throws DBException {
    String CMD_dbget = DBFactory.CMD_dbget;
    String TAG_Response = servReq.getTagResponse();
    String TAG_Record = DBFactory.TAG_Record;
    String ATTR_command = servReq.getAttrCommand();
    String ATTR_result = servReq.getAttrResult();

    /* send request / get response */
    Document xmlDoc = null;
    try {
      xmlDoc =
          servReq.sendRequest(
              CMD_dbget,
              new ServiceRequest.RequestBody() {
                public StringBuffer appendRequestBody(StringBuffer sb, int indent) {
                  return DBRecordKey.this.toRequestXML(sb, indent);
                }
              });
    } catch (IOException ioe) {
      Print.logException("Error", ioe);
      throw new DBException("Request read error", ioe);
    }

    /* parse 'GTSResponse' */
    Element gtsResponse = xmlDoc.getDocumentElement();
    if (!gtsResponse.getTagName().equalsIgnoreCase(TAG_Response)) {
      Print.logError("Request XML does not start with '%s'", TAG_Response);
      throw new DBException("Response XML does not begin eith '" + TAG_Response + "'");
    }

    /* request command/argument */
    String cmd = StringTools.trim(gtsResponse.getAttribute(ATTR_command));
    String result = StringTools.trim(gtsResponse.getAttribute(ATTR_result));
    if (StringTools.isBlank(result)) {
      result = StringTools.trim(gtsResponse.getAttribute("type"));
    }
    if (!result.equalsIgnoreCase("success")) {
      Print.logError("Response indicates failure");
      throw new DBException("Response does not indicate 'success'");
    }

    /* Record */
    NodeList rcdList = XMLTools.getChildElements(gtsResponse, TAG_Record);
    if (rcdList.getLength() <= 0) {
      Print.logError("No 'Record' tags");
      throw new DBException("GTSResponse does not contain any 'Record' tags");
    }
    Element rcdElem = (Element) rcdList.item(0);

    /* return DBRecord */
    gDBR dbr = (gDBR) DBFactory.parseXML_DBRecord(rcdElem);
    dbr.setVirtual(true);
    return dbr;
  }
Exemple #9
0
 /** @deprecated use allText(Element elem, boolean trim) */
 public static String allTextFromElement(Element elem, boolean trim) throws DOMException {
   StringBuffer textBuf = new StringBuffer();
   NodeList nl = elem.getChildNodes();
   for (int j = 0, len = nl.getLength(); j < len; ++j) {
     Node node = nl.item(j);
     if (node instanceof Text) // includes Text and CDATA!
     textBuf.append(node.getNodeValue());
   }
   String out = textBuf.toString();
   return (trim ? out.trim() : out);
 }
Exemple #10
0
 public String getProperty(String pPropertyName) {
   String propertyValue = null;
   NodeList nodeList = mConfigFileDocument.getElementsByTagName(pPropertyName);
   int nodeListLength = nodeList.getLength();
   if (nodeListLength > 0) {
     Node firstChildNode = nodeList.item(nodeListLength - 1).getFirstChild();
     if (null != firstChildNode) {
       propertyValue = firstChildNode.getNodeValue();
     }
   }
   return (propertyValue);
 }
Exemple #11
0
  private static String getTextContent(Node n) {
    NodeList nodeList = n.getChildNodes();
    String textContent = "";
    for (int j = 0; j < nodeList.getLength(); j++) {
      Node k = nodeList.item(j);
      if (k.getNodeType() == Node.TEXT_NODE) {
        textContent = k.getNodeValue();
        break;
      }
    }

    return textContent;
  }
 public void load(InputStream is) throws IOException, ParserConfigurationException, SAXException {
   doc = db.parse(is);
   docElt = doc.getDocumentElement();
   if (docElt.getTagName().equals(docElementName)) {
     NodeList nl = docElt.getElementsByTagName(trackElementName);
     for (int i = 0; i < nl.getLength(); i++) {
       Element elt = (Element) nl.item(i);
       Track track = new Track(elt);
       tracks.add(track);
       hash.put(track.getKey(), track);
     }
   }
 }
  @Override
  public VPackage parse() {

    logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath());

    long startParsing = System.currentTimeMillis();

    try {
      Document document = getDocument();
      Element root = document.getDocumentElement();

      _package = new VPackage(xmlFile);

      Node name = root.getElementsByTagName(EL_NAME).item(0);
      _package.setName(name.getTextContent());
      Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0);
      _package.setDescription(descr.getTextContent());

      NodeList list = root.getElementsByTagName(EL_CLASS);

      boolean initPainters = false;
      for (int i = 0; i < list.getLength(); i++) {
        PackageClass pc = parseClass((Element) list.item(i));
        if (pc.getPainterName() != null) {
          initPainters = true;
        }
      }

      if (initPainters) {
        _package.initPainters();
      }

      logger.info(
          "Parsing the package '{}' finished in {}ms.\n",
          _package.getName(),
          (System.currentTimeMillis() - startParsing));
    } catch (Exception e) {
      collector.collectDiagnostic(e.getMessage(), true);
      if (RuntimeProperties.isLogDebugEnabled()) {
        e.printStackTrace();
      }
    }

    try {
      checkProblems("Error parsing package file " + xmlFile.getName());
    } catch (Exception e) {
      return null;
    }

    return _package;
  }
Exemple #14
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);
      }
    }
  }
Exemple #15
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);
     }
   }
 }
Exemple #16
0
  /**
   * Searches the children of an element looking for a Text node. If it finds one, it returns it.
   *
   * @param element The element whose children will be searched
   * @return The text for the element, or null if there is none
   */
  public static String getElementString(Element element) {
    NodeList nodes = element.getChildNodes();

    int numNodes = nodes.getLength();

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

      if (node instanceof Text) {
        return ((Text) node).getData();
      }
    }

    return null;
  }
Exemple #17
0
  static {
    try {
      URL url = SpellCheckActivator.bundleContext.getBundle().getResource(RESOURCE_LOC);

      InputStream stream = url.openStream();

      if (stream == null) throw new IOException();

      // strict parsing options
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      factory.setValidating(false);
      factory.setIgnoringComments(true);
      factory.setIgnoringElementContentWhitespace(true);

      // parses configuration xml
      /*-
       * Warning: Felix is unable to import the com.sun.rowset.internal
       * package, meaning this can't use the XmlErrorHandler. This causes
       * a warning and a default handler to be attached. Otherwise this
       * should have: builder.setErrorHandler(new XmlErrorHandler());
       */
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document doc = builder.parse(stream);

      // iterates over nodes, parsing contents
      Node root = doc.getChildNodes().item(1);

      NodeList categories = root.getChildNodes();

      for (int i = 0; i < categories.getLength(); ++i) {
        Node node = categories.item(i);
        if (node.getNodeName().equals(NODE_DEFAULTS)) {
          parseDefaults(node.getChildNodes());
        } else if (node.getNodeName().equals(NODE_LOCALES)) {
          parseLocales(node.getChildNodes());
        } else {
          logger.warn("Unrecognized category: " + node.getNodeName());
        }
      }
    } catch (IOException exc) {
      logger.error("Unable to load spell checker parameters", exc);
    } catch (SAXException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    } catch (ParserConfigurationException exc) {
      logger.error("Unable to parse spell checker parameters", exc);
    }
  }
Exemple #18
0
  public void trim() {
    try {
      XPathFactory xpathFactory = XPathFactory.newInstance();
      XPathExpression xpathExp =
          xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
      NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(node, XPathConstants.NODESET);

      // Remove each empty text node from document.
      for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemple #19
0
  /**
   * Method that reads a XML-file, and returns a Model that contains the information
   *
   * @param file
   * @return
   * @return
   */
  public static Model readXML(String file) {
    // initialize table to be filled with content of XML file
    Model t = new Model();
    try {
      // Create file to be parsed by document parser
      File xmlfile = new File(file);
      // create parser
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      // parse the file
      Document parsedfile = parser.parse(xmlfile);
      // normalize the parsed file (make it more user-friendly)
      parsedfile.getDocumentElement().normalize();

      NodeList cells = parsedfile.getElementsByTagName("CELL");
      for (int i = 0; i < cells.getLength(); i++) {
        // Get cell at list index i
        Node currentcell = cells.item(i);
        // read the elements "location" attributes row/column
        if (Node.ELEMENT_NODE == currentcell.getNodeType()) {
          Element cellinfo = (Element) currentcell;
          // get the row number from node attribute
          int row = Integer.parseInt(cellinfo.getAttribute("row")) - 1;
          // get the column number from the node attribute
          int col = Integer.parseInt(cellinfo.getAttribute("column")) - 1;
          // get content from node
          String content = cellinfo.getTextContent();
          if (content != null) {
            content = content.replace("\n", "");
          }
          // Make the content an Integer (if it is a number), easier
          // for
          // using it later on
          // put content in table, with row/column inserted as x/y
          t.setContent(row, col, (String) content);
        }
      }

    } catch (ParserConfigurationException e) {
      System.out.println("Fileparser could not be made");
    } catch (IOException f) {
      System.out.println("File could not be parsed, did you enter the correct file name?");
    } catch (SAXException g) {
      System.out.println("Something went wrong in parsing the file");
    }
    return t;
  }
 /* return the value of the XML text node (never null) */
 protected static String GetNodeText(Node root) {
   StringBuffer sb = new StringBuffer();
   if (root != null) {
     NodeList list = root.getChildNodes();
     for (int i = 0; i < list.getLength(); i++) {
       Node n = list.item(i);
       if (n.getNodeType() == Node.CDATA_SECTION_NODE) { // CDATA Section
         sb.append(n.getNodeValue());
       } else if (n.getNodeType() == Node.TEXT_NODE) {
         sb.append(n.getNodeValue());
       } else {
         // Print.logWarn("Unrecognized node type: " + n.getNodeType());
       }
     }
   }
   return sb.toString();
 }
Exemple #21
0
  /**
   * Reads the children of an XML element and matches them to properties of a bean.
   *
   * @param ob The bean to receive the values
   * @param element The element the corresponds to the bean
   * @throws IOException If there is an error reading the document
   */
  public void readObject(Object ob, Element element) throws IOException {
    // If the object is null, skip the element
    if (ob == null) {
      return;
    }

    try {
      BeanInfo info = (BeanInfo) beanCache.get(ob.getClass());

      if (info == null) {
        // Get the bean info for the object
        info = Introspector.getBeanInfo(ob.getClass(), Object.class);

        beanCache.put(ob.getClass(), info);
      }

      // Get the object's properties
      PropertyDescriptor[] props = info.getPropertyDescriptors();

      // Get the attributes of the node
      NamedNodeMap attrs = element.getAttributes();

      // Get the children of the XML element
      NodeList nodes = element.getChildNodes();

      int numNodes = nodes.getLength();

      for (int i = 0; i < props.length; i++) {
        // Treat indexed properties a little differently
        if (props[i] instanceof IndexedPropertyDescriptor) {
          readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs);
        } else {
          readProperty(ob, props[i], nodes, attrs);
        }
      }
    } catch (IntrospectionException exc) {
      throw new IOException(
          "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString());
    }
  }
Exemple #22
0
  /**
   * Examine the areaspec and determine the number and position of callouts.
   *
   * <p>The <code><a href="http://docbook.org/tdg/html/areaspec.html">areaspecNodeSet</a></code> is
   * examined and a sorted list of the callouts is constructed.
   *
   * <p>This data structure is used to augment the result tree fragment with callout bullets.
   *
   * @param areaspecNodeSet The source document &lt;areaspec&gt; element.
   */
  public void setupCallouts(NodeList areaspecNodeList) {
    callout = new Callout[10];
    calloutCount = 0;
    calloutPos = 0;
    lineNumber = 1;
    colNumber = 1;

    // First we walk through the areaspec to calculate the position
    // of the callouts
    //  <areaspec>
    //  <areaset id="ex.plco.const" coords="">
    //    <area id="ex.plco.c1" coords="4"/>
    //    <area id="ex.plco.c2" coords="8"/>
    //  </areaset>
    //  <area id="ex.plco.ret" coords="12"/>
    //  <area id="ex.plco.dest" coords="12"/>
    //  </areaspec>
    int pos = 0;
    int coNum = 0;
    boolean inAreaSet = false;
    Node areaspec = areaspecNodeList.item(0);
    NodeList children = areaspec.getChildNodes();

    for (int count = 0; count < children.getLength(); count++) {
      Node node = children.item(count);
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNodeName().equalsIgnoreCase("areaset")) {
          coNum++;
          NodeList areas = node.getChildNodes();
          for (int acount = 0; acount < areas.getLength(); acount++) {
            Node area = areas.item(acount);
            if (area.getNodeType() == Node.ELEMENT_NODE) {
              if (area.getNodeName().equalsIgnoreCase("area")) {
                addCallout(coNum, area, defaultColumn);
              } else {
                System.out.println("Unexpected element in areaset: " + area.getNodeName());
              }
            }
          }
        } else if (node.getNodeName().equalsIgnoreCase("area")) {
          coNum++;
          addCallout(coNum, node, defaultColumn);
        } else {
          System.out.println("Unexpected element in areaspec: " + node.getNodeName());
        }
      }
    }

    // Now sort them
    java.util.Arrays.sort(callout, 0, calloutCount);
  }
Exemple #23
0
 public static EPCResult traverseAML(
     EPCResult partialResult,
     Node currentNode,
     Object parent,
     HashMap ObjDef_Name,
     HashMap ObjDef_LinkId,
     HashMap modelid_net,
     HashMap function_LinkId)
     throws Exception {
   if (currentNode.hasChildNodes()) {
     for (int i = 0; i < currentNode.getChildNodes().getLength(); i++) {
       Node currentChild = currentNode.getChildNodes().item(i);
       if (currentChild.getNodeName().equals("Group")) {
         String id = currentChild.getAttributes().getNamedItem("Group.ID").getNodeValue();
         String GroupName = "";
         if (currentChild.hasChildNodes()) {
           NodeList currentChildren = currentChild.getChildNodes();
           for (int j = 0; j < currentChildren.getLength(); j++) {
             Node Child = currentChildren.item(j);
             if (!(Child.getNodeName().equals("AttrDef"))) {
               continue;
             }
             if (Child.getAttributes()
                 .getNamedItem("AttrDef.Type")
                 .getNodeValue()
                 .equals("AT_NAME")) {
               if (Child.hasChildNodes()) {
                 for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
                   if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                     continue;
                   } else {
                     GroupName = getTextContent(Child.getChildNodes().item(l));
                   }
                 }
                 break;
               }
             }
           }
           if (GroupName.equals("")) {
             GroupName = id;
           }
         }
         ModelHierarchyDirectory dir = new ModelHierarchyDirectory(id, GroupName);
         partialResult.addInHierarchy(dir, parent, GroupName);
         partialResult =
             traverseAML(
                 partialResult,
                 currentChild,
                 dir,
                 ObjDef_Name,
                 ObjDef_LinkId,
                 modelid_net,
                 function_LinkId);
       }
       if (currentChild.getNodeName().equals("Model")
           && currentChild
               .getAttributes()
               .getNamedItem("Model.Type")
               .getNodeValue()
               .equals("MT_EEPC")) {
         String ModelName = "gaga";
         if (currentChild.hasChildNodes()) {
           NodeList currentChildren = currentChild.getChildNodes();
           for (int j = 0; j < currentChildren.getLength(); j++) {
             Node Child = currentChildren.item(j);
             if (!(Child.getNodeName().equals("AttrDef"))) {
               continue;
             }
             if (Child.getAttributes()
                 .getNamedItem("AttrDef.Type")
                 .getNodeValue()
                 .equals("AT_NAME")) {
               if (Child.hasChildNodes()) {
                 for (int l = 0; l < Child.getChildNodes().getLength(); l++) {
                   if (!(Child.getChildNodes().item(l).getNodeName().equals("AttrValue"))) {
                     continue;
                   } else {
                     ModelName = getTextContent(Child.getChildNodes().item(l));
                   }
                 }
               }
               break;
             }
           }
         }
         try {
           ModelName = ModelName.replaceAll("\n", " ");
           EPC net = read(currentChild, ObjDef_Name, ObjDef_LinkId, function_LinkId, ModelName);
           partialResult.addInHierarchy(net, parent, ModelName);
           modelid_net.put(
               currentChild.getAttributes().getNamedItem("Model.ID").getNodeValue(), net);
         } catch (Throwable x) {
           Message.add(x.getClass().getName());
           // throw new IOException(x.getMessage());
         }
       }
     }
   }
   return partialResult;
 }
  public void addPackageClass(PackageClass pClass) {

    Document doc;
    try {
      doc = getDocument();
    } catch (Exception e) {
      e.printStackTrace();
      return;
    }

    String name = pClass.getName();

    // check if such class exists and remove duplicates
    Element rootEl = doc.getDocumentElement();
    NodeList classEls = rootEl.getElementsByTagName(EL_CLASS);
    for (int i = 0; i < classEls.getLength(); i++) {
      Element nameEl = getElementByName((Element) classEls.item(i), EL_NAME);
      if (name.equals(nameEl.getTextContent())) {
        rootEl.removeChild(classEls.item(i));
      }
    }

    Element classNode = doc.createElement(EL_CLASS);
    doc.getDocumentElement().appendChild(classNode);
    classNode.setAttribute(ATR_TYPE, PackageClass.ComponentType.SCHEME.getXmlName());
    classNode.setAttribute(ATR_STATIC, "false");

    Element className = doc.createElement(EL_NAME);
    className.setTextContent(name);
    classNode.appendChild(className);

    Element desrc = doc.createElement(EL_DESCRIPTION);
    desrc.setTextContent(pClass.getDescription());
    classNode.appendChild(desrc);

    Element icon = doc.createElement(EL_ICON);
    icon.setTextContent(pClass.getIcon());
    classNode.appendChild(icon);

    // graphics
    classNode.appendChild(generateGraphicsNode(doc, pClass.getGraphics()));

    // ports
    List<Port> ports = pClass.getPorts();
    if (!ports.isEmpty()) {
      Element portsEl = doc.createElement(EL_PORTS);
      classNode.appendChild(portsEl);

      for (Port port : ports) {
        portsEl.appendChild(generatePortNode(doc, port));
      }
    }

    // fields
    Collection<ClassField> fields = pClass.getFields();
    if (!fields.isEmpty()) {
      Element fieldsEl = doc.createElement(EL_FIELDS);
      classNode.appendChild(fieldsEl);

      for (ClassField cf : fields) {
        fieldsEl.appendChild(generateFieldNode(doc, cf));
      }
    }

    // write
    try {
      writeDocument(doc, new FileOutputStream(xmlFile));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }
  }
  /* return reverse-geocode using nearest address */
  public ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr, boolean cache) {

    /* check for failover mode */
    if (this.isReverseGeocodeFailoverMode()) {
      ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider();
      return frgp.getReverseGeocode(gp, localeStr, cache);
    }

    /* URL */
    String url = this.getAddressReverseGeocodeURL(gp, localeStr);
    Print.logDebug("Google RG URL: " + url);
    // byte xmlBytes[] = HTMLTools.readPage(url);

    /* create XML document */
    Document xmlDoc = GetXMLDocument(url, this.getReverseGeocodeTimeout());
    if (xmlDoc == null) {
      return null;
    }

    /* vars */
    String errCode = null;
    String address = null;

    /* parse "xml" */
    Element kml = xmlDoc.getDocumentElement();
    if (kml.getTagName().equalsIgnoreCase(TAG_kml)) {
      NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response);
      for (int g = 0; (g < ResponseList.getLength()); g++) {
        Element response = (Element) ResponseList.item(g);
        NodeList responseNodes = response.getChildNodes();
        for (int n = 0; n < responseNodes.getLength(); n++) {
          Node responseNode = responseNodes.item(n);
          if (!(responseNode instanceof Element)) {
            continue;
          }
          Element responseElem = (Element) responseNode;
          String responseNodeName = responseElem.getNodeName();
          if (responseNodeName.equalsIgnoreCase(TAG_name)) {
            // <name>40.479581,-117.773438</name>
          } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) {
            // <Status> ... </Status>
            NodeList statusNodes = responseElem.getChildNodes();
            for (int st = 0; st < statusNodes.getLength(); st++) {
              Node statusNode = statusNodes.item(st);
              if (!(statusNode instanceof Element)) {
                continue;
              }
              Element statusElem = (Element) statusNode;
              String statusNodeName = statusElem.getNodeName();
              if (statusNodeName.equalsIgnoreCase(TAG_code)) {
                errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200"
                break; // we only care about the 'code'
              }
            }
          } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) {
            // <Placemark> ... </Placemark>
            String id = responseElem.getAttribute(ATTR_id);
            if ((id != null) && id.equals("p1")) {
              NodeList placemarkNodes = responseElem.getChildNodes();
              for (int pm = 0; pm < placemarkNodes.getLength(); pm++) {
                Node placemarkNode = placemarkNodes.item(pm);
                if (!(placemarkNode instanceof Element)) {
                  continue;
                }
                Element placemarkElem = (Element) placemarkNode;
                String placemarkNodeName = placemarkElem.getNodeName();
                if (placemarkNodeName.equalsIgnoreCase(TAG_address)) {
                  address = GoogleGeocodeV2.GetNodeText(placemarkElem);
                  break; // we only care about the 'address'
                }
              }
            } else {
              // Print.logInfo("Skipping Placemark ID = %s", id);
            }
          }
        }
      }
    }

    /* create address */
    if (FAILOVER_DEBUG) {
      errCode = "620";
    } else if (!StringTools.isBlank(address)) {
      // address found
      ReverseGeocode rg = new ReverseGeocode();
      rg.setFullAddress(address);
      return rg;
    }

    /* check for Google reverse-geocode limit exceeded */
    if ((errCode != null) && errCode.equals("620")) {
      Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!");
      if (this.hasFailoverReverseGeocodeProvider()) {
        this.startReverseGeocodeFailoverMode();
        ReverseGeocodeProvider frgp = this.getFailoverReverseGeocodeProvider();
        Print.logWarn("Failing over to '" + frgp.getName() + "'");
        return frgp.getReverseGeocode(gp, localeStr, cache);
      }
    }

    /* no reverse-geocode available */
    return null;
  }
  // http://code.google.com/apis/maps/documentation/geocoding/index.html
  public GeoPoint getGeocode(String address, String country) {

    /* URL */
    String url = this.getGeoPointGeocodeURL(address, country);
    Print.logDebug("Google GC URL: " + url);

    /* create XML document */
    Document xmlDoc = GetXMLDocument(url, this.getGeocodeTimeout());
    if (xmlDoc == null) {
      return null;
    }

    /* vars */
    String errCode = null;
    GeoPoint geoPoint = null;

    /* parse "xml" */
    Element kml = xmlDoc.getDocumentElement();
    if (kml.getTagName().equalsIgnoreCase(TAG_kml)) {
      NodeList ResponseList = XMLTools.getChildElements(kml, TAG_Response);
      for (int g = 0; (g < ResponseList.getLength()); g++) {
        Element response = (Element) ResponseList.item(g);
        NodeList responseNodes = response.getChildNodes();
        for (int n = 0; n < responseNodes.getLength(); n++) {
          Node responseNode = responseNodes.item(n);
          if (!(responseNode instanceof Element)) {
            continue;
          }
          Element responseElem = (Element) responseNode;
          String responseNodeName = responseElem.getNodeName();
          if (responseNodeName.equalsIgnoreCase(TAG_name)) {
            // <name>1600 Amphitheatre Parkway, Mountain View, CA</name>
          } else if (responseNodeName.equalsIgnoreCase(TAG_Status)) {
            // <Status> ... </Status>
            NodeList statusNodes = responseElem.getChildNodes();
            for (int st = 0; st < statusNodes.getLength(); st++) {
              Node statusNode = statusNodes.item(st);
              if (!(statusNode instanceof Element)) {
                continue;
              }
              Element statusElem = (Element) statusNode;
              String statusNodeName = statusElem.getNodeName();
              if (statusNodeName.equalsIgnoreCase(TAG_code)) {
                errCode = StringTools.trim(GoogleGeocodeV2.GetNodeText(statusElem)); // expect "200"
                break; // we only care about the 'code'
              }
            }
          } else if (responseNodeName.equalsIgnoreCase(TAG_Placemark)) {
            // <Placemark> ... </Placemark>
            String id = responseElem.getAttribute(ATTR_id);
            if ((id != null) && id.equals("p1")) {
              NodeList placemarkNodes = responseElem.getChildNodes();
              for (int pm = 0; (geoPoint == null) && (pm < placemarkNodes.getLength()); pm++) {
                Node placemarkNode = placemarkNodes.item(pm);
                if (!(placemarkNode instanceof Element)) {
                  continue;
                }
                Element placemarkElem = (Element) placemarkNode;
                String placemarkNodeName = placemarkElem.getNodeName();
                if (placemarkNodeName.equalsIgnoreCase(TAG_Point)) {
                  NodeList pointNodes = placemarkElem.getChildNodes();
                  for (int ptn = 0; (geoPoint == null) && (ptn < pointNodes.getLength()); ptn++) {
                    Node pointNode = pointNodes.item(ptn);
                    if (!(pointNode instanceof Element)) {
                      continue;
                    }
                    Element pointElem = (Element) pointNode;
                    String pointNodeName = pointElem.getNodeName();
                    if (pointNodeName.equalsIgnoreCase(TAG_coordinates)) {
                      String ll[] = StringTools.split(GoogleGeocodeV2.GetNodeText(pointElem), ',');
                      if (ll.length >= 2) {
                        double lon = StringTools.parseDouble(ll[0], 0.0); // longitude is first
                        double lat = StringTools.parseDouble(ll[1], 0.0);
                        if (GeoPoint.isValid(lat, lon)) {
                          geoPoint = new GeoPoint(lat, lon);
                          break; // we only care about the 'GeoPoint'
                        }
                      }
                    }
                  }
                }
              }
            } else {
              // Print.logInfo("Skipping Placemark ID = %s", id);
            }
          }
        }
      }
    }

    /* create address */
    if (geoPoint != null) {
      // GeoPoint found
      return geoPoint;
    }

    /* check for Google reverse-geocode limit exceeded */
    if ((errCode != null) && errCode.equals("620")) {
      Print.logError("!!!! Google Reverse-Geocode Limit Exceeded [Error 620] !!!!");
    }

    /* no reverse-geocode available */
    return null;
  }
  protected void init(Element root) {
    NodeList children = root.getChildNodes();

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

      if (child.getNodeName().equals("meta")) {
        Element meta = (Element) child;
        String value = XMLUtil.getText(meta);
        this.metaAttributes.put(meta.getAttribute("name"), value);
      }
    }

    // handle registers - OPTIONAL
    Element r = XMLUtil.getChildElement(root, "registers");

    if (r != null) {
      List registers = XMLUtil.getChildElements(r, "register");

      for (int i = 0; i < registers.size(); i++) {
        Element register = (Element) registers.get(i);
        RegisterDescriptor registerDescriptor =
            DescriptorFactory.getFactory().createRegisterDescriptor(register);
        registerDescriptor.setParent(this);
        this.registers.add(registerDescriptor);
      }
    }

    // handle global-conditions - OPTIONAL
    Element globalConditionsElement = XMLUtil.getChildElement(root, "global-conditions");

    if (globalConditionsElement != null) {
      Element globalConditions = XMLUtil.getChildElement(globalConditionsElement, "conditions");

      ConditionsDescriptor conditionsDescriptor =
          DescriptorFactory.getFactory().createConditionsDescriptor(globalConditions);
      conditionsDescriptor.setParent(this);
      this.globalConditions = conditionsDescriptor;
    }

    // handle initial-steps - REQUIRED
    Element intialActionsElement = XMLUtil.getChildElement(root, "initial-actions");
    List initialActions = XMLUtil.getChildElements(intialActionsElement, "action");

    for (int i = 0; i < initialActions.size(); i++) {
      Element initialAction = (Element) initialActions.get(i);
      ActionDescriptor actionDescriptor =
          DescriptorFactory.getFactory().createActionDescriptor(initialAction);
      actionDescriptor.setParent(this);
      this.initialActions.add(actionDescriptor);
    }

    // handle global-actions - OPTIONAL
    Element globalActionsElement = XMLUtil.getChildElement(root, "global-actions");

    if (globalActionsElement != null) {
      List globalActions = XMLUtil.getChildElements(globalActionsElement, "action");

      for (int i = 0; i < globalActions.size(); i++) {
        Element globalAction = (Element) globalActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(globalAction);
        actionDescriptor.setParent(this);
        this.globalActions.add(actionDescriptor);
      }
    }

    // handle common-actions - OPTIONAL
    //   - Store actions in HashMap for now. When parsing Steps, we'll resolve
    //      any common actions into local references.
    Element commonActionsElement = XMLUtil.getChildElement(root, "common-actions");

    if (commonActionsElement != null) {
      List commonActions = XMLUtil.getChildElements(commonActionsElement, "action");

      for (int i = 0; i < commonActions.size(); i++) {
        Element commonAction = (Element) commonActions.get(i);
        ActionDescriptor actionDescriptor =
            DescriptorFactory.getFactory().createActionDescriptor(commonAction);
        actionDescriptor.setParent(this);
        addCommonAction(actionDescriptor);
      }
    }

    // handle timer-functions - OPTIONAL
    Element timerFunctionsElement = XMLUtil.getChildElement(root, "trigger-functions");

    if (timerFunctionsElement != null) {
      List timerFunctions = XMLUtil.getChildElements(timerFunctionsElement, "trigger-function");

      for (int i = 0; i < timerFunctions.size(); i++) {
        Element timerFunction = (Element) timerFunctions.get(i);
        Integer id = new Integer(timerFunction.getAttribute("id"));
        FunctionDescriptor function =
            DescriptorFactory.getFactory()
                .createFunctionDescriptor(XMLUtil.getChildElement(timerFunction, "function"));
        function.setParent(this);
        this.timerFunctions.put(id, function);
      }
    }

    // handle steps - REQUIRED
    Element stepsElement = XMLUtil.getChildElement(root, "steps");
    List steps = XMLUtil.getChildElements(stepsElement, "step");

    for (int i = 0; i < steps.size(); i++) {
      Element step = (Element) steps.get(i);
      StepDescriptor stepDescriptor =
          DescriptorFactory.getFactory().createStepDescriptor(step, this);
      this.steps.add(stepDescriptor);
    }

    // handle splits - OPTIONAL
    Element splitsElement = XMLUtil.getChildElement(root, "splits");

    if (splitsElement != null) {
      List split = XMLUtil.getChildElements(splitsElement, "split");

      for (int i = 0; i < split.size(); i++) {
        Element s = (Element) split.get(i);
        SplitDescriptor splitDescriptor = DescriptorFactory.getFactory().createSplitDescriptor(s);
        splitDescriptor.setParent(this);
        this.splits.add(splitDescriptor);
      }
    }

    // handle joins - OPTIONAL:
    Element joinsElement = XMLUtil.getChildElement(root, "joins");

    if (joinsElement != null) {
      List join = XMLUtil.getChildElements(joinsElement, "join");

      for (int i = 0; i < join.size(); i++) {
        Element s = (Element) join.get(i);
        JoinDescriptor joinDescriptor = DescriptorFactory.getFactory().createJoinDescriptor(s);
        joinDescriptor.setParent(this);
        this.joins.add(joinDescriptor);
      }
    }
  }
Exemple #28
0
  /**
   * ** Returns a ReverseGeocode instance containing address information ** @param gp The GeoPoint
   * ** @return The ReverseGeocode instance
   */
  private ReverseGeocode getAddressReverseGeocode(GeoPoint gp, String localeStr) {

    /* URL */
    String url = this.getAddressReverseGeocodeURL(gp);
    Print.logInfo("Address URL: " + url);

    /* create XML document */
    Document xmlDoc = GetXMLDocument(url);
    if (xmlDoc == null) {
      return null;
    }

    /* create ReverseGeocode response */
    Element reversegeocode = xmlDoc.getDocumentElement();
    if (!reversegeocode.getTagName().equalsIgnoreCase(TAG_reversegeocode)) {
      return null;
    }

    /* init */
    String address_val = null; // null address
    String house_val = null; // house number
    String road_val = null; // street name
    String city_val = null; // city name
    String county_val = null; // county name
    String state_val = null; // state/province
    String postcode_val = null; // postal code
    String country_name_val = null; // country name
    String country_code_val = null; // country code

    // full address
    NodeList resultList = XMLTools.getChildElements(reversegeocode, TAG_result);
    for (int r = 0; r < resultList.getLength(); r++) {
      Element result = (Element) resultList.item(r);
      // String osmType = XMLTools.getAttribute(result, ATTR_osm_type, null, false);
      address_val = XMLTools.getNodeText(result, " ", false);
      break; // only the first element
    }

    // address components
    NodeList addresspartsList = XMLTools.getChildElements(reversegeocode, TAG_addressparts);
    for (int a = 0; (a < addresspartsList.getLength()); a++) {
      Element addressparts = (Element) addresspartsList.item(a);
      NodeList addresspartsChildren = addressparts.getChildNodes();
      for (int ac = 0; ac < addresspartsChildren.getLength(); ac++) {
        Node child = addresspartsChildren.item(ac);
        if (!(child instanceof Element)) {
          continue;
        }
        Element elem = (Element) child;
        String elemName = elem.getNodeName();
        if (elemName.equalsIgnoreCase(TAG_house)) {
          house_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_tram)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_road)) {
          road_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_residential)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_village)) {
          // ignore
        } else if (elemName.equalsIgnoreCase(TAG_town)) {
          if (StringTools.isBlank(city_val)) {
            city_val = XMLTools.getNodeText(elem, " ", false);
          }
        } else if (elemName.equalsIgnoreCase(TAG_city)) {
          city_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_county)) {
          county_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_postcode)) {
          postcode_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_state)) {
          state_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_country)) {
          country_name_val = XMLTools.getNodeText(elem, " ", false);
        } else if (elemName.equalsIgnoreCase(TAG_country_code)) {
          country_code_val = StringTools.trim(XMLTools.getNodeText(elem, " ", false)).toUpperCase();
        } else {
          // elemName unrecognized
        }
      }
      break; // only the first element
    }

    /* populate ReverseGeocode instance */
    ReverseGeocode rg = new ReverseGeocode();
    StringBuffer addr = new StringBuffer();
    // house number /road
    if (!StringTools.isBlank(house_val)) {
      addr.append(house_val);
      if (!StringTools.isBlank(road_val)) {
        addr.append(" ");
        addr.append(road_val);
        rg.setStreetAddress(house_val + " " + road_val);
      } else {
        rg.setStreetAddress(house_val);
      }
    } else if (!StringTools.isBlank(road_val)) {
      addr.append(road_val);
      rg.setStreetAddress(road_val);
    }
    // city/county
    if (!StringTools.isBlank(city_val)) {
      if (addr.length() > 0) {
        addr.append(", ");
      }
      addr.append(city_val);
      rg.setCity(city_val);
    }
    if (!StringTools.isBlank(county_val)) {
      if (StringTools.isBlank(city_val)) {
        // "city" not provided, at least include the "county"
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append("[").append(county_val).append("]");
      }
      // rg.setCounty(county_val);
    }
    // state/province
    if (!StringTools.isBlank(state_val)) {
      if (addr.length() > 0) {
        addr.append(", ");
      }
      addr.append(state_val);
      rg.setStateProvince(state_val);
      if (!StringTools.isBlank(postcode_val)) {
        addr.append(" ").append(postcode_val);
        rg.setPostalCode(postcode_val);
      }
    } else {
      if (!StringTools.isBlank(postcode_val)) {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(postcode_val);
        rg.setPostalCode(postcode_val);
      }
    }
    // country
    if (!StringTools.isBlank(country_code_val)) {
      if (country_code_val.equalsIgnoreCase("US")) {
        // if (addr.length() > 0) { addr.append(", "); }
        // addr.append("USA");
      } else if (!StringTools.isBlank(country_name_val)) {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(country_name_val);
      } else {
        if (addr.length() > 0) {
          addr.append(", ");
        }
        addr.append(country_code_val);
      }
      rg.setCountryCode(country_code_val);
    }
    // full address
    rg.setFullAddress(addr.toString());

    return rg;
  }
Exemple #29
0
  private static void parseNet(
      Node node,
      EPC net,
      HashMap ObjDef_Name,
      HashMap ObjDef_LinkId,
      HashMap function_LinkId,
      String ModelName)
      throws Exception {
    HashMap mapping = new HashMap();

    // read all nodes
    NodeList nodes = node.getChildNodes();
    net.setIdentifier(ModelName);
    // Message.add("here I am still happy");
    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      if (!n.getNodeName().equals("ObjOcc")) {
        continue;
      }
      if (n.getAttributes().getNamedItem("SymbolNum") == null) {
        continue;
      }
      String symbolnum = n.getAttributes().getNamedItem("SymbolNum").getNodeValue();
      if (!(symbolnum.equals("ST_FUNC")
          || symbolnum.equals("ST_EV")
          || symbolnum.equals("ST_OPR_AND_1")
          || symbolnum.equals("ST_OPR_OR_1")
          || symbolnum.equals("ST_OPR_XOR_1"))) {
        continue;
      }

      String ObjDef = n.getAttributes().getNamedItem("ObjDef.IdRef").getNodeValue();
      String ownName = (String) ObjDef_Name.get(ObjDef);
      // Message.add("YES " +
      // n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue());
      String id = n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue();
      // Message.add(id + " " + ownName);
      if (ownName == null || ownName == "") {
        ownName = id.substring(7, 11);
      }
      if (symbolnum.equals("ST_FUNC")) {
        if (ObjDef_LinkId.containsKey(ObjDef)) {
          EPCSubstFunction sf =
              (EPCSubstFunction)
                  net.addFunction(
                      new EPCSubstFunction(new LogEvent(ownName, "unknown:normal"), net, null));
          sf.setIdentifier(ownName);
          mapping.put(id, sf);
          function_LinkId.put(sf, ObjDef_LinkId.get(ObjDef));
        } else {
          EPCFunction f =
              net.addFunction(new EPCFunction(new LogEvent(ownName, "unknown:normal"), net));
          f.setIdentifier(ownName);
          mapping.put(id, f);
        }
      } else if (symbolnum.equals("ST_EV")) {
        EPCEvent e = net.addEvent(new EPCEvent(ownName, net));
        e.setIdentifier(ownName);
        mapping.put(id, e);
      } else if (symbolnum.equals("ST_OPR_AND_1")) {
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.AND, net));
        mapping.put(id, c);
      } else if (symbolnum.equals("ST_OPR_OR_1")) {
        // EPCConnector c = net.addConnector(new
        // EPCConnector(EPCConnector.OR, net));
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.AND, net));
        mapping.put(id, c);
      } else if (symbolnum.equals("ST_OPR_XOR_1")) {
        EPCConnector c = net.addConnector(new EPCConnector(EPCConnector.XOR, net));
        mapping.put(id, c);
      }
    }

    for (int i = 0; i < nodes.getLength(); i++) {
      Node n = nodes.item(i);
      if (!n.getNodeName().equals("ObjOcc")) {
        continue;
      }
      if (n.getAttributes().getNamedItem("SymbolNum") == null) {
        continue;
      }
      String symbolnum = n.getAttributes().getNamedItem("SymbolNum").getNodeValue();
      if (!(symbolnum.equals("ST_FUNC")
          || symbolnum.equals("ST_EV")
          || symbolnum.equals("ST_OPR_AND_1")
          || symbolnum.equals("ST_OPR_OR_1")
          || symbolnum.equals("ST_OPR_XOR_1"))) {
        continue;
      }
      String source = n.getAttributes().getNamedItem("ObjOcc.ID").getNodeValue();
      if (n.hasChildNodes()) {
        for (int j = 0; j < n.getChildNodes().getLength(); j++) {
          if (n.getChildNodes().item(j).getNodeName().equals("CxnOcc")) {
            Node CxnOcc = n.getChildNodes().item(j);
            String dest = CxnOcc.getAttributes().getNamedItem("ToObjOcc.IdRef").getNodeValue();
            if (mapping.get(dest) == null) {
              continue;
            }
            if (net.addEdge((EPCObject) mapping.get(source), (EPCObject) mapping.get(dest))
                == null) {
              throw (new Exception(
                  "<html>Structural properties of EPCs are violated in input file.<br>"
                      + "The following edge could not be added:<br><br>"
                      + mapping.get(source).toString()
                      + " ==> "
                      + mapping.get(dest).toString()
                      + "<br><br>Import aborted.</html>"));
            }
          }
        }
      }
    }
  }
    private ClassGraphics parse(Element grNode /*, boolean isRelation*/) {
      ClassGraphics newGraphics = new ClassGraphics();
      newGraphics.setShowFields(Boolean.parseBoolean(grNode.getAttribute(ATR_SHOW_FIELDS)));
      // newGraphics.setRelation( isRelation );

      NodeList list = grNode.getChildNodes();
      for (int k = 0; k < list.getLength(); k++) {
        if (list.item(k).getNodeType() != Node.ELEMENT_NODE) continue;
        Element node = (Element) list.item(k);
        String nodeName = node.getNodeName();

        Shape shape = null;
        if (EL_BOUNDS.equals(nodeName)) {
          Dim dim = getDim(node);
          newGraphics.setBounds(dim.x, dim.y, dim.width, dim.height);
          continue;
        } else if (EL_LINE.equals(nodeName)) {

          shape = makeLine(node, newGraphics);

        } else if (EL_RECT.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Rect(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_OVAL.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          shape =
              new Oval(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_ARC.equals(nodeName)) {

          Dim dim = getDim(node);
          Lineprops lp = getLineProps(node);
          int startAngle = Integer.parseInt(node.getAttribute(ATR_START_ANGLE));
          int arcAngle = Integer.parseInt(node.getAttribute(ATR_ARC_ANGLE));
          shape =
              new Arc(
                  dim.x,
                  dim.y,
                  dim.width,
                  dim.height,
                  startAngle,
                  arcAngle,
                  getColor(node),
                  isShapeFilled(node),
                  lp.strokeWidth,
                  lp.lineType);

        } else if (EL_POLYGON.equals(nodeName)) {
          Lineprops lp = getLineProps(node);

          Polygon polygon =
              new Polygon(getColor(node), isShapeFilled(node), lp.strokeWidth, lp.lineType);

          // points
          NodeList points = node.getElementsByTagName(EL_POINT);
          int pointCount = points.getLength();
          // arrays of polygon points
          int[] xs = new int[pointCount];
          int[] ys = new int[pointCount];
          // arrays of FIXED information about polygon points
          int[] fxs = new int[pointCount];
          int[] fys = new int[pointCount];
          int width = newGraphics.getBoundWidth();
          int height = newGraphics.getBoundHeight();

          for (int j = 0; j < pointCount; j++) {
            FixedCoords fc = getFixedCoords((Element) points.item(j), width, height, null);
            xs[j] = fc.x;
            fxs[j] = fc.fx;
            ys[j] = fc.y;
            fys[j] = fc.fy;
          }

          polygon.setPoints(xs, ys, fxs, fys);
          shape = polygon;

        } else if (EL_IMAGE.equals(nodeName)) {

          Dim dim = getDim(node);
          // image path should be relative to the package xml
          String imgPath = node.getAttribute(ATR_PATH);
          String fullPath = FileFuncs.preparePathOS(getWorkingDir() + imgPath);
          shape = new Image(dim.x, dim.y, fullPath, imgPath, isShapeFixed(node));

        } else if (EL_TEXT.equals(nodeName)) {
          shape = makeText(node, newGraphics);
          /*
           * if (str.equals("*self")) newText.name = "self"; else if
           * (str.equals("*selfWithName")) newText.name = "selfName";
           */
        }

        if (shape != null) newGraphics.addShape(shape);
      }

      return newGraphics;
    }