示例#1
0
 private void removeNodes(NodeList nl) {
   int count = nl.getLength();
   for (int i = 0; i < count; i++) {
     Node node = nl.item(i);
     Node parent = node.getParentNode();
     if (parent == null) continue;
     parent.removeChild(node);
   }
 }
示例#2
0
  private List<Node> getChildNodes(Node parentNode, String tagName) {
    List<Node> nodeList = new ArrayList<Node>();
    for (Node child = parentNode.getFirstChild(); child != null; child = child.getNextSibling()) {
      if (child.getNodeType() == Node.ELEMENT_NODE && tagName.equals(child.getNodeName())) {
        nodeList.add(child);
      }
    }

    return nodeList;
  }
示例#3
0
 private String getXPath(Node node, String xpath) {
   if (node == null) {
     return "";
   }
   String nodeName = node.getNodeName();
   Node parent = node.getParentNode();
   if (parent == null) {
     return xpath;
   }
   return getXPath(parent, "/" + nodeName + xpath);
 }
示例#4
0
 private void call(Node operation)
     throws ParserConfigurationException, TransformerConfigurationException {
   String opName = operation.getNodeName();
   if (opName.equals("call")) {
     String script =
         Utils.combine(Utils.getParentDir(this.currentScript), operation.getTextContent());
     call(script);
   } else if (opName.equals("apply")) processApply(operation);
   else if (opName.equals("xml")) processXml(operation);
   else if (opName.equals("txt")) processTxt(operation);
   else if (opName.equals("copy")) processCopy(operation);
   else if (opName.equals("delete")) processDelete(operation);
 }
示例#5
0
 private void setXmlEntry(Document doc, Node opSet) {
   NodeList targetNodes = findNodes(doc, opSet);
   NodeList valueNodes = getValueNodes(opSet);
   if (targetNodes == null) {
     return;
   }
   int targetNodesCount = targetNodes.getLength();
   for (int i = 0; i < targetNodesCount; i++) {
     Node target = targetNodes.item(i);
     for (Node child; (child = target.getFirstChild()) != null; target.removeChild(child)) ;
     appendNodes(doc, target, valueNodes);
   }
 }
  public Node getAppletAppNode() {
    Node node = doc.getDocumentElement();

    if (node == null) {
      Element root = doc.createElement(XmlTagNames.XML_APPLET_APP_TAG);
      Attr attr = doc.createAttribute(XmlTagNames.XML_VERSION_ATTR);
      attr.setNodeValue(XmlTagNames.XML_APPLET_APP_VERSION);
      doc.appendChild(root);
      return root;
    } else if (node.getNodeName().equals(XmlTagNames.XML_APPLET_APP_TAG)) {
      return node;
    }
    return null;
  }
示例#7
0
 private void replaceXmlEntry(Document doc, Node opReplace) {
   NodeList targetNodes = findNodes(doc, opReplace);
   NodeList valueNodes = getValueNodes(opReplace);
   if (targetNodes == null) {
     return;
   }
   int targetNodesCount = targetNodes.getLength();
   for (int i = 0; i < targetNodesCount; i++) {
     Node target = targetNodes.item(i);
     Node parent = target.getParentNode();
     if (parent == null) continue;
     parent.removeChild(target);
     appendNodes(doc, parent, valueNodes);
   }
 }
示例#8
0
  /**
   * Removes empty #text nodes from a document. From James Murty on this StackOverflow post:
   * http://stackoverflow.com/questions/978810/how-to-strip-whitespace-only-text-nodes-from-a-dom-before-serialization
   *
   * @param doc The document to remove empty text nodes from.
   */
  private static void removeEmptyTextNodes(Document doc) {
    try {
      XPathFactory xpathFactory = XPathFactory.newInstance();
      // XPath to find empty text nodes.
      XPathExpression xpathExp =
          xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']");
      NodeList emptyTextNodes = (NodeList) xpathExp.evaluate(doc, XPathConstants.NODESET);

      // Remove each empty text node from document.
      for (int i = 0; i < emptyTextNodes.getLength(); i++) {
        Node emptyTextNode = emptyTextNodes.item(i);
        emptyTextNode.getParentNode().removeChild(emptyTextNode);
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
示例#9
0
 /**
  * Gets the definitions of a word, sets the main one if necessary, and returns it.
  *
  * @param overwrite if true, then function will attempt to retrieve from online even if the
  *     definition is already set.
  * @return String containing the main definition of the word.
  */
 public static Word[] getWordsFromFile(ByteArrayInputStream inputStream) {
   try {
     // now to parse the XML
     DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
     DocumentBuilder db = dbf.newDocumentBuilder();
     Document doc = db.parse(inputStream);
     removeEmptyTextNodes(doc);
     NodeList wordList = doc.getElementsByTagName("WordDefinitions");
     int wordCount = wordList.getLength();
     Word[] returnWords = new Word[wordCount];
     for (int wordi = 0; wordi < wordCount; wordi++) {
       NodeList list = ((Element) wordList.item(wordi)).getElementsByTagName("Definition");
       Element wordElement = (Element) wordList.item(wordi);
       String word = wordElement.getAttribute("word");
       String mainDefinition = wordElement.getAttribute("mainDefinition");
       int numDefinitions = list.getLength();
       Definition[] wordOtherDefinitions = new Definition[numDefinitions];
       for (int i = 0; i < numDefinitions; i++) {
         Node node = list.item(i);
         NodeList children = node.getChildNodes(); // gets each child node of the definition
         // get all data
         String definition = children.item(XML_DEFINITION_LOC).getTextContent();
         String theWord = children.item(XML_WORD_LOC).getTextContent();
         NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes();
         String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent();
         String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent();
         // now we've got all the data lets add it to the array
         wordOtherDefinitions[i] =
             new Definition(dictionaryName, dictionaryId, definition, theWord);
       }
       if (wordOtherDefinitions.length == 0) {
         wordOtherDefinitions =
             new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)};
       }
       Word currentWord = new Word(word, mainDefinition);
       currentWord.setOtherDefinitions(wordOtherDefinitions);
       returnWords[wordi] = currentWord;
     }
     return returnWords;
   } catch (Exception ex) {
     ex.printStackTrace();
     return null;
   }
 }
示例#10
0
  private void call(String script)
      throws ParserConfigurationException, TransformerConfigurationException {
    File callerScript = this.currentScript;
    Document doc = null;
    try {
      this.currentScript = new File(script);
      DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      doc = db.parse(this.currentScript);
    } catch (Exception ex) {
      this.currentScript = callerScript;
      Utils.onError(new Error.FileParse(script));
      return;
    }

    NodeList operations = doc.getDocumentElement().getChildNodes();
    for (int i = 0; i < operations.getLength(); i++) {
      Node operation = operations.item(i);
      if (operation.getNodeType() != Node.ELEMENT_NODE) continue;
      call(operation);
    }
    this.currentScript = callerScript;
  }
示例#11
0
 /**
  * Gets the definitions of a word, sets the main one if necessary, and returns it.
  *
  * @param overwrite if true, then function will attempt to retrieve from online even if the
  *     definition is already set.
  * @return String containing the main definition of the word.
  */
 public String getDefinitions(ByteArrayInputStream inputStream, boolean overwrite) {
   if (overwrite || (definition == null || definition.isEmpty())) {
     // get definition from online service
     // if not able to access internet, then do something
     try {
       // now to parse the XML
       DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
       DocumentBuilder db = dbf.newDocumentBuilder();
       Document doc = db.parse(inputStream);
       removeEmptyTextNodes(doc);
       NodeList list = doc.getElementsByTagName("Definition");
       int numDefinitions = list.getLength();
       otherDefinitions = new Definition[numDefinitions];
       for (int i = 0; i < numDefinitions; i++) {
         Node node = list.item(i);
         NodeList children = node.getChildNodes(); // gets each child node of the definition
         // get all data
         String definition = children.item(XML_DEFINITION_LOC).getTextContent();
         String word = children.item(XML_WORD_LOC).getTextContent();
         NodeList dictionaryNode = children.item(XML_DICTIONARY_BRANCH_LOC).getChildNodes();
         String dictionaryId = dictionaryNode.item(XML_DICTIONARY_ID_LOC).getTextContent();
         String dictionaryName = dictionaryNode.item(XML_DICTIONARY_NAME_LOC).getTextContent();
         // now we've got all the data lets add it to the array
         otherDefinitions[i] = new Definition(dictionaryName, dictionaryId, definition, word);
       }
       if (otherDefinitions.length == 0) {
         otherDefinitions =
             new Definition[] {new Definition("nil", "nil", "NO DEFINITION FOUND", word)};
       }
       this.setMainDefinition(otherDefinitions[0].getDefinition());
       return otherDefinitions[0].getDefinition();
     } catch (Exception ex) {
       ex.printStackTrace();
       return "ERROR! " + ex;
     }
   } else {
     return this.definition;
   }
 }
示例#12
0
 private void processDelete(Node operation) {
   String path = absolutePath(operation.getTextContent());
   File target = new File(path);
   if (!target.exists()) {
     Utils.onError(new Error.FileNotFound(target.getPath()));
     return;
   }
   try {
     if (target.isDirectory()) {
       FileUtils.deleteDirectory(target);
     } else {
       FileUtils.forceDelete(target);
     }
   } catch (IOException ex) {
     Utils.onError(new Error.FileDelete(target.getPath()));
   }
 }
示例#13
0
  public void parseStartup(File file) {
    Logger.getLogger(com.bombdiggity.amazon.ec2.install.Installer.class)
        .info((new StringBuilder("InstallParser.parseStartup: ")).append(file).toString());
    try {
      Document doc = loadFile(file);
      if (doc != null) {
        XPathFactory factory = XMLUtils.newXPathFactory();
        XPath xpath = factory.newXPath();
        String rootXPath = "/Startup/Commands/*";
        Element root = doc.getDocumentElement();
        XPathExpression rootExp = xpath.compile(rootXPath);
        NodeList streamList = (NodeList) rootExp.evaluate(root, XPathConstants.NODESET);
        if (streamList != null) {
          for (int i = 0; i < streamList.getLength(); i++) {
            Node streamNode = streamList.item(i);
            Element streamElem = (Element) streamNode;
            if (streamElem.getNodeName().toLowerCase().equals("install")) {
              String packageName = null;
              String folderPath = null;
              for (Node child = streamNode.getFirstChild();
                  child != null;
                  child = child.getNextSibling())
                if (child.getNodeName().toLowerCase().equals("package"))
                  packageName = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("folder"))
                  folderPath = XMLUtils.getNodeValue(child).trim();

              if (packageName != null) InstallCommands.installPackage(session, packageName);
              else if (folderPath != null) InstallCommands.installFolder(session, folderPath);
              else
                Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
                    .error("StartupParser.loadFile: <Install>: <Package> or <Folder> required");
            } else if (streamElem.getNodeName().toLowerCase().equals("download")) {
              String url = null;
              String method = "get";
              String data = null;
              String destination = "/opt";
              String action = null;
              List headers = new ArrayList();
              for (Node child = streamNode.getFirstChild();
                  child != null;
                  child = child.getNextSibling())
                if (child.getNodeName().toLowerCase().equals("url"))
                  url = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("method"))
                  method = XMLUtils.getNodeValue(child).toLowerCase().trim();
                else if (child.getNodeName().toLowerCase().equals("data"))
                  data = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("destination"))
                  destination = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("action"))
                  action = XMLUtils.getNodeValue(child).toLowerCase().trim();
                else if (child.getNodeName().toLowerCase().equals("header")) {
                  Node nameNode = XMLUtils.getNodeByTagName((Element) child, "Name");
                  Node valueNode = XMLUtils.getNodeByTagName((Element) child, "Value");
                  if (nameNode != null && valueNode != null) {
                    Map namePair = new HashMap();
                    namePair.put(
                        XMLUtils.getNodeValue(nameNode).trim(),
                        XMLUtils.getNodeValue(valueNode).trim());
                    headers.add(namePair);
                  } else {
                    Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
                        .error(
                            "StartupParser.loadFile: <Download/Header>: <Name> and <Value> required");
                  }
                }

              if (url != null && destination != null)
                InstallCommands.downloadFile(
                    session, url, method, data, headers, destination, action);
              else
                Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
                    .error("StartupParser.loadFile: <Download>: <URL> and <Destination> required");
            } else if (streamElem.getNodeName().toLowerCase().equals("s3fetch")) {
              String awsAccessKeyId = null;
              String awsSecretAccessKey = null;
              String bucket = null;
              String key = null;
              String destination = null;
              String action = null;
              for (Node child = streamNode.getFirstChild();
                  child != null;
                  child = child.getNextSibling())
                if (child.getNodeName().toLowerCase().equals("awsaccesskeyid"))
                  awsAccessKeyId = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("awssecretaccesskey"))
                  awsSecretAccessKey = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("bucket"))
                  bucket = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("key"))
                  key = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("destination"))
                  destination = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("action"))
                  action = XMLUtils.getNodeValue(child).toLowerCase().trim();

              if (awsAccessKeyId != null
                  && awsSecretAccessKey != null
                  && bucket != null
                  && key != null
                  && destination != null)
                InstallCommands.fetchFile(
                    session, awsAccessKeyId, awsSecretAccessKey, bucket, key, destination, action);
              else
                Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
                    .error(
                        "StartupParser.loadFile: <Fetch>: <AWSAccessKeyId>, <AWSSecretAccessKey>, <Bucket>, <Key> and <Destination> required");
            } else if (streamElem.getNodeName().toLowerCase().equals("runscript")) {
              String script = null;
              List params = new ArrayList();
              for (Node child = streamNode.getFirstChild();
                  child != null;
                  child = child.getNextSibling())
                if (child.getNodeName().toLowerCase().equals("script"))
                  script = XMLUtils.getNodeValue(child).trim();
                else if (child.getNodeName().toLowerCase().equals("param")) {
                  String param = XMLUtils.getNodeValue(child).trim();
                  params.add(param);
                }

              if (script != null) InstallCommands.runScript(session, script, params);
              else
                Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
                    .error("StartupParser.loadFile: <RunScript>: <Script> required");
            }
          }
        }
      }
    } catch (Exception e) {
      Logger.getLogger(com.bombdiggity.amazon.ec2.install.InstallParser.class)
          .error(
              (new StringBuilder("InstallParser.parseStartup: ")).append(e.toString()).toString());
      e.printStackTrace();
    }
  }
示例#14
0
 private void appendNodes(Document doc, Node target, NodeList nodes) {
   for (int i = 0; i < nodes.getLength(); i++) {
     Node node = nodes.item(i);
     target.appendChild(doc.importNode(node, true));
   }
 }
示例#15
0
  private void processTxt(Node operation) {
    List<Node> targets = getChildNodes(operation, "target");
    List<Node> optionNodes = getChildNodes(operation, "opt");
    List<Node> separatorNode = getChildNodes(operation, "separator");
    if (targets.isEmpty() || optionNodes.isEmpty()) {
      return;
    }
    String defaultSeparator = "=";
    String globalSeparator = defaultSeparator;
    if (!separatorNode.isEmpty()) {
      globalSeparator = separatorNode.get(0).getTextContent();
      if (globalSeparator.length() != 1) {
        globalSeparator = defaultSeparator;
      }
    }
    Map<String, String> options = new HashMap<String, String>();
    Map<String, String> processedOptions = new HashMap<String, String>();
    for (int i = 0; i < optionNodes.size(); i++) {
      Node option = optionNodes.get(i);
      String name = option.getAttributes().getNamedItem("name").getNodeValue();
      String value = option.getTextContent();
      if (options.containsKey(name)) {
        options.remove(name);
      }
      options.put(name, value);
    }
    for (int t = 0; t < targets.size(); t++) {
      File target = new File(absolutePath(targets.get(t).getTextContent()));
      File tmpFile = new File(Utils.timestamp());
      BufferedWriter bw = null;
      BufferedReader br = null;
      try {
        Node separatorAttr = targets.get(t).getAttributes().getNamedItem("separator");
        String separator = (separatorAttr == null) ? globalSeparator : separatorAttr.getNodeValue();
        if (separator.length() != 1) {
          separator = globalSeparator;
        }
        bw = new BufferedWriter(new FileWriter(tmpFile));
        if (target.exists()) {
          br = new BufferedReader(new FileReader(target));
          for (String line; (line = br.readLine()) != null; ) {
            String[] parts = line.split(separator);
            if (parts.length < 2) {
              bw.write(line);
              bw.newLine();
              continue;
            }

            String optName = parts[0].trim();
            if (options.containsKey(optName)) {
              String optValue = options.get(optName);
              bw.write(optName + " " + separator + " " + optValue);
              bw.newLine();
              processedOptions.put(optName, optValue);
              options.remove(optName);
            } else if (processedOptions.containsKey(optName)) {
              bw.write(optName + " " + separator + " " + processedOptions.get(optName));
              bw.newLine();
            } else {
              bw.write(line);
              bw.newLine();
            }
          }
          br.close();
        }
        for (Map.Entry<String, String> entry : options.entrySet()) {
          bw.write(entry.getKey() + " " + separator + " " + entry.getValue());
          bw.newLine();
        }
        bw.close();
        FileUtils.copyFile(tmpFile, target);
        FileUtils.forceDelete(tmpFile);
      } catch (IOException ex) {
        Utils.onError(new Error.WriteTxtConfig(target.getPath()));
      }
    }
  }