private void initAllowedHosts(Document pDoc) {
    NodeList nodes = pDoc.getElementsByTagName("remote");
    if (nodes.getLength() == 0) {
      // No restrictions found
      allowedHostsSet = null;
      return;
    }

    allowedHostsSet = new HashSet<String>();
    for (int i = 0; i < nodes.getLength(); i++) {
      Node node = nodes.item(i);
      NodeList childs = node.getChildNodes();
      for (int j = 0; j < childs.getLength(); j++) {
        Node hostNode = childs.item(j);
        if (hostNode.getNodeType() != Node.ELEMENT_NODE) {
          continue;
        }
        assertNodeName(hostNode, "host");
        String host = hostNode.getTextContent().trim().toLowerCase();
        if (SUBNET_PATTERN.matcher(host).matches()) {
          if (allowedSubnetsSet == null) {
            allowedSubnetsSet = new HashSet<String>();
          }
          allowedSubnetsSet.add(host);
        } else {
          allowedHostsSet.add(host);
        }
      }
    }
  }
示例#2
0
文件: D4.java 项目: sarekautowerke/D4
  public List parsePage(String pageCode) {
    List sections = new ArrayList();
    List folders = new ArrayList();
    List files = new ArrayList();
    int start = pageCode.indexOf("<div id=\"list-view\" class=\"view\"");
    int end = pageCode.indexOf("<div id=\"gallery-view\" class=\"view\"");
    String usefulSection = "";
    if (start != -1 && end != -1) {
      usefulSection = pageCode.substring(start, end);
    } else {
      debug("Could not parse page");
    }
    try {
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      InputSource is = new InputSource();
      is.setCharacterStream(new StringReader(usefulSection));
      Document doc = db.parse(is);

      NodeList divs = doc.getElementsByTagName("div");
      for (int i = 0; i < divs.getLength(); i++) {
        Element div = (Element) divs.item(i);
        boolean isFolder = false;
        if (div.getAttribute("class").equals("filename")) {
          NodeList imgs = div.getElementsByTagName("img");
          for (int j = 0; j < imgs.getLength(); j++) {
            Element img = (Element) imgs.item(j);
            if (img.getAttribute("class").indexOf("folder") > 0) {
              isFolder = true;
            } else {
              isFolder = false; // it's a file
            }
          }

          NodeList anchors = div.getElementsByTagName("a");
          Element anchor = (Element) anchors.item(0);
          String attr = anchor.getAttribute("href");
          String fileName = anchor.getAttribute("title");
          String fileURL;
          if (isFolder && !attr.equals("#")) {
            folders.add(attr);
            folders.add(fileName);
          } else if (!isFolder && !attr.equals("#")) {
            // Dropbox uses ajax to get the file for download, so the url isn't enough. We must be
            // sneaky here.
            fileURL = "https://dl.dropbox.com" + attr.substring(23) + "?dl=1";
            files.add(fileURL);
            files.add(fileName);
          }
        }
      }
    } catch (Exception e) {
      debug(e.toString());
    }

    sections.add(files);
    sections.add(folders);

    return sections;
  }
 private void initMBeanSets(Document pDoc) throws MalformedObjectNameException {
   for (String tag : new String[] {"allow", "mbeans"}) {
     NodeList nodes = pDoc.getElementsByTagName(tag);
     if (nodes.getLength() > 0) {
       // "allow" and "mbeans" are synonyms
       if (allow == null) {
         allow = new MBeanPolicyConfig();
       }
       extractMbeanConfiguration(nodes, allow);
     }
   }
   NodeList nodes = pDoc.getElementsByTagName("deny");
   if (nodes.getLength() > 0) {
     deny = new MBeanPolicyConfig();
     extractMbeanConfiguration(nodes, deny);
   }
 }
示例#4
0
  /**
   * @param inputStream
   * @param session
   * @param sessionName @return
   * @throws RuntimeException
   */
  public void loadSession(InputStream inputStream, Session session, String sessionName) {

    log.debug("Load session");

    Document document = null;
    try {
      document = Utilities.createDOMDocumentFromXmlStream(inputStream);
    } catch (Exception e) {
      log.error("Load session error", e);
      throw new RuntimeException(e);
    }

    NodeList tracks = document.getElementsByTagName("Track");
    hasTrackElments = tracks.getLength() > 0;

    HashMap additionalInformation = new HashMap();
    additionalInformation.put(INPUT_FILE_KEY, sessionName);

    NodeList nodes = document.getElementsByTagName(SessionElement.GLOBAL.getText());
    if (nodes == null || nodes.getLength() == 0) {
      nodes = document.getElementsByTagName(SessionElement.SESSION.getText());
    }

    processRootNode(session, nodes.item(0), additionalInformation);

    // Add tracks not explicitly allocated to panels.  It is legal to define sessions with the
    // Resources
    // section only (no Panel or Track elements).
    addLeftoverTracks(trackDictionary.values());

    if (session.getGroupTracksBy() != null && session.getGroupTracksBy().length() > 0) {
      igv.setGroupByAttribute(session.getGroupTracksBy());
    }

    if (session.isRemoveEmptyPanels()) {
      igv.getMainPanel().removeEmptyDataPanels();
    }

    igv.resetOverlayTracks();
  }
示例#5
0
  public void handleDocument(Document document) {
    /* Tutti i nodi contenuti in document che si chiamano "NodoCella" */

    NodeList cas = document.getElementsByTagName("NodoCella");
    Element casellona = (Element) cas.item(0);

    id = casellona.getElementsByTagName("id").item(0).getTextContent();
    x = casellona.getElementsByTagName("XCOR").item(0).getTextContent();
    y = casellona.getElementsByTagName("YCOR").item(0).getTextContent();
    text = casellona.getElementsByTagName("text").item(0).getTextContent();
    down = casellona.getElementsByTagName("down").item(0).getTextContent();
    up = casellona.getElementsByTagName("up").item(0).getTextContent();
    laterale = casellona.getElementsByTagName("laterale").item(0).getTextContent();
    laterale1 = casellona.getElementsByTagName("laterale1").item(0).getTextContent();
    laterale2 = casellona.getElementsByTagName("laterale2").item(0).getTextContent();
    laterale3 = casellona.getElementsByTagName("laterale3").item(0).getTextContent();
    laterale4 = casellona.getElementsByTagName("laterale4").item(0).getTextContent();
    laterale5 = casellona.getElementsByTagName("laterale5").item(0).getTextContent();
    laterale6 = casellona.getElementsByTagName("laterale6").item(0).getTextContent();

    CasellaStart casella_start =
        new CasellaStart(
            id, text, x, y, down, up, laterale, laterale1, laterale2, laterale3, laterale4,
            laterale5, laterale6);

    GestioneCaselle.caselle.add(casella_start);

    for (int i = 0; i < cas.getLength(); i++) {
      Element casella = (Element) cas.item(i);

      id = casella.getElementsByTagName("id").item(0).getTextContent();
      x = casella.getElementsByTagName("XCOR").item(0).getTextContent();
      y = casella.getElementsByTagName("YCOR").item(0).getTextContent();
      text = casella.getElementsByTagName("text").item(0).getTextContent();
      down = casella.getElementsByTagName("down").item(0).getTextContent();
      up = casella.getElementsByTagName("up").item(0).getTextContent();
      laterale = casella.getElementsByTagName("laterale").item(0).getTextContent();

      Casella nuova_casella = new Casella(id, text, x, y, down, up, laterale);

      GestioneCaselle.caselle.add(nuova_casella);
    }
    // this.caselle.remove(1);

    casella_start.setLaterali();
  }
 // ===============================================================================
 // Parsing routines
 private void initTypeSet(Document pDoc) {
   NodeList nodes = pDoc.getElementsByTagName("commands");
   if (nodes.getLength() > 0) {
     // Leave typeSet null if no commands has been given...
     typeSet = new HashSet<JmxRequest.Type>();
   }
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     NodeList childs = node.getChildNodes();
     for (int j = 0; j < childs.getLength(); j++) {
       Node commandNode = childs.item(j);
       if (commandNode.getNodeType() != Node.ELEMENT_NODE) {
         continue;
       }
       assertNodeName(commandNode, "command");
       String typeName = commandNode.getTextContent().trim();
       JmxRequest.Type type = JmxRequest.Type.valueOf(typeName.toUpperCase());
       typeSet.add(type);
     }
   }
 }
  private static void parseXML() {
    try {
      Document doc =
          DocumentBuilderFactory.newInstance()
              .newDocumentBuilder()
              .parse(CommandBuilder.class.getResourceAsStream("/CommandMap.xml"));
      NodeList nodes = doc.getElementsByTagName("CommandMap");
      for (int i = 0; i < nodes.getLength(); i++) {
        Node n = nodes.item(i);

        NamedNodeMap atts = n.getAttributes();
        String rootCommand = atts.getNamedItem("rootCommand").getNodeValue();
        rootNode = new Category(rootCommand, "");

        NodeList children = n.getChildNodes();
        for (int p = 0; p < children.getLength(); p++) {
          parseNode(children.item(p), rootNode);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#8
0
文件: D4.java 项目: sarekautowerke/D4
 public String getFolderName(String pageCode) {
   String usefulSection =
       pageCode.substring(
           pageCode.indexOf("<h3 id=\"breadcrumb\">"),
           pageCode.indexOf("<div id=\"list-view\" class=\"view\""));
   String folderName;
   try {
     DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
     InputSource is = new InputSource();
     is.setCharacterStream(new StringReader(usefulSection));
     Document doc = db.parse(is);
     NodeList divs = doc.getElementsByTagName("h3");
     for (int i = 0; i < divs.getLength(); i++) {
       Element div = (Element) divs.item(i);
       String a = div.getTextContent();
       folderName = a.substring(a.indexOf("/>") + 2).trim();
       return folderName;
     }
   } catch (Exception e) {
     debug(e.toString());
   }
   return "Error!";
 }
 private void initHttpMethodSet(Document pDoc) {
   NodeList nodes = pDoc.getElementsByTagName("http");
   if (nodes.getLength() > 0) {
     // Leave typeSet null if no commands has been given...
     httpMethodsSet = new HashSet<String>();
   }
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     NodeList childs = node.getChildNodes();
     for (int j = 0; j < childs.getLength(); j++) {
       Node commandNode = childs.item(j);
       if (commandNode.getNodeType() != Node.ELEMENT_NODE) {
         continue;
       }
       assertNodeName(commandNode, "method");
       String methodName = commandNode.getTextContent().trim().toLowerCase();
       if (!methodName.equals("post") || methodName.equals("get")) {
         throw new SecurityException(
             "HTTP method must be either GET or POST, but not " + methodName);
       }
       httpMethodsSet.add(methodName);
     }
   }
 }
示例#10
0
  /**
   * XML Circuit constructor
   *
   * @param file the file that contains the XML description of the circuit
   * @param g the graphics that will paint the node
   * @throws CircuitLoadingException if the internal circuit can not be loaded
   */
  public CircuitUI(File file, Graphics g) throws CircuitLoadingException {
    this("");

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;
    Document doc;
    Element root;

    Hashtable<Integer, Link> linkstable = new Hashtable<Integer, Link>();

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.parse(file);
    } catch (SAXException sxe) {
      throw new CircuitLoadingException("SAX exception raised, invalid XML file.");
    } catch (ParserConfigurationException pce) {
      throw new CircuitLoadingException(
          "Parser exception raised, parser configuration is invalid.");
    } catch (IOException ioe) {
      throw new CircuitLoadingException("I/O exception, file cannot be loaded.");
    }

    root = (Element) doc.getElementsByTagName("Circuit").item(0);
    this.setName(root.getAttribute("name"));

    NodeList nl = root.getElementsByTagName("Node");
    Element e;
    Node n;
    Class cl;

    for (int i = 0; i < nl.getLength(); ++i) {
      e = (Element) nl.item(i);

      try {
        cl = Class.forName(e.getAttribute("class"));
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      try {
        n = ((Node) cl.newInstance());
      } catch (Exception exc) {
        System.err.println(exc.getMessage());
        throw new RuntimeException("Circuit creation from xml.");
      }

      this.nodes.add(n);
      n.setLocation(new Integer(e.getAttribute("x")), new Integer(e.getAttribute("y")));

      if (n instanceof giraffe.ui.Nameable) ((Nameable) n).setNodeName(e.getAttribute("node_name"));

      if (n instanceof giraffe.ui.CompositeNode) {
        try {
          ((CompositeNode) n)
              .load(new File(file.getParent() + "/" + e.getAttribute("file_name")), g);
        } catch (Exception exc) {
          /* try to load from the lib */
          ((CompositeNode) n)
              .load(new File(giraffe.Giraffe.PATH + "/lib/" + e.getAttribute("file_name")), g);
        }
      }

      NodeList nlist = e.getElementsByTagName("Anchor");
      Element el;

      for (int j = 0; j < nlist.getLength(); ++j) {
        el = (Element) nlist.item(j);

        Anchor a = n.getAnchor(new Integer(el.getAttribute("id")));
        NodeList linklist = el.getElementsByTagName("Link");
        Element link;
        Link l;

        for (int k = 0; k < linklist.getLength(); ++k) {
          link = (Element) linklist.item(k);
          int id = new Integer(link.getAttribute("id"));
          int index = new Integer(link.getAttribute("index"));

          if (id >= this.linkID) linkID = id + 1;

          if (linkstable.containsKey(id)) {
            l = linkstable.get(id);
            l.addLinkedAnchorAt(a, index);
            a.addLink(l);
          } else {
            l = new Link(id);
            l.addLinkedAnchorAt(a, index);
            this.links.add(l);
            linkstable.put(id, l);
            a.addLink(l);
          }
        }
      }
    }
  }
示例#11
0
  // -----------------------------------------------------
  // Description: Using the specified template, create
  // csv records corresponding to the output xml criteria.
  // -----------------------------------------------------
  void transformWithTemplate(String templateName, String fileName, String destinationDirectory) {

    System.out.println("fileName = " + fileName);
    String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.'));

    try {
      File fXmlFile = new File(templateLocation, templateName);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
      NodeList nList = doc.getElementsByTagName("output");

      // loop through all the output nodes
      for (int temp = 0; temp < nList.getLength(); temp++) {

        Node nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;
          String outputLine = getTagValue("line", eElement);

          FileWriter output =
              new FileWriter(
                  destinationDirectory
                      + File.separator
                      + fileName_woext.substring(0, fileName.lastIndexOf('_'))
                      + ".csv",
                  true);
          BufferedWriter bufWrite = new BufferedWriter(output);

          System.out.println(
              destinationDirectory
                  + File.separator
                  + fileName_woext.substring(0, fileName.lastIndexOf("_"))
                  + ".csv");

          if (Settings.optionalIdentifier != null) {
            bufWrite.write("\"" + Settings.optionalIdentifier + "\"");
          }

          String[] outputItems = outputLine.split("#");
          for (String outputItem : outputItems) {
            if ((temp == 0) && (Settings.optionalIdentifier == null)) {
              bufWrite.write(
                  "\"" + interpretText(destinationDirectory, fileName_woext, outputItem) + "\"");
            } else {
              bufWrite.write(
                  ",\"" + interpretText(destinationDirectory, fileName_woext, outputItem) + "\"");
            }
          }

          bufWrite.write("\r\n");
          bufWrite.close();
          output.close();
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#12
0
  // -----------------------------------------------------
  // Description: Using the specified template, extract
  // the template sections into PNG and TXT corresponding
  // parts.
  // -----------------------------------------------------
  void extractWithTemplate(String templateName, String fileName, String destinationDirectory) {

    // from template
    int intOriginX = 0;
    int intOriginY = 0;

    // from template
    int intX = 0;
    int intY = 0;
    int intWidth = 0;
    int intHeight = 0;

    // calculated
    int viaTemplateX = 0;
    int viaTemplateY = 0;
    int viaTemplatePlusWidth = 0;
    int viaTemplatePlusHeight = 0;

    System.out.println("fileName = " + fileName);
    String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.'));
    String pathPlusFileName_woext =
        destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext;
    System.out.println("pathPlusFileName_woext = " + pathPlusFileName_woext);

    try {

      File fXmlFile = new File(templateLocation, templateName);
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      System.out.println("Root element :" + doc.getDocumentElement().getNodeName());

      NodeList nList = doc.getElementsByTagName("section");

      Node nNode;
      for (int temp = 0; temp < nList.getLength(); temp++) {

        nNode = nList.item(temp);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {

          Element eElement = (Element) nNode;

          String myX = getTagValue("x", eElement);
          String myY = getTagValue("y", eElement);
          String myWidth = getTagValue("width", eElement);
          String myHeight = getTagValue("height", eElement);
          String mySuffix = getTagValue("suffix", eElement);

          intX = Integer.parseInt(myX);
          intY = Integer.parseInt(myY);
          intWidth = Integer.parseInt(myWidth);
          intHeight = Integer.parseInt(myHeight);

          viaTemplateX = intX - (intOriginX - pageX);
          viaTemplateY = intY - (intOriginY - pageY);
          viaTemplatePlusWidth = viaTemplateX + intWidth;
          viaTemplatePlusHeight = viaTemplateY + intHeight;

          Spawn.execute(
              Settings.Programs.CONVERT.path(),
              pathPlusFileName_woext + "_trim.png",
              "-crop",
              String.format("%dx%d+%d+%d", intWidth, intHeight, viaTemplateX, viaTemplateY),
              "+repage",
              pathPlusFileName_woext + "_" + mySuffix + ".png");
          Spawn.execute(
              Settings.Programs.CONVERT.path(),
              pathPlusFileName_woext + "_trim.png",
              "-fill",
              "none",
              "-stroke",
              "red",
              "-strokewidth",
              "3",
              "-draw",
              String.format(
                  "rectangle %d,%d %d,%d",
                  viaTemplateX, viaTemplateY, viaTemplatePlusWidth, viaTemplatePlusHeight),
              "+repage",
              pathPlusFileName_woext + "_draw.png");
          Spawn.execute(
              Settings.Programs.TESSERACT.path(),
              pathPlusFileName_woext + "_" + mySuffix + ".png",
              pathPlusFileName_woext + "_" + mySuffix);
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#13
0
  // -----------------------------------------------------
  // Description: Determine if a template exists for the
  // given file and return true on success.
  // -----------------------------------------------------
  boolean templateExistFor(String fileName, String destinationDirectory) {

    templateIdentified = false;

    // from template
    int intOriginX = 0;
    int intOriginY = 0;

    // from template
    int intX = 0;
    int intY = 0;
    int intWidth = 0;
    int intHeight = 0;

    // calculated
    int viaTemplateX = 0;
    int viaTemplateY = 0;
    int viaTemplatePlusWidth = 0;
    int viaTemplatePlusHeight = 0;

    String fileName_woext = fileName.substring(0, fileName.lastIndexOf('.'));
    String pathPlusFileName_woext =
        destinationDirectory + File.separator + fileName_woext + File.separator + fileName_woext;

    try {

      File folder = new File(templateLocation);
      File[] listOfFiles = folder.listFiles();

      long startTime = System.currentTimeMillis();

      for (File file : listOfFiles) {

        if (file.isFile()) {

          templateName = "";

          DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
          DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
          Document doc = dBuilder.parse(file);
          doc.getDocumentElement().normalize();

          System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
          NodeList nList = doc.getElementsByTagName("condition");

          for (int temp = 0; temp < nList.getLength(); temp++) {

            Node nNode = nList.item(temp);
            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

              Element eElement = (Element) nNode;

              String myX = getTagValue("x", eElement);
              String myY = getTagValue("y", eElement);
              String myWidth = getTagValue("width", eElement);
              String myHeight = getTagValue("height", eElement);
              String mySuffix = getTagValue("suffix", eElement);
              String myRequirements = getTagValue("required", eElement);

              intX = Integer.parseInt(myX);
              intY = Integer.parseInt(myY);
              intWidth = Integer.parseInt(myWidth);
              intHeight = Integer.parseInt(myHeight);

              viaTemplateX = intX - (intOriginX - pageX);
              viaTemplateY = intY - (intOriginY - pageY);
              viaTemplatePlusWidth = viaTemplateX + intWidth;
              viaTemplatePlusHeight = viaTemplateY + intHeight;

              Spawn.execute(
                  Settings.Programs.CONVERT.path(),
                  pathPlusFileName_woext + "_trim.png",
                  "-crop",
                  String.format("%dx%d+%d+%d", intWidth, intHeight, viaTemplateX, viaTemplateY),
                  "+repage",
                  pathPlusFileName_woext + "_" + mySuffix + ".png");
              Spawn.execute(
                  Settings.Programs.CONVERT.path(),
                  pathPlusFileName_woext + "_trim.png",
                  "-fill",
                  "none",
                  "-stroke",
                  "red",
                  "-strokewidth",
                  "3",
                  "-draw",
                  String.format(
                      "rectangle %d,%d %d,%d",
                      viaTemplateX, viaTemplateY, viaTemplatePlusWidth, viaTemplatePlusHeight),
                  "+repage",
                  pathPlusFileName_woext + "_draw.png");
              Spawn.execute(
                  Settings.Programs.TESSERACT.path(),
                  pathPlusFileName_woext + "_" + mySuffix + ".png",
                  pathPlusFileName_woext + "_" + mySuffix);

              String line = ""; // String that holds current file line
              String accumulate = "";

              try {
                FileReader input = new FileReader(pathPlusFileName_woext + "_" + mySuffix + ".txt");
                BufferedReader bufRead = new BufferedReader(input);

                line = bufRead.readLine();

                while (line != null) {
                  accumulate += line;
                  line = bufRead.readLine();
                }

                bufRead.close();
                input.close();

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

              String[] requirements = myRequirements.split("#");
              for (String requirement : requirements) {
                if (requirement.equals(accumulate.trim())) {
                  templateName = file.getName();
                  templateIdentified = true;
                  return templateIdentified;
                }
              }
            }
          }
        }
      }

      // record end time
      long endTime = System.currentTimeMillis();
      System.out.println(
          "Template Search [" + fileName + "] " + (endTime - startTime) / 1000 + " seconds");

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

    return templateIdentified;
  }
  public boolean runTest(Test test) throws Exception {
    String filename = test.file.toString();
    if (this.verbose) {
      System.out.println(
          "Running "
              + filename
              + " against "
              + this.host
              + ":"
              + this.port
              + " with "
              + this.browser);
    }
    this.document = parseDocument(filename);

    if (this.baseUrl == null) {
      NodeList links = this.document.getElementsByTagName("link");
      if (links.getLength() != 0) {
        Element link = (Element) links.item(0);
        setBaseUrl(link.getAttribute("href"));
      }
    }
    if (this.verbose) {
      System.out.println("Base URL=" + this.baseUrl);
    }

    Node body = this.document.getElementsByTagName("body").item(0);
    Element resultContainer = document.createElement("div");
    resultContainer.setTextContent("Result: ");
    Element resultElt = document.createElement("span");
    resultElt.setAttribute("id", "result");
    resultElt.setIdAttribute("id", true);
    resultContainer.appendChild(resultElt);
    body.insertBefore(resultContainer, body.getFirstChild());

    Element executionLogContainer = document.createElement("div");
    executionLogContainer.setTextContent("Execution Log:");
    Element executionLog = document.createElement("div");
    executionLog.setAttribute("id", "log");
    executionLog.setIdAttribute("id", true);
    executionLog.setAttribute("style", "white-space: pre;");
    executionLogContainer.appendChild(executionLog);
    body.appendChild(executionLogContainer);

    NodeList tableRows = document.getElementsByTagName("tr");
    Element theadRow = (Element) tableRows.item(0);
    test.name = theadRow.getTextContent();
    appendCellToRow(theadRow, "Result");

    this.commandProcessor =
        new HtmlCommandProcessor(this.host, this.port, this.browser, this.baseUrl);
    String resultState;
    String resultLog;
    test.result = true;
    try {
      this.commandProcessor.start();
      test.commands = new Command[tableRows.getLength() - 1];
      for (int i = 1; i < tableRows.getLength(); i++) {
        Element stepRow = (Element) tableRows.item(i);
        Command command = executeStep(stepRow);
        appendCellToRow(stepRow, command.result);
        test.commands[i - 1] = command;
        if (command.error) {
          test.result = false;
        }
        if (command.failure) {
          test.result = false;
          // break;
        }
      }
      resultState = test.result ? "PASSED" : "FAILED";
      resultLog = (test.result ? "Test Complete" : "Error");
      this.commandProcessor.stop();
    } catch (Exception e) {
      test.result = false;
      resultState = "ERROR";
      resultLog = "Failed to initialize session\n" + e;
      e.printStackTrace();
    }
    document.getElementById("result").setTextContent(resultState);
    Element log = document.getElementById("log");
    log.setTextContent(log.getTextContent() + resultLog + "\n");
    return test.result;
  }
示例#15
0
  public static void main(String[] args) {
    String specloc = System.getProperty("spec");
    if (specloc == null) {
      System.out.print("No spec file given, quitting");
      System.exit(0);
    }

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss z");
    java.util.Date date = new java.util.Date();
    String startstamp = dateFormat.format(date);

    boolean firstrun = true;

    while (true) {
      System.out.println("Loading XML Spec file: " + specloc);
      // BufferedWriter out = null;
      SocketAcceptor acceptor = null;
      SocketAcceptor statusacceptor = null;

      Vector<MonitorThread> monitorlist = new Vector<MonitorThread>();
      try {
        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
        Document doc = docBuilder.parse(new File(specloc));

        doc.getDocumentElement().normalize();
        String heartbeatportString = doc.getDocumentElement().getAttribute("heartbeatport");
        String statusportString = doc.getDocumentElement().getAttribute("statusport");
        String logfiledir = doc.getDocumentElement().getAttribute("logfiledir");
        String masterlabel = doc.getDocumentElement().getAttribute("label");
        String nodeid = doc.getDocumentElement().getAttribute("id");
        String smtphost = doc.getDocumentElement().getAttribute("smtphost");
        String l1mailto = doc.getDocumentElement().getAttribute("l1mailto");
        String l2mailto = doc.getDocumentElement().getAttribute("l2mailto");
        String l2threshold = doc.getDocumentElement().getAttribute("l2threshold");

        if (heartbeatportString == null || heartbeatportString.equals("")) {
          System.out.println("No heartbeat specified in spec, quitting");
          System.exit(0);
        }
        if (statusportString == null || statusportString.equals("")) {
          System.out.println("No status port specified in spec, quitting");
          System.exit(0);
        }
        if (logfiledir == null || logfiledir.equals("")) {
          System.out.println("No logfile directory location specified in spec, quitting");
          System.exit(0);
        }

        int heartbeatport = Integer.valueOf(heartbeatportString).intValue();
        System.out.println("This Monitor is using port " + heartbeatport + " for heartbeat");

        int statusport = Integer.valueOf(statusportString).intValue();
        System.out.println("This Monitor is using port " + statusport + " for status updates");

        System.out.println("Logging to directory " + logfiledir);
        Log log = new Log(logfiledir);
        log.nodelabel = masterlabel;
        log.setMailer(smtphost, l1mailto, l2mailto, convertStringToInt(l2threshold));

        if (firstrun) {
          firstrun = false;
          log.logit("Monitor Node Started", "start", null);
        }
        log.logit("Logging started", "", null);

        ThreadPing threadping = new ThreadPing(log, false);
        Thread pinger = new Thread(threadping);
        threadping.thisThread = pinger;
        pinger.start();
        log.pinger = threadping;

        // ShutdownHook hook = new ShutdownHook(out);
        // Runtime.getRuntime().addShutdownHook(hook);

        // Starting Heartbeat server

        acceptor = new NioSocketAcceptor();
        acceptor.getSessionConfig().setReuseAddress(true);
        acceptor.getSessionConfig().setTcpNoDelay(true);
        acceptor.setReuseAddress(true);
        // acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor
            .getFilterChain()
            .addLast(
                "codec",
                new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        acceptor.setReuseAddress(true);
        // acceptor.setCloseOnDeactivation(true);
        acceptor.getSessionConfig().setTcpNoDelay(true);

        acceptor.setDefaultLocalAddress(new InetSocketAddress(heartbeatport));
        Vector<IoSession> sessionlist = new Vector<IoSession>();
        acceptor.setHandler(new HeartBeatHandler(sessionlist));
        acceptor.bind();

        // Starting Path Monitoring
        NodeList listOfServers = doc.getElementsByTagName("check");
        int totalServers = listOfServers.getLength();
        System.out.println("Total # of checks: " + totalServers);

        // Vector<PingMonitorThread> pinglist = new Vector<PingMonitorThread>();
        // Vector<PortMonitorThread> portlist = new Vector<PortMonitorThread>();
        // Vector<HeartbeatMonitorThread> heartbeatlist = new Vector<HeartbeatMonitorThread>();

        System.out.println();
        for (int i = 0; i < totalServers; i++) {
          Node serverNode = listOfServers.item(i);

          Element serverNodeElement = (Element) serverNode;
          String checklabel = serverNodeElement.getAttribute("label");
          String host =
              serverNodeElement
                  .getElementsByTagName("host")
                  .item(0)
                  .getChildNodes()
                  .item(0)
                  .getNodeValue();
          String checktype =
              serverNodeElement
                  .getElementsByTagName("checktype")
                  .item(0)
                  .getChildNodes()
                  .item(0)
                  .getNodeValue();
          boolean enabled = true;
          if (serverNodeElement.getElementsByTagName("enabled").item(0) != null
              && serverNodeElement
                  .getElementsByTagName("enabled")
                  .item(0)
                  .getChildNodes()
                  .item(0)
                  .getNodeValue()
                  .toLowerCase()
                  .equals("false")) {
            enabled = false;
          }
          String successrateString =
              serverNodeElement
                  .getElementsByTagName("successrate")
                  .item(0)
                  .getChildNodes()
                  .item(0)
                  .getNodeValue();
          String retryrateString =
              serverNodeElement
                  .getElementsByTagName("retryrate")
                  .item(0)
                  .getChildNodes()
                  .item(0)
                  .getNodeValue();
          // String l2thresholdoverride =
          // serverNodeElement.getElementsByTagName("l2threshold").item(0).getChildNodes().item(0).getNodeValue();
          String l2thresholdoverride = getElementValue("l2threshold", serverNodeElement);
          // String l1mailtoadd =
          // serverNodeElement.getElementsByTagName("l1mailto").item(0).getChildNodes().item(0).getNodeValue();
          String l1mailtoadd = getElementValue("l1mailto", serverNodeElement);
          // String l2mailtoadd =
          // serverNodeElement.getElementsByTagName("l2mailto").item(0).getChildNodes().item(0).getNodeValue();
          String l2mailtoadd = getElementValue("l2mailto", serverNodeElement);

          int l2thresholdoverrideint = convertStringToInt(l2thresholdoverride);
          String[] l1mailtoaddarray = new String[0];
          String[] l2mailtoaddarray = new String[0];
          if (!l1mailtoadd.equals("")) {
            l1mailtoaddarray = l1mailtoadd.split(",");
          }
          if (!l2mailtoadd.equals("")) {
            l2mailtoaddarray = l2mailtoadd.split(",");
          }

          // System.out.println(l1mailtoaddarray.length + "-" + l2mailtoaddarray.length);

          int successrate = 30;
          int retryrate = 30;
          if (host == null || host.equals("")) {
            System.out.println("No Host, skipping this path");
            enabled = false;
          }

          if (successrateString == null || successrateString.equals("")) {
            System.out.println(
                "No Success Rate defined, using default (" + successrate + " seconds)");
          } else {
            successrate = Integer.valueOf(successrateString).intValue();
          }

          if (retryrateString == null || retryrateString.equals("")) {
            System.out.println("No retry rate defined, using default (" + retryrate + " seconds)");
          } else {
            retryrate = Integer.valueOf(retryrateString).intValue();
          }

          System.out.println(checklabel);

          if (checktype.equals("heartbeat")) {
            String portString =
                serverNodeElement
                    .getElementsByTagName("port")
                    .item(0)
                    .getChildNodes()
                    .item(0)
                    .getNodeValue();

            if (portString == null || portString.equals("")) {
              System.out.println("No Heartbeat, skipping this path");
            } else {
              int heartbeat = Integer.valueOf(portString).intValue();
              System.out.println("Starting Heartbeat Check:");
              System.out.println("Host: " + host);
              System.out.println("Port: " + heartbeat);
              System.out.println();
              HeartbeatMonitorThread m =
                  new HeartbeatMonitorThread(
                      host, heartbeat, log, successrate, retryrate, checklabel);
              m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray);
              Thread t = new Thread(m);
              m.thisthread = t;
              if (enabled) {
                t.start();
                log.logit(
                    "Starting Heartbeat Check - " + host + ":" + heartbeat,
                    "enable-" + successrate + "-" + retryrate,
                    m.getStatus());
              } else {
                log.logit(
                    "Heartbeat Check - " + host + ":" + heartbeat + " Disabled on start",
                    "disable",
                    m.getStatus());
              }
              monitorlist.add(m);
            }
          } else if (checktype.equals("ping")) {
            System.out.println("Starting Ping Check:");
            System.out.println("Host: " + host);
            System.out.println();
            PingMonitorThread m =
                new PingMonitorThread(host, log, successrate, retryrate, checklabel);
            m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray);
            Thread t = new Thread(m);
            m.thisthread = t;
            if (enabled) {
              t.start();
              log.logit(
                  "Starting Ping Check - " + host,
                  "enable-" + successrate + "-" + retryrate,
                  m.getStatus());
            } else {
              log.logit("Ping Check - " + host + " Disabled on start", "disable", m.getStatus());
            }
            monitorlist.add(m);
          } else if (checktype.equals("port")) {
            String portString =
                serverNodeElement
                    .getElementsByTagName("port")
                    .item(0)
                    .getChildNodes()
                    .item(0)
                    .getNodeValue();

            if (portString == null || portString.equals("")) {
              System.out.println("No Port Given, skipping");
            } else {
              int heartbeat = Integer.valueOf(portString).intValue();
              System.out.println("Starting Port Check:");
              System.out.println("Host: " + host);
              System.out.println("Port: " + heartbeat);
              System.out.println();

              PortMonitorThread m =
                  new PortMonitorThread(host, heartbeat, log, successrate, retryrate, checklabel);
              m.setAlertOverride(l2thresholdoverrideint, l1mailtoaddarray, l2mailtoaddarray);
              Thread t = new Thread(m);
              m.thisthread = t;
              if (enabled) {
                t.start();
                log.logit(
                    "Starting Port Check - " + host + ":" + heartbeat,
                    "enable-" + successrate + "-" + retryrate,
                    m.getStatus());
              } else {
                log.logit(
                    "Port Check - " + host + ":" + heartbeat + " Disabled on start",
                    "disable",
                    m.getStatus());
              }
              monitorlist.add(m);
            }
          }
        }

        statusacceptor = new NioSocketAcceptor();
        statusacceptor.setReuseAddress(true);
        // statusacceptor.getFilterChain().addLast("logger", new LoggingFilter());
        statusacceptor.getSessionConfig().setTcpNoDelay(true);
        statusacceptor.getSessionConfig().setKeepAlive(true);
        statusacceptor.getSessionConfig().setBothIdleTime(5);
        statusacceptor.getSessionConfig().setReaderIdleTime(5);
        statusacceptor.getSessionConfig().setWriteTimeout(5);
        // statusacceptor.setReuseAddress(true);
        statusacceptor.setCloseOnDeactivation(true);
        statusacceptor.setDefaultLocalAddress(new InetSocketAddress(statusport));
        statusacceptor.setHandler(
            new StatusHttpProtocolHandler(
                monitorlist,
                acceptor,
                statusacceptor,
                log,
                masterlabel,
                nodeid,
                sessionlist,
                startstamp));
        statusacceptor.bind();

        System.out.println("Status Listener activated...");
      } catch (Exception e) {
        e.printStackTrace();
        try {
          // out.flush();
          // out.close();
        } catch (Exception e2) {
        }

        try {
          Thread.sleep(30000);
        } catch (Exception e3) {
        }
      }

      for (int x = 0; x < monitorlist.size(); x++) {
        if (monitorlist.get(x).getThisThread() != null) {
          try {
            monitorlist.get(x).getThisThread().join();
          } catch (Exception e) {
          }
        }
      }

      if (acceptor != null) {
        while (acceptor.isActive() || !acceptor.isDisposed()) {
          try {
            Thread.sleep(1000);
          } catch (Exception e) {
          }
        }
      }

      if (statusacceptor != null) {
        while (statusacceptor.isActive() || !statusacceptor.isDisposed()) {
          try {
            Thread.sleep(1000);
          } catch (Exception e) {
          }
        }
      }
      System.out.println("Main thread has reached end, reloading...");
      /*
      try
      {
      	Thread.sleep(9999999);
      }
      catch (Exception e)
      {
      	e.printStackTrace();
      }
      */
    }
  }