Ejemplo n.º 1
0
  NodeList getElementsByTagNameNS(
      final Parent xshadow, final String namespaceURI, final String localName) {
    if (localName == null) {
      return EMPTYLIST;
    }
    if (namespaceURI == null) {
      return EMPTYLIST;
    }

    final boolean alluri = "*".equals(namespaceURI);
    final boolean allname = "*".equals(localName);

    final ArrayList<JElement> enodes = new ArrayList<JElement>();
    if (xshadow != null) {
      final Iterator<org.jdom2.Element> it = xshadow.getDescendants(Filters.element());

      org.jdom2.Element e = null;
      if (xshadow instanceof org.jdom2.Element) {
        e = (org.jdom2.Element) xshadow;
      } else {
        if (it.hasNext()) {
          e = it.next();
        }
      }
      while (e != null) {
        if ((allname || localName.equals(e.getName()))
            && (alluri || namespaceURI.equals(e.getNamespaceURI()))) {
          enodes.add(find(e));
        }
        e = it.hasNext() ? it.next() : null;
      }
    }
    return new JNodeList(enodes);
  }
Ejemplo n.º 2
0
  static void parseXml(Element p_element, MessageDigest p_md, ArrayList<String> p_ignoreList) {
    p_md.update(p_element.getName().getBytes());

    String content = p_element.getText();

    if (content != null) {
      p_md.update(content.getBytes());
    }

    for (Attribute attribute : p_element.getAttributes()) {
      String name = attribute.getName();

      if (p_ignoreList.contains(name)) {
        continue;
      }

      String value = attribute.getValue();

      if (value != null) {
        p_md.update(value.getBytes());
      }
    }

    for (Element child : p_element.getChildren()) {
      parseXml(child, p_md, p_ignoreList);
    }
  }
  static void filterMarkerInElement(List<Element> eltList, Map<String, Object> parameterMap) {
    final Pattern patternMarker = Pattern.compile("\\$\\{([^}]+)\\}"); // matching pattern is ${..}

    for (Element elt : eltList) {
      String elementValue = elt.getText();

      if (elementValue == null) {
        continue;
      }

      Matcher matcher = patternMarker.matcher(elementValue);
      while (matcher.find()) {
        String marker = matcher.group(0); // full pattern matched ${..}
        String markerName = matcher.group(1); // get only text between curly braces
        String parameterValue = ServletUtil.getFirstParameter(parameterMap.get(markerName));

        if (parameterValue != null) {
          elementValue = elementValue.replace(marker, parameterValue);
          elt.setText(elementValue);

        } else {
          logger.warn(
              "Found marker \""
                  + marker
                  + "\" with NO matching parameter in Element <"
                  + elt.getName()
                  + ">");
        }
      }
    }
  }
  protected void parseLauncherTemplate(JnlpTemplate launcher)
      throws ServletErrorException, IOException {

    // PARSE JNLP LAUNCHER AS JDOM
    Element rootElt = null;
    BufferedReader reader = null;

    try {
      // Assume the template has UTF-8 encoding
      reader =
          new BufferedReader(
              new InputStreamReader(
                  launcher.realPathURL.openConnection().getInputStream(), "UTF-8"));

      rootElt = new SAXBuilder(XMLReaders.NONVALIDATING, null, null).build(reader).getRootElement();

      // rootElt = new SAXBuilder().build(launcher.realPathURL).getRootElement();
      // NOTE : doesn't work with all URl like "file://///server/..."

    } catch (JDOMException e) {
      throw new ServletErrorException(
          HttpServletResponse.SC_NOT_ACCEPTABLE, "Can't parse launcher template", e);
    } finally {
      FileUtil.safeClose(reader);
    }

    if (!rootElt.getName().equals(JNLP_TAG_ELT_ROOT)) {
      throw new ServletErrorException(
          HttpServletResponse.SC_NOT_ACCEPTABLE, "Invalid JNLP launcher template");
    }

    launcher.rootElt = rootElt;
  }
  private org.jdom2.Element getDataforCase(String specName, String caseID, String data) {
    String caseData = "";
    try {
      caseData = _ibClient.getCaseData(caseID, _handle);
    } catch (IOException e) {
      e.printStackTrace();
    }
    org.jdom2.Element result = new org.jdom2.Element(specName);

    SAXBuilder builder = new SAXBuilder();
    org.jdom2.Element root = null;
    List<org.jdom2.Element> ls = null;
    try {
      org.jdom2.Document document = builder.build(new StringReader(data));
      root = document.getRootElement();

      ls = document.getRootElement().getChildren();
    } catch (Exception e) {
      System.out.println(e);
    }
    for (org.jdom2.Element l : ls) {
      String paramName = l.getName();
      org.jdom2.Element advElem = root.getChild(paramName);
      try {
        if (advElem != null) {
          org.jdom2.Element copy = (org.jdom2.Element) advElem.clone();
          result.addContent(copy);
        } else {
          result.addContent(new org.jdom2.Element(paramName));
        }
      } catch (IllegalAddException iae) {
      }
    }
    return result;
  }
  private void ItemPostConstraint(WorkItemRecord wir, String data) {
    AdviceQuery query = new AdviceQuery();

    List<Advice> advs = query.getAdvicesByAdviceJoinPointID(wir.getID());
    if ((advs != null) && (advs.size() > 0)) {
      suspendCase(wir.getCaseID().substring(0, wir.getCaseID().indexOf('.')));
      System.out.println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
      System.out.println(
          "suspended case is " + wir.getCaseID().substring(0, wir.getCaseID().indexOf('.')));
      for (Advice advice : advs) {
        SAXBuilder builder = new SAXBuilder();

        List<org.jdom2.Element> ls = null;
        org.jdom2.Element root = null;
        try {
          org.jdom2.Document document = builder.build(new StringReader(data));
          ls = document.getRootElement().getChildren();
        } catch (Exception e) {
          System.out.println(e);
        }
        String s = "<" + advice.getProceedName() + ">";
        for (org.jdom2.Element l : ls) {
          s = s + "<" + l.getName() + ">" + l.getText() + "</" + l.getName() + ">";
        }
        s = s + "</" + advice.getProceedName() + ">";

        connect();

        advice.setSynched(false);
        this._Persister.beginTransaction();
        this._Persister.update(advice);
        this._Persister.commit();

        System.out.println(
            "*** try to checkin workitem with proceed id of "
                + advice.getProceedID()
                + " - with data: "
                + s);
        try {
          _ibClient.checkInWorkItem(advice.getProceedID(), s, "", _handle);
        } catch (IOException e) {
          System.out.println("************************ problem in checkin");
          e.printStackTrace();
        }
      }
    }
  }
 private void handlePartOfOrganOfOrgan(
     Document document, Element description, Element biologicalEntity, String parentOrgan) {
   String partOfChain =
       getPartOfChain(document, description, biologicalEntity, 0).replace(" of ", ",").trim();
   if (!partOfChain.isEmpty()) {
     // use explicit part_of
     log(
         LogLevel.DEBUG,
         "===>[pchain] use '"
             + partOfChain
             + "' as constraint to '"
             + biologicalEntity.getName()
             + "'");
     appendConstraint(biologicalEntity, formatParentOrgan(partOfChain));
   } else {
     String part = biologicalEntity.getName();
     if (part.matches("\\b(" + nonSpecificParts + ")\\b.*")
         && !part.contains(",")
         && parentOrgan.equals("whole_organism")) {
       parentOrgan =
           hasPart(
               biologicalEntity,
               biologicalEntity,
               description,
               parentOrgan,
               part,
               nonSpecificParts);
       if (!parentOrgan.isEmpty()) {
         log(
             LogLevel.DEBUG,
             "===>[part of 2] use '"
                 + parentOrgan
                 + "' as constraint to '"
                 + biologicalEntity.getName()
                 + "'");
         appendConstraint(biologicalEntity, formatParentOrgan(parentOrgan));
       } /*else{
         	//quite strong an assumption that the organ of the first clause is the parent organ of all following clauses.
         	//If this is not true, or the part_of hashtable is complete, comment out this part.
         	//log(LogLevel.DEBUG,"===>[default] use '"+pocp+"' as constraint to '"+struct.getName()+"'");
         	struct.appendConstraint(formatParentOrgan(pocp));
         	parentorgan = pocp;
         }*/
     }
   }
 }
 /**
  * Load all the deals in this element
  *
  * @param e an element that contains messages in XML format.
  */
 protected void loadDeals(Element e) {
   Element root = StringToElement.getElementFromString(e.getValue(), e.getName());
   for (Element d : root.getChildren()) {
     String owner = d.getChildText("owner");
     Element deal = d.getChild("Deal");
     addDeal(owner, new Contrat(deal));
   }
 }
Ejemplo n.º 9
0
  /**
   * Gets maps that are not installed, but may be downloaded.
   *
   * @return set of all maps available for download
   */
  public static Set<AutoRefMap> getRemoteMaps() {
    // check the cache first, we might want to just use the cached value
    long time = ManagementFactory.getRuntimeMXBean().getUptime() - _cachedRemoteMapsTime;
    if (_cachedRemoteMaps != null && time < AutoRefMap.REMOTE_MAP_CACHE_LENGTH)
      return _cachedRemoteMaps;

    Set<AutoRefMap> maps = Sets.newHashSet();
    String repo = AutoRefMatch.getMapRepo();

    try {
      Map<String, String> params = Maps.newHashMap();
      params.put("prefix", "maps/");

      for (; ; ) {
        String url = String.format("%s?%s", repo, QueryUtil.prepareParams(params));
        Element listing = new SAXBuilder().build(new URL(url)).getRootElement();
        assert "ListBucketResult".equals(listing.getName()) : "Unexpected response";
        Namespace ns = listing.getNamespace();

        String lastkey = null;
        for (Element entry : listing.getChildren("Contents", ns)) {
          lastkey = entry.getChildTextTrim("Key", ns);
          if (!lastkey.endsWith(".zip")) continue;

          String[] keyparts = lastkey.split("/");
          String mapfile = keyparts[keyparts.length - 1];

          String mapslug = mapfile.substring(0, mapfile.length() - 4);
          String slugparts[] = mapslug.split("-v");

          if (slugparts.length < 2) {
            AutoReferee.log("Invalid map filename: " + mapfile, Level.WARNING);
            AutoReferee.log("Map files should be of the form \"MapName-vX.X.zip\"", Level.WARNING);
          } else {
            String etag = entry.getChildTextTrim("ETag", ns);
            maps.add(
                new AutoRefMap(
                    slugparts[0], slugparts[1], lastkey, etag.substring(1, etag.length() - 1)));
          }
        }

        // stop looping if the result says that it hasn't been truncated (no more results)
        if (!Boolean.parseBoolean(listing.getChildText("IsTruncated", ns))) break;

        // use the last key as a marker for the next pass
        if (lastkey != null) params.put("marker", lastkey);
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (JDOMException e) {
      e.printStackTrace();
    }

    _cachedRemoteMapsTime = ManagementFactory.getRuntimeMXBean().getUptime();
    return _cachedRemoteMaps = maps;
  }
Ejemplo n.º 10
0
 /**
  * get named element from parent element
  *
  * @param elem _more_
  * @param eleName _more_
  * @return _more_
  */
 public Element readElements(Element elem, String eleName) {
   List<Element> children = elem.getChildren();
   for (Element child : children) {
     String childName = child.getName();
     if (childName.equals(eleName)) {
       return child;
     }
   }
   return null;
 }
Ejemplo n.º 11
0
  public static void xpathAttVal(Document doc, String ruta, String val) {

    XPathExpression<Element> xpath = XPathFactory.instance().compile(ruta, Filters.element());
    List<Element> elemento = xpath.evaluate(doc);
    Iterator it = elemento.iterator();

    while (it.hasNext()) {
      Element at = (Element) it.next();
      System.out.println(at.getName() + ": " + at.getAttributeValue(val));
    }
  }
Ejemplo n.º 12
0
  /**
   * This will invoke the <code>endElement</code> callback in the <code>ContentHandler</code>.
   *
   * @param element <code>Element</code> used in callbacks.
   */
  private void endElement(Element element) throws JDOMException {
    String namespaceURI = element.getNamespaceURI();
    String localName = element.getName();
    String rawName = element.getQualifiedName();

    try {
      contentHandler.endElement(namespaceURI, localName, rawName);
    } catch (SAXException se) {
      throw new JDOMException("Exception in endElement", se);
    }
  }
Ejemplo n.º 13
0
  public void addVariables(Element inRoot) throws org.jdom2.DataConversionException {
    Element vs = inRoot.getChild("decoder").getChild("variables");

    Element segment = new Element("segment");
    segment.setAttribute("space", "253");
    root.addContent(segment);

    Iterator it = vs.getDescendants();
    while (it.hasNext()) {
      Object o = it.next();
      if (o instanceof Element) {
        Element e = (Element) o;
        if (e.getName().equals("variable")) {
          // get common attributes
          String comment = e.getAttributeValue("comment");
          for (Object oc : e.getChildren("comment")) {
            Element ec = (Element) oc;
            if (ec.getAttributeValue("lang", "xml").equals("")) comment = ec.getText();
          }
          String name = e.getAttributeValue("label");
          if (name.equals("")) name = e.getAttributeValue("item");
          for (Object on : e.getChildren("label")) {
            Element en = (Element) on;
            if (en.getAttributeValue("lang", "xml").equals("")) name = en.getText();
          }

          long cv = e.getAttribute("CV").getIntValue();

          // find subtype and process
          Element type;
          type = e.getChild("decVal");
          if (type != null) {
            segment.addContent(handleDecVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("enumVal");
          if (type != null) {
            segment.addContent(handleEnumVal(type, cv, name, comment, e.getAttributeValue("mask")));
            continue;
          }
          type = e.getChild("shortAddressVal");
          if (type != null) {
            segment.addContent(handleShortAddressVal(type, cv, name, comment));
            continue;
          }
          type = e.getChild("longAddressVal");
          if (type != null) {
            segment.addContent(handleLongAddressVal(type, cv, name, comment));
            continue;
          }
        }
      }
    }
  }
 /**
  * This constructor is not intended for usage.
  *
  * @param xml An XML string
  * @throws JDOMException Is thrown when the xml string is invalid
  * @throws IOException Is thrown when the xml string is invalid
  */
 public LolStatus(String xml) throws JDOMException, IOException {
   outputter.setFormat(outputter.getFormat().setExpandEmptyElements(false));
   final SAXBuilder saxBuilder = new SAXBuilder();
   doc = saxBuilder.build(new StringReader(xml));
   for (final Element e : doc.getRootElement().getChildren()) {
     boolean found = false;
     for (final XMLProperty p : XMLProperty.values()) {
       if (p.name().equals(e.getName())) {
         found = true;
       }
     }
     if (!found) {
       System.err.println(
           "XMLProperty \""
               + e.getName()
               + "\" value: \""
               + e.getValue()
               + "\" not implemented yet!");
     }
   }
 }
Ejemplo n.º 15
0
  private String parseXmlToHtml(List<Content> docElements) {
    String html = "";
    Iterator<Content> li = docElements.listIterator();
    while (li.hasNext()) {
      Content content = li.next();
      CType type = content.getCType();
      if (type == CType.Element) {
        Element element = (Element) content;
        if (element.getName().equals("bold")) html += "<b>";
        else if (element.getName().equals("italics")) html += "<i>";
        else if (element.getName().equals("list")) html += "<ul>";
        else if (element.getName().equals("item")) {
          html = html.trim();
          html += "<li>";
        }

        html += parseXmlToHtml(element.getContent()).trim();

        if (element.getName().equals("bold")) html += "</b>";
        else if (element.getName().equals("italics")) html += "</i>";
        else if (element.getName().equals("list")) html += "</ul>";
        else if (element.getName().equals("item")) html += "</li>";

      } else if (type == CType.Text) {
        Text text = (Text) content;
        String str = text.getText();
        html += str;
      }
    }
    return html;
  }
Ejemplo n.º 16
0
  public static AutoRefGoal fromElement(AutoRefTeam team, Element elt) {
    Class<? extends AutoRefGoal> cls = goalNames.get(elt.getName());
    if (cls == null) return null;

    try {
      Constructor<? extends AutoRefGoal> cons =
          cls.getConstructor(AutoRefTeam.class, Element.class);
      return cons.newInstance(team, elt).getGoalSettings(team, elt);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Ejemplo n.º 17
0
  public static void main(String[] args) {

    long start = System.currentTimeMillis();

    try {
      // 获取JDOM解析器
      SAXBuilder builder = new SAXBuilder();
      // 解析文件
      File file = new File("xml/books.xml");
      Document document = builder.build(file);

      // 写入XML文件
      FileOutputStream fileOutputStream = new FileOutputStream(new File("D:/aaa.xml"));
      XMLOutputter xmlOutputter = new XMLOutputter();
      xmlOutputter.output(document, fileOutputStream);
      fileOutputStream.close();

      // 获取根节点
      Element root = document.getRootElement();
      // 获取子节点列表
      List<Element> books = root.getChildren();
      // 循环遍历子节点
      for (int i = 0; i < books.size(); i++) {
        // 获取某一个子节点
        Element book = books.get(i);
        // 获取得属性值
        String isbn = book.getAttributeValue("isbn");
        System.out.print("isbn: " + isbn);
        List<Element> childrenList = book.getChildren();
        for (Element element : childrenList) {
          System.out.print("   " + element.getName() + ": ");
          System.out.print(element.getText());
        }
        System.out.println("");
      }
    } catch (JDOMException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }

    long end = System.currentTimeMillis();
    System.out.println("耗时: " + (end - start));
  }
Ejemplo n.º 18
0
  void metaVersusData(Element p_element) {
    m_metaSize += p_element.getName().length();

    String content = p_element.getText();

    if (content != null) m_dataSize += content.length();

    for (Attribute attribute : p_element.getAttributes()) {
      String name = attribute.getName();

      m_metaSize += name.length();

      String value = attribute.getValue();

      if (value != null) {
        m_dataSize += value.length();
      }
    }

    for (Element child : p_element.getChildren()) {
      metaVersusData(child);
    }
  }
Ejemplo n.º 19
0
  /**
   * This will invoke the <code>startElement</code> callback in the <code>ContentHandler</code>.
   *
   * @param element <code>Element</code> used in callbacks.
   * @param nsAtts <code>List</code> of namespaces to declare with the element or <code>null</code>.
   */
  private void startElement(Element element, Attributes nsAtts) throws JDOMException {
    String namespaceURI = element.getNamespaceURI();
    String localName = element.getName();
    String rawName = element.getQualifiedName();

    // Allocate attribute list.
    AttributesImpl atts = (nsAtts != null) ? new AttributesImpl(nsAtts) : new AttributesImpl();

    for (Attribute a : element.getAttributes()) {
      atts.addAttribute(
          a.getNamespaceURI(),
          a.getName(),
          a.getQualifiedName(),
          getAttributeTypeName(a.getAttributeType()),
          a.getValue());
    }

    try {
      contentHandler.startElement(namespaceURI, localName, rawName, atts);
    } catch (SAXException se) {
      throw new JDOMException("Exception in startElement", se);
    }
  }
Ejemplo n.º 20
0
  /**
   * Amend the given NetcdfFile with metadata from HDF-EOS structMetadata
   *
   * @param ncfile Amend this file
   * @param structMetadata structMetadata as String
   * @throws IOException on read error
   */
  private void amendFromODL(NetcdfFile ncfile, String structMetadata) throws IOException {
    Group rootg = ncfile.getRootGroup();

    ODLparser parser = new ODLparser();
    Element root = parser.parseFromString(structMetadata); // now we have the ODL in JDOM elements
    FeatureType featureType = null;

    // SWATH
    Element swathStructure = root.getChild("SwathStructure");
    if (swathStructure != null) {
      List<Element> swaths = swathStructure.getChildren();
      for (Element elemSwath : swaths) {
        Element swathNameElem = elemSwath.getChild("SwathName");
        if (swathNameElem == null) {
          log.warn("No SwathName element in {} {} ", elemSwath.getName(), ncfile.getLocation());
          continue;
        }
        String swathName = NetcdfFile.makeValidCdmObjectName(swathNameElem.getText().trim());
        Group swathGroup = findGroupNested(rootg, swathName);
        // if (swathGroup == null)
        //  swathGroup = findGroupNested(rootg, H4header.createValidObjectName(swathName));

        if (swathGroup != null) {
          featureType = amendSwath(ncfile, elemSwath, swathGroup);
        } else {
          log.warn("Cant find swath group {} {}", swathName, ncfile.getLocation());
        }
      }
    }

    // GRID
    Element gridStructure = root.getChild("GridStructure");
    if (gridStructure != null) {
      List<Element> grids = gridStructure.getChildren();
      for (Element elemGrid : grids) {
        Element gridNameElem = elemGrid.getChild("GridName");
        if (gridNameElem == null) {
          log.warn("No GridName element in {} {} ", elemGrid.getName(), ncfile.getLocation());
          continue;
        }
        String gridName = NetcdfFile.makeValidCdmObjectName(gridNameElem.getText().trim());
        Group gridGroup = findGroupNested(rootg, gridName);
        // if (gridGroup == null)
        //  gridGroup = findGroupNested(rootg, H4header.createValidObjectName(gridName));
        if (gridGroup != null) {
          featureType = amendGrid(elemGrid, ncfile, gridGroup, ncfile.getLocation());
        } else {
          log.warn("Cant find Grid group {} {}", gridName, ncfile.getLocation());
        }
      }
    }

    // POINT - NOT DONE YET
    Element pointStructure = root.getChild("PointStructure");
    if (pointStructure != null) {
      List<Element> pts = pointStructure.getChildren();
      for (Element elem : pts) {
        Element nameElem = elem.getChild("PointName");
        if (nameElem == null) {
          log.warn("No PointName element in {} {}", elem.getName(), ncfile.getLocation());
          continue;
        }
        String name = nameElem.getText().trim();
        Group ptGroup = findGroupNested(rootg, name);
        // if (ptGroup == null)
        //  ptGroup = findGroupNested(rootg, H4header.createValidObjectName(name));
        if (ptGroup != null) {
          featureType = FeatureType.POINT;
        } else {
          log.warn("Cant find Point group {} {}", name, ncfile.getLocation());
        }
      }
    }

    if (featureType != null) {
      if (showWork) System.out.println("***EOS featureType= " + featureType.toString());
      rootg.addAttribute(new Attribute(CF.FEATURE_TYPE, featureType.toString()));
      // rootg.addAttribute(new Attribute(CDM.CONVENTIONS, "HDFEOS"));
    }
  }
Ejemplo n.º 21
0
  /**
   * Create a LayoutEditor object, then register and fill it, then pop it in a JFrame
   *
   * @param shared Top level Element to unpack.
   */
  @Override
  public boolean load(Element shared, Element perNode) {
    boolean result = true;
    Attribute a;
    // find coordinates
    int x = 0;
    int y = 0;
    // From this version onwards separate sizes for window and panel are used
    int windowHeight = 400;
    int windowWidth = 300;
    int panelHeight = 340;
    int panelWidth = 280;
    int sidetrackwidth = 3;
    int mainlinetrackwidth = 3;
    try {
      x = shared.getAttribute("x").getIntValue();
      y = shared.getAttribute("y").getIntValue();
      // For compatibility with previous versions, try and see if height and width tags are
      // contained in the file
      if ((a = shared.getAttribute("height")) != null) {
        windowHeight = a.getIntValue();
        panelHeight = windowHeight - 60;
      }
      if ((a = shared.getAttribute("width")) != null) {
        windowWidth = a.getIntValue();
        panelWidth = windowWidth - 18;
      }
      // For files created by the new version, retrieve window and panel sizes
      if ((a = shared.getAttribute("windowheight")) != null) {
        windowHeight = a.getIntValue();
      }
      if ((a = shared.getAttribute("windowwidth")) != null) {
        windowWidth = a.getIntValue();
      }
      if ((a = shared.getAttribute("panelheight")) != null) {
        panelHeight = a.getIntValue();
      }
      if ((a = shared.getAttribute("panelwidth")) != null) {
        panelWidth = a.getIntValue();
      }

      mainlinetrackwidth = shared.getAttribute("mainlinetrackwidth").getIntValue();
      sidetrackwidth = shared.getAttribute("sidetrackwidth").getIntValue();
    } catch (org.jdom2.DataConversionException e) {
      log.error("failed to convert LayoutEditor's attribute");
      result = false;
    }
    double xScale = 1.0;
    double yScale = 1.0;
    a = shared.getAttribute("xscale");
    if (a != null) {
      try {
        xScale = (Float.parseFloat(a.getValue()));
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("yscale");
    if (a != null) {
      try {
        yScale = (Float.parseFloat(a.getValue()));
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    // find the name and default track color
    String name = "";
    if (shared.getAttribute("name") != null) {
      name = shared.getAttribute("name").getValue();
    }
    if (jmri.jmrit.display.PanelMenu.instance().isPanelNameUsed(name)) {
      JFrame frame = new JFrame("DialogDemo");
      frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
      log.warn("File contains a panel with the same name (" + name + ") as an existing panel");
      int n =
          JOptionPane.showConfirmDialog(
              frame,
              java.text.MessageFormat.format(rb.getString("DuplicatePanel"), new Object[] {name}),
              rb.getString("DuplicatePanelTitle"),
              JOptionPane.YES_NO_OPTION);
      if (n == JOptionPane.NO_OPTION) {
        return false;
      }
    }
    String defaultColor = "black";
    String defaultTextColor = "black";
    if (shared.getAttribute("defaulttrackcolor") != null) {
      defaultColor = shared.getAttribute("defaulttrackcolor").getValue();
    }
    if (shared.getAttribute("defaulttextcolor") != null) {
      defaultTextColor = shared.getAttribute("defaulttextcolor").getValue();
    }
    String turnoutCircleColor =
        "track"; // default to using use default track color for circle color
    if (shared.getAttribute("turnoutcirclecolor") != null) {
      turnoutCircleColor = shared.getAttribute("turnoutcirclecolor").getValue();
    }
    int turnoutCircleSize = 2;
    if (shared.getAttribute("turnoutcirclesize") != null) {
      try {
        turnoutCircleSize = shared.getAttribute("turnoutcirclesize").getIntValue();
      } catch (DataConversionException e1) {
        // leave at default if cannot convert
        log.warn("unable to convert turnoutcirclesize");
      }
    }
    boolean turnoutDrawUnselectedLeg = true;
    if ((a = shared.getAttribute("turnoutdrawunselectedleg")) != null
        && a.getValue().equals("no")) {
      turnoutDrawUnselectedLeg = false;
    }
    // create the objects
    LayoutEditor panel = new LayoutEditor(name);
    panel.setLayoutName(name);
    panel.setMainlineTrackWidth(mainlinetrackwidth);
    panel.setSideTrackWidth(sidetrackwidth);
    panel.setDefaultTrackColor(defaultColor);
    panel.setDefaultTextColor(defaultTextColor);
    panel.setTurnoutCircleColor(turnoutCircleColor);
    panel.setTurnoutCircleSize(turnoutCircleSize);
    panel.setTurnoutDrawUnselectedLeg(turnoutDrawUnselectedLeg);
    panel.setXScale(xScale);
    panel.setYScale(yScale);
    // turnout size parameters
    double sz = 20.0;
    a = shared.getAttribute("turnoutbx");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setTurnoutBX(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("turnoutcx");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setTurnoutCX(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("turnoutwid");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setTurnoutWid(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("xoverlong");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setXOverLong(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("xoverhwid");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setXOverHWid(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    a = shared.getAttribute("xovershort");
    if (a != null) {
      try {
        sz = (Float.parseFloat(a.getValue()));
        panel.setXOverShort(sz);
      } catch (Exception e) {
        log.error("failed to convert to float - " + a.getValue());
        result = false;
      }
    }
    // grid size parameter
    int iz = 10; // thisw value is never used but it's the default
    a = shared.getAttribute("gridSize");
    if (a != null) {
      try {
        iz = (Integer.parseInt(a.getValue()));
        panel.setGridSize(iz);
      } catch (Exception e) {
        log.error("failed to convert to int - " + a.getValue());
        result = false;
      }
    }

    // set contents state
    String slValue = "both";
    if ((a = shared.getAttribute("sliders")) != null && a.getValue().equals("no")) {
      slValue = "none";
    }
    if ((a = shared.getAttribute("scrollable")) != null) {
      slValue = a.getValue();
    }

    boolean edValue = true;
    if ((a = shared.getAttribute("editable")) != null && a.getValue().equals("no")) {
      edValue = false;
    }

    boolean value = true;
    if ((a = shared.getAttribute("positionable")) != null && a.getValue().equals("no")) {
      value = false;
    }
    panel.setAllPositionable(value);

    value = true;
    if ((a = shared.getAttribute("controlling")) != null && a.getValue().equals("no")) {
      value = false;
    }
    panel.setAllControlling(value);

    value = true;
    if ((a = shared.getAttribute("animating")) != null && a.getValue().equals("no")) {
      value = false;
    }
    panel.setTurnoutAnimation(value);

    boolean hbValue = true;
    if ((a = shared.getAttribute("showhelpbar")) != null && a.getValue().equals("no")) {
      hbValue = false;
    }

    boolean dgValue = false;
    if ((a = shared.getAttribute("drawgrid")) != null && a.getValue().equals("yes")) {
      dgValue = true;
    }

    boolean sgaValue = false;
    if ((a = shared.getAttribute("snaponadd")) != null && a.getValue().equals("yes")) {
      sgaValue = true;
    }

    boolean sgmValue = false;
    if ((a = shared.getAttribute("snaponmove")) != null && a.getValue().equals("yes")) {
      sgmValue = true;
    }

    boolean aaValue = false;
    if ((a = shared.getAttribute("antialiasing")) != null && a.getValue().equals("yes")) {
      aaValue = true;
    }

    value = false;
    if ((a = shared.getAttribute("turnoutcircles")) != null && a.getValue().equals("yes")) {
      value = true;
    }
    panel.setTurnoutCircles(value);

    value = false;
    if ((a = shared.getAttribute("tooltipsnotedit")) != null && a.getValue().equals("yes")) {
      value = true;
    }
    panel.setTooltipsNotEdit(value);

    value = false;
    if ((a = shared.getAttribute("autoblkgenerate")) != null && a.getValue().equals("yes")) {
      value = true;
    }
    panel.setAutoBlockAssignment(value);

    value = true;
    if ((a = shared.getAttribute("tooltipsinedit")) != null && a.getValue().equals("no")) {
      value = false;
    }
    panel.setTooltipsInEdit(value);
    // set default track color
    if ((a = shared.getAttribute("defaulttrackcolor")) != null) {
      panel.setDefaultTrackColor(a.getValue());
    }
    // set default track color
    if ((a = shared.getAttribute("defaultoccupiedtrackcolor")) != null) {
      panel.setDefaultOccupiedTrackColor(a.getValue());
    }
    // set default track color
    if ((a = shared.getAttribute("defaultalternativetrackcolor")) != null) {
      panel.setDefaultAlternativeTrackColor(a.getValue());
    }
    try {
      int red = shared.getAttribute("redBackground").getIntValue();
      int blue = shared.getAttribute("blueBackground").getIntValue();
      int green = shared.getAttribute("greenBackground").getIntValue();
      panel.setDefaultBackgroundColor(ColorUtil.colorToString(new Color(red, green, blue)));
      panel.setBackgroundColor(new Color(red, green, blue));
    } catch (org.jdom2.DataConversionException e) {
      log.warn("Could not parse color attributes!");
    } catch (NullPointerException e) { // considered normal if the attributes are not present
    }
    if (shared.getAttribute("useDirectTurnoutControl") != null) {
      if (shared.getAttribute("useDirectTurnoutControl").getValue().equals("yes")) {
        panel.setDirectTurnoutControl(true);
      }
    }
    // Set editor's option flags, load content after
    // this so that individual item flags are set as saved
    panel.initView();

    // load the contents
    List<Element> items = shared.getChildren();
    for (int i = 0; i < items.size(); i++) {
      // get the class, hence the adapter object to do loading
      Element item = items.get(i);
      String adapterName = item.getAttribute("class").getValue();
      if (log.isDebugEnabled()) {
        String id = "<null>";
        try {
          id = item.getAttribute("ident").getValue();
        } catch (Exception e) {
        }
        log.debug("Load " + id + " for [" + panel.getName() + "] via " + adapterName);
      }
      try {
        XmlAdapter adapter = (XmlAdapter) Class.forName(adapterName).newInstance();
        // and do it
        adapter.load(item, panel);
        if (!panel.loadOK()) {
          result = false;
        }
      } catch (Exception e) {
        log.error("Exception while loading " + item.getName() + ":" + e);
        result = false;
        e.printStackTrace();
      }
    }
    panel.disposeLoadData(); // dispose of url correction data

    // final initialization of objects
    panel.setConnections();

    // display the results
    panel.setAllEditable(edValue); // set first since other attribute use this setting
    panel.setShowHelpBar(hbValue);
    panel.setDrawGrid(dgValue);
    panel.setSnapOnAdd(sgaValue);
    panel.setSnapOnMove(sgmValue);
    panel.setAntialiasingOn(aaValue);
    panel.setScroll(slValue);
    panel.pack();
    panel.setLayoutDimensions(windowWidth, windowHeight, x, y, panelWidth, panelHeight);
    panel.setVisible(true); // always show the panel
    panel.resetDirty();

    // register the resulting panel for later configuration
    InstanceManager.getOptionalDefault(jmri.ConfigureManager.class).registerUser(panel);
    if (jmri.InstanceManager.getDefault(jmri.TransitManager.class).getSystemNameList().size() > 0) {
      if (shared.getAttribute("openDispatcher") != null) {
        if (shared.getAttribute("openDispatcher").getValue().equals("yes")) {
          panel.setOpenDispatcherOnLoad(true);
          jmri.jmrit.dispatcher.DispatcherFrame.instance();
        } else {
          panel.setOpenDispatcherOnLoad(false);
        }
      }
    }
    return result;
  }
  /**
   * form and apply a parent organ to parts
   *
   * @param description:
   * @param statement
   * @param parentStructure element holding a candidate parent
   * @param parentOfParentStructure string of the name of the parent organ of the parentstructure
   * @return
   */
  private String attachParentOrganToOtherBiologicalEntities(
      Document document,
      Element description,
      Element statement,
      Element parentStructure,
      String parentOfParentStructure,
      String nonSpecificParts) {
    String parentOrgan =
        getParentOrgan(document, description, parentStructure, parentOfParentStructure);

    // parentorgan = parentorgan.trim();
    // attach parentorgan to other 'structures' in this statement
    List<Element> biologicalEntities =
        statement.getChildren("biological_entity"); // could include 'relation' too

    String parentStructureName = null;
    for (Element biologicalEntity : biologicalEntities) {
      if (!biologicalEntity.equals(parentStructure)) {
        // skip the 1st structure which is parentstruct
        if (!hasStructuralConstraint(biologicalEntity)) {
          String partOfChain =
              getPartOfChain(document, description, biologicalEntity, 3)
                  .replace(" of ", ",")
                  .trim(); // part of organ of organ
          String part =
              biologicalEntity.getAttributeValue("name")
                  + (partOfChain.isEmpty() ? "" : "," + partOfChain);

          if (part.matches("\\b(" + nonSpecificParts + ")\\b.*")
              && !part.contains(",")
              && parentOrgan.equals("whole_organism")) {
            parentStructureName =
                hasPart(
                    parentStructure,
                    biologicalEntity,
                    description,
                    parentOrgan,
                    part,
                    nonSpecificParts);
            if (!parentStructureName.isEmpty()) {
              log(
                  LogLevel.DEBUG,
                  "===>[part of 1] use '"
                      + parentStructureName
                      + "' as constraint to '"
                      + biologicalEntity.getName()
                      + "'");
              appendConstraint(biologicalEntity, formatParentOrgan(parentStructureName));
            } else if (possess(parentStructure, biologicalEntity, description)) {
              parentStructureName = formatParentOrgan(parentOrgan);
              log(
                  LogLevel.DEBUG,
                  "===>[possess] use '"
                      + parentStructureName
                      + "' as constraint to '"
                      + biologicalEntity.getName()
                      + "'");
              appendConstraint(biologicalEntity, formatParentOrgan(parentStructureName));
            }
          }
        }
      }
    }
    return parentStructureName != null
        ? parentStructureName
        : parentOrgan.replaceAll("(^,|,$)", "");
  }
  /**
   * if parentStruct and partStruct has a non-possessing relation, return "" (e.g., The nucleus
   * situated in the posterior part of the body. => Body is not part of Nucleus.) otherwise (i.e.
   * has no relation, or has a possessing relation), return parent structure name as a string
   *
   * @param parentStructure
   * @param partStructure
   * @param description
   * @param parentName a list of organ, separated by ',', listed from suborgan to parent organ.
   * @param partName a list of organ, separated by ',', listed from suborgan to parent organ.
   * @return the name of parent structure (Format: "blade,leaf"), or "" if parentStruct is not a
   *     parent
   */
  private String hasPart(
      Element parentStructure,
      Element partStructure,
      Element description,
      String parentName,
      String partName,
      String nonSpecificParts) {
    if (partName.contains(",")) {
      return partName.substring(partName.indexOf(",")).trim();
    }

    List<Element> statements = description.getChildren("statement");
    // check relations for evidence
    boolean hasRelation = false;
    boolean hasPossessRelation = false;
    for (Element statement : statements) {
      List<Element> relations = statement.getChildren("relation");
      for (Element relation : relations) {
        String from = relation.getAttributeValue("from");
        String to = relation.getAttributeValue("to");
        if ((from != null
            && from.equals(parentStructure.getAttributeValue("id"))
            && to != null
            && to.equals(partStructure.getAttributeValue("id")))) {
          hasRelation = true;
          if (possessionTerms.contains(relation.getName())) hasPossessRelation = true;
        }
      }
    }

    // check character constraints for evidence
    String parentId = parentStructure.getAttributeValue("id");
    String partId = partStructure.getAttributeValue("id");
    for (Element statement : statements) {
      List<Element> biologicalEnties = statement.getChildren("biological_entity");
      for (Element biologicalEntity : biologicalEnties) {
        for (Element character : biologicalEntity.getChildren("character")) {
          String constraintId = character.getAttributeValue("constraintid");
          String constraint = character.getAttributeValue("constraint");
          if (constraintId != null
              && constraintId.equals(partId)
              && biologicalEntity.getAttributeValue("id").equals(parentId)
              && constraint != null) {
            hasRelation = true;
            if (possessionTerms.contains(
                constraint.contains(" ")
                    ? constraint.substring(0, constraint.indexOf(" "))
                    : constraint)) // first word in constraint string is in possess
            hasPossessRelation = true;
          }
        }
      }
    }

    if (!hasRelation || (hasRelation && hasPossessRelation)) {
      if (partName.matches("\\b(" + nonSpecificParts + ")\\b.*") && !partName.contains(",")) {
        parentName =
            parentName.replaceFirst(
                "(\\b(" + nonSpecificParts + ")\\b,? ?)+",
                ""); // "base of surface, stem" does not make sense.
        return parentName;
      }
    }
    return "";
  }
Ejemplo n.º 24
0
  public static void read(org.jdom2.Element root, StringBuilder errlog) {

    List children = root.getChildren();
    for (int i = 0; i < children.size(); i++) {
      Element elem = (Element) children.get(i);
      if (elem.getName().equals("ioServiceProvider")) {
        String className = elem.getAttributeValue("class");

        try {
          ucar.nc2.NetcdfFile.registerIOProvider(className);
        } catch (ClassNotFoundException e) {
          errlog.append(
              "CoordSysBuilder class not found= " + className + "; check your classpath\n");
        } catch (Exception e) {
          errlog.append("IOServiceProvider " + className + " failed= " + e.getMessage() + "\n");
        }

      } else if (elem.getName().equals("coordSysBuilder")) {
        String conventionName = elem.getAttributeValue("convention");
        String className = elem.getAttributeValue("class");

        try {
          ucar.nc2.dataset.CoordSysBuilder.registerConvention(conventionName, className);
        } catch (ClassNotFoundException e) {
          errlog.append(
              "CoordSysBuilder class not found= " + className + "; check your classpath\n");
        } catch (Exception e) {
          errlog.append("CoordSysBuilder " + className + " failed= " + e.getMessage() + "\n");
        }

      } else if (elem.getName().equals("coordTransBuilder")) {
        String transformName = elem.getAttributeValue("name");
        String className = elem.getAttributeValue("class");

        try {
          ucar.nc2.dataset.CoordTransBuilder.registerTransform(transformName, className);
        } catch (ClassNotFoundException e) {
          errlog.append(
              "CoordSysBuilder class not found= " + className + "; check your classpath\n");
        } catch (Exception e) {
          errlog.append("CoordTransBuilder " + className + " failed= " + e.getMessage() + "\n");
        }

      } else if (elem.getName().equals("typedDatasetFactory")) {
        String typeName = elem.getAttributeValue("datatype");
        String className = elem.getAttributeValue("class");
        FeatureType datatype = FeatureType.valueOf(typeName.toUpperCase());
        if (null == datatype) {
          errlog.append(
              "TypedDatasetFactory " + className + " unknown datatype= " + typeName + "\n");
          continue;
        }

        try {
          ucar.nc2.dt.TypedDatasetFactory.registerFactory(datatype, className);
        } catch (ClassNotFoundException e) {
          errlog.append(
              "CoordSysBuilder class not found= " + className + "; check your classpath\n");
        } catch (Exception e) {
          errlog.append("TypedDatasetFactory " + className + " failed= " + e.getMessage() + "\n");
        }

      } else if (elem.getName().equals("gribParameterTable")) {
        String editionS = elem.getAttributeValue("edition");
        String centerS = elem.getAttributeValue("center");
        String subcenterS = elem.getAttributeValue("subcenter");
        String versionS = elem.getAttributeValue("version");
        String filename = elem.getText();
        if ((centerS == null) || (versionS == null) || (filename == null)) {
          errlog.append("table element must center, version and filename attributes\n");
          continue;
        }

        // Grib1ParamTables.addParameterTable(int center, int subcenter, int tableVersion, String
        // filename) {
        // use reflection to decouple from the grib package
        try {
          int center = Integer.parseInt(centerS);
          int subcenter = (subcenterS == null) ? -1 : Integer.parseInt(subcenterS);
          int version = Integer.parseInt(versionS);

          // ucar.nc2.grib.grib1.tables.Grib1ParamTables.addParameterTable(int center, int
          // subcenter, int tableVersion, String tableFilename)
          Class c =
              RuntimeConfigParser.class
                  .getClassLoader()
                  .loadClass("ucar.nc2.grib.grib1.tables.Grib1ParamTables");
          Method m =
              c.getMethod("addParameterTable", int.class, int.class, int.class, String.class);
          m.invoke(null, center, subcenter, version, filename);

        } catch (Exception e) {
          e.printStackTrace();
        }

        String strictS = elem.getAttributeValue("strict");
        if (strictS != null) {
          boolean notStrict = strictS.equalsIgnoreCase("false");
          try {
            Class c =
                RuntimeConfigParser.class
                    .getClassLoader()
                    .loadClass("ucar.grib.grib1.tables.Grib1ParamTables");
            Method m = c.getMethod("setStrict", boolean.class);
            m.invoke(null, !notStrict);

          } catch (Exception e) {
            e.printStackTrace();
          }

          continue;
        }

      } else if (elem.getName().equals("gribParameterTableLookup")) {

        String editionS = elem.getAttributeValue("edition");
        String filename = elem.getText();

        // ucar.nc2.grib.grib1.tables.Grib1ParamTables.addParameterTableLookup(String
        // lookupFilename)
        try {
          Class c =
              RuntimeConfigParser.class
                  .getClassLoader()
                  .loadClass("ucar.nc2.grib.grib1.tables.Grib1ParamTables");
          Method m = c.getMethod("addParameterTableLookup", String.class);
          m.invoke(null, filename);

        } catch (Exception e) {
          e.printStackTrace();
        }

      } else if (elem.getName().equals("table")) {
        String type = elem.getAttributeValue("type");
        String filename = elem.getAttributeValue("filename");
        if ((type == null) || (filename == null)) {
          errlog.append("table element must have both type and filename attributes\n");
          continue;
        }

        try {
          if (type.equalsIgnoreCase("GRIB1")) {
            // ucar.grib.grib1.GribPDSParamTable.addParameterUserLookup( filename);
            // use reflection instead to decouple from the grib package
            try {
              Class c =
                  RuntimeConfigParser.class
                      .getClassLoader()
                      .loadClass("ucar.grib.grib1.GribPDSParamTable");
              Method m = c.getMethod("addParameterUserLookup", String.class);
              m.invoke(null, filename);

            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            } catch (NoSuchMethodException e) {
              e.printStackTrace();
            } catch (InvocationTargetException e) {
              e.printStackTrace();
            } catch (IllegalAccessException e) {
              e.printStackTrace();
            }

          } else if (type.equalsIgnoreCase("GRIB2")) {
            // ucar.grib.grib2.ParameterTable.addParametersUser( filename);
            try {
              Class c =
                  RuntimeConfigParser.class
                      .getClassLoader()
                      .loadClass(" ucar.grib.grib2.ParameterTable");
              Method m = c.getMethod("addParametersUser", String.class);
              m.invoke(null, filename);

            } catch (Exception e) {
              e.printStackTrace();
            }

          } else {
            errlog.append("Unknown table type " + type + "\n");
            continue;
          }

        } catch (Exception e) {
          errlog.append("table read failed on  " + filename + " = " + e.getMessage() + "\n");
        }

      } else if (elem.getName().equals("bufrtable")) {

        String filename = elem.getAttributeValue("filename");
        if (filename == null) {
          errlog.append("bufrtable must have filename attribute\n");
          continue;
        }

        // reflection is used to decouple optional jars
        Class bufrTablesClass;
        try {
          bufrTablesClass =
              RuntimeConfigParser.class
                  .getClassLoader()
                  .loadClass(
                      "ucar.nc2.iosp.bufr.tables.BufrTables"); // only load if bufr.jar is present
          java.lang.Class[] params = new Class[1];
          params[0] = String.class;
          Method method = bufrTablesClass.getMethod("addLookupFile", params);
          Object[] args = new Object[1];
          args[0] = filename;
          method.invoke(null, args); // static method has null for object

        } catch (Throwable e) {
          if (e instanceof FileNotFoundException)
            errlog.append("bufrtable read failed on  " + filename + " = " + e.getMessage() + "\n");
          else errlog.append("bufr.jar is not on classpath\n");
        }

      } else if (elem.getName().equals("Netcdf4Clibrary")) {
        // cdm does not have a dependency on netcdf4 (and we don't want to introduce one),
        // so we cannot refer to the Nc4Iosp.class object.
        String nc4IospClassName = "ucar.nc2.jni.netcdf.Nc4Iosp";

        /*
          <Netcdf4Clibrary>
            <libraryPath>/usr/local/lib</libraryPath>
            <libraryName>netcdf</libraryName>
            <useForReading>false</useForReading>
          </Netcdf4Clibrary>
        */
        String path = elem.getChildText("libraryPath");
        String name = elem.getChildText("libraryName");

        if (path != null && name != null) {
          // reflection is used to decouple optional jars
          try {
            Class nc4IospClass =
                RuntimeConfigParser.class.getClassLoader().loadClass(nc4IospClassName);
            Method method =
                nc4IospClass.getMethod(
                    "setLibraryAndPath", new Class[] {String.class, String.class});
            method.invoke(null, path, name); // static method has null for object
          } catch (Throwable e) {
            errlog.append(nc4IospClassName + " is not on classpath\n");
          }
        }

        boolean useForReading = Boolean.parseBoolean(elem.getChildText("useForReading"));
        if (useForReading) {
          try {
            // Registers Nc4Iosp in front of all the other IOSPs already registered in
            // NetcdfFile.<clinit>().
            // Crucially, this means that we'll try to open a file with Nc4Iosp before we try it
            // with H5iosp.
            NetcdfFile.registerIOProvider(nc4IospClassName);
          } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) {
            errlog.append(
                String.format(
                    "Could not register IOSP '%s': %s%n", nc4IospClassName, e.getMessage()));
          }
        }
      }
    }
  }
Ejemplo n.º 25
0
  /** Parse a DAX file with jdom */
  private void parseXmlFile(String path) {

    try {

      SAXBuilder builder = new SAXBuilder();
      // parse using builder to get DOM representation of the XML file
      Document dom = builder.build(new File(path));
      Element root = dom.getRootElement();
      List list = root.getChildren();
      for (Iterator it = list.iterator(); it.hasNext(); ) {
        Element node = (Element) it.next();
        if (node.getName().toLowerCase().equals("job")) {

          long length = 0;
          String nodeName = node.getAttributeValue("id");
          String nodeType = node.getAttributeValue("name");

          /**
           * capture runtime. If not exist, by default the runtime is 0.1. Otherwise CloudSim would
           * ignore this task. BUG/#11
           */
          double runtime = 0.1;
          if (node.getAttributeValue("runtime") != null) {
            String nodeTime = node.getAttributeValue("runtime");
            runtime = 1000 * Double.parseDouble(nodeTime);
            if (runtime < 100) {
              runtime = 100;
            }
            length = (long) runtime;
          } else {
            Log.printLine("Cannot find runtime for " + nodeName + ",set it to be 0");
          }
          // multiple the scale, by default it is 1.0
          length *= Parameters.getRuntimeScale();

          List fileList = node.getChildren();

          List mFileList = new ArrayList<org.cloudbus.cloudsim.File>();

          for (Iterator itf = fileList.iterator(); itf.hasNext(); ) {
            Element file = (Element) itf.next();
            if (file.getName().toLowerCase().equals("uses")) {
              String fileName = file.getAttributeValue("name"); // DAX version 3.3
              if (fileName == null) {
                fileName = file.getAttributeValue("file"); // DAX version 3.0
              }
              if (fileName == null) {
                Log.print("Error in parsing xml");
              }

              String inout = file.getAttributeValue("link");
              double size = 0.0;

              String fileSize = file.getAttributeValue("size");
              if (fileSize != null) {
                size = Double.parseDouble(fileSize) /*/ 1024*/;
              } else {
                Log.printLine("File Size not found for " + fileName);
              }

              /** a bug of cloudsim, size 0 causes a problem. 1 is ok. */
              if (size == 0) {
                size++;
              }
              /** Sets the file type 1 is input 2 is output */
              int type = 0;
              if (inout.equals("input")) {
                type = Parameters.FileType.INPUT.value;
              } else if (inout.equals("output")) {
                type = Parameters.FileType.OUTPUT.value;
              } else {
                Log.printLine("Parsing Error");
              }
              org.cloudbus.cloudsim.File tFile;
              /*
               * Already exists an input file (forget output file)
               */
              if (size < 0) {
                /*
                 * Assuming it is a parsing error
                 */
                size = 0 - size;
                Log.printLine("Size is negative, I assume it is a parser error");
              }
              if (type == Parameters.FileType.OUTPUT.value) {
                /** It is good that CloudSim does tell whether a size is zero */
                tFile = new org.cloudbus.cloudsim.File(fileName, (int) size);
              } else if (ReplicaCatalog.containsFile(fileName)) {
                tFile = ReplicaCatalog.getFile(fileName);
              } else {

                tFile = new org.cloudbus.cloudsim.File(fileName, (int) size);
                ReplicaCatalog.setFile(fileName, tFile);
              }

              tFile.setType(type);
              mFileList.add(tFile);
            }
          }
          Task task;
          // In case of multiple workflow submission. Make sure the jobIdStartsFrom is consistent.
          synchronized (this) {
            task = new Task(this.jobIdStartsFrom, length);
            this.jobIdStartsFrom++;
          }
          task.setType(nodeType);

          task.setUserId(userId);
          mName2Task.put(nodeName, task);

          for (Iterator itm = mFileList.iterator(); itm.hasNext(); ) {
            org.cloudbus.cloudsim.File file = (org.cloudbus.cloudsim.File) itm.next();
            task.addRequiredFile(file.getName());
          }

          task.setFileList(mFileList);
          this.getTaskList().add(task);

          /** Add dependencies info. */
        } else if (node.getName().toLowerCase().equals("child")) {
          List pList = node.getChildren();
          String childName = node.getAttributeValue("ref");
          if (mName2Task.containsKey(childName)) {

            Task childTask = (Task) mName2Task.get(childName);

            for (Iterator itc = pList.iterator(); itc.hasNext(); ) {
              Element parent = (Element) itc.next();
              String parentName = parent.getAttributeValue("ref");
              if (mName2Task.containsKey(parentName)) {
                Task parentTask = (Task) mName2Task.get(parentName);
                parentTask.addChild(childTask);
                childTask.addParent(parentTask);
              }
            }
          }
        }
      }
      /** If a task has no parent, then it is root task. */
      ArrayList roots = new ArrayList<Task>();
      for (Iterator it = mName2Task.values().iterator(); it.hasNext(); ) {
        Task task = (Task) it.next();
        task.setDepth(0);
        if (task.getParentList().isEmpty()) {
          roots.add(task);
        }
      }

      /** Add depth from top to bottom. */
      for (Iterator it = roots.iterator(); it.hasNext(); ) {
        Task task = (Task) it.next();
        setDepth(task, 1);
      }
      /** Clean them so as to save memory. Parsing workflow may take much memory */
      this.mName2Task.clear();

    } catch (JDOMException jde) {
      Log.printLine("JDOM Exception;Please make sure your dax file is valid");

    } catch (IOException ioe) {
      Log.printLine("IO Exception;Please make sure dax.path is correctly set in your config file");

    } catch (Exception e) {
      e.printStackTrace();
      Log.printLine("Parsing Exception");
    }
  }