Exemplo n.º 1
0
  public static void vol(int issue_length, NodeList issue_node) {
    for (int i = 0; i < issue_length; i++) {
      Node nnode = issue_node.item(i);
      if (nnode.getNodeType() == Element.ELEMENT_NODE) {
        Element enode = (Element) nnode;

        NodeList article_node = enode.getElementsByTagName("article");
        int article_length = enode.getElementsByTagName("article").getLength();

        for (int j = 0; j < article_length; j++) {
          Node m = article_node.item(j);
          if (m.getNodeType() == Element.ELEMENT_NODE) {
            Element f = (Element) m;
            String title = f.getElementsByTagName("title").item(0).getTextContent();
            // System.out.println(title);
            if (title.equals("Research in Knowledge Base Management Systems.")) {
              // String article = f.getElementsByTagName("title").item(0).getTextContent();
              String endPage = f.getElementsByTagName("endPage").item(0).getTextContent();
              String initPage = f.getElementsByTagName("initPage").item(0).getTextContent();
              String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent();
              String num_element = enode.getElementsByTagName("number").item(0).getTextContent();
              // System.out.println("Title: "+ title);
              System.out.println("Volume: " + vol_element);
              System.out.println("Number: " + num_element);
              System.out.println("Init Page: " + initPage);
              System.out.println("End Page: " + endPage);
            }
          }
        }
      }
    }
  }
Exemplo n.º 2
0
  /**
   * Constructor
   *
   * @param filename the XML config file
   */
  public LdapConfig(String filename) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document document = builder.parse(filename);

    // -- root element
    Node node = document.getFirstChild();
    while (node != null && node.getNodeType() != Node.ELEMENT_NODE) node = node.getNextSibling();

    if (node == null || !node.getNodeName().equals("ldap"))
      throw new Exception("root element is different from 'ldap'");

    this.ldapUrl = node.getAttributes().getNamedItem("url").getNodeValue();

    node = node.getFirstChild();
    while (node != null) {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNodeName().equals("authentication")) handleAuthentication(node);
        else if (node.getNodeName().equals("plugins")) handlePlugins(node);
        else if (node.getNodeName().equals("services")) handleServices(node);
        else if (node.getNodeName().equals("users")) handleUsers(node);
        else if (node.getNodeName().equals("groups")) handleGroups(node);
        else Logging.getLogger().warning("unexepected node : " + node.getNodeName());
      }
      node = node.getNextSibling();
    }
  }
Exemplo n.º 3
0
  public static void main(String[] args) {
    System.out.println("--------Part 1-------------------------------");
    Document xmlDoc = getDocument("SigmodRecord.xml");
    int issue_length = xmlDoc.getElementsByTagName("issue").getLength();
    NodeList issue_node = xmlDoc.getElementsByTagName("issue");

    for (int i = 0; i < issue_length; i++) {
      Node nnode = issue_node.item(i);
      if (nnode.getNodeType() == Element.ELEMENT_NODE) {
        Element enode = (Element) nnode;
        String vol_element = enode.getElementsByTagName("volume").item(0).getTextContent();
        String num_element = enode.getElementsByTagName("number").item(0).getTextContent();
        if (vol_element.equals("13") && num_element.equals("4")) {
          NodeList article_node = xmlDoc.getElementsByTagName("article");
          int article_length = xmlDoc.getElementsByTagName("article").getLength();
          for (int j = 0; j < article_length; j++) {
            Node m = article_node.item(j);
            if (m.getNodeType() == Element.ELEMENT_NODE) {
              Element f = (Element) m;
              String auth = f.getElementsByTagName("author").item(0).getTextContent();
              if (auth.equals("David Maier")) {
                String title = f.getElementsByTagName("title").item(0).getTextContent();
                System.out.println("Title: " + title);
              }
            }
          }
        }
      }
    }
    // Part 2 of the Program (Print the author names off all articles whose title contains the word
    // "database" or "Database".)
    System.out.println("--------Part 2------------------------------- ");
    NodeList article_node = xmlDoc.getElementsByTagName("article");
    int article_length = xmlDoc.getElementsByTagName("article").getLength();
    for (int j = 0; j < article_length; j++) {
      Node m = article_node.item(j);
      if (m.getNodeType() == Element.ELEMENT_NODE) {
        Element f = (Element) m;
        String article = f.getElementsByTagName("title").item(0).getTextContent();
        if (article.contains("Database") || article.contains("database")) {
          int length = f.getElementsByTagName("author").getLength();
          for (int i = 0; i < length; i++) {
            String auth = f.getElementsByTagName("author").item(i).getTextContent();
            System.out.println("Author: " + auth);
          }
        }
      }
    }
    // Part 3 of the Program (Print the volume/number and the init/end pages of the article titled
    // "Research in Knowledge Base Management Systems.".)
    System.out.println("--------Part 3------------------------------- ");
    vol(issue_length, issue_node);
  }
Exemplo n.º 4
0
  // Lee la configuracion que se encuentra en conf/RegistryConf
  private void readConfXml() {
    try {
      File inputFile = new File("src/java/Conf/RegistryConf.xml");
      DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
      Document doc = dBuilder.parse(inputFile);
      doc.getDocumentElement().normalize();
      NodeList nList = doc.getElementsByTagName("RegistryConf");
      for (int i = 0; i < nList.getLength(); i++) {
        Node nNode = nList.item(i);
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
          Element eElement = (Element) nNode;
          RegistryConf reg = new RegistryConf();
          String aux;
          int idSensor;
          int value;
          aux = eElement.getElementsByTagName("idSensor").item(0).getTextContent();
          idSensor = Integer.parseInt(aux);
          reg.setIdSensor(idSensor);

          aux = eElement.getElementsByTagName("saveType").item(0).getTextContent();
          reg.setSaveTypeString(aux);

          aux = eElement.getElementsByTagName("value").item(0).getTextContent();
          value = Integer.parseInt(aux);
          reg.setValue(value);

          registryConf.add(reg);
          lastRead.put(idSensor, 0);
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  // Gets the specified XML Schema doc if one is mentioned in the file
  public static File getSchemaFile(Document xmlDoc) {
    /** @todo Must be an easier way of doing this... */
    logger.logComment("Getting schema file for: " + xmlDoc.getDocumentURI());

    NodeList nl = xmlDoc.getChildNodes();
    for (int j = 0; j < nl.getLength(); j++) {
      Node node = nl.item(j);
      logger.logComment("Type: " + node.getNodeType() + "Name: " + node.getNodeName());
      if (node.getNodeName().equals(XML_STYLESHEET_NODE)) {
        String nodeVal = node.getNodeValue();

        logger.logComment("Looking at: " + nodeVal);
        String xslFileName =
            nodeVal.substring(nodeVal.indexOf("href=\"") + 6, nodeVal.length() - 1);
        File xslFile = new File(xslFileName);
        return xslFile;
      }

      if (node.getAttributes().getLength() > 0) {
        logger.logComment("Attributes: " + node.getAttributes());
        if (node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR) != null) {
          String locString = node.getAttributes().getNamedItem(XML_SCHEMA_LOC_ATTR).getNodeValue();
          logger.logComment("Loc string: " + locString);
          String file = locString.split("\\s")[1];
          return new File(file);
        }
      }
    }
    logger.logError("No node found with name: " + XML_STYLESHEET_NODE);
    return null;
  }
Exemplo n.º 6
0
 /* return the value of the XML text node (never null) */
 protected static String GetNodeText(Node root) {
   StringBuffer sb = new StringBuffer();
   if (root != null) {
     NodeList list = root.getChildNodes();
     for (int i = 0; i < list.getLength(); i++) {
       Node n = list.item(i);
       if (n.getNodeType() == Node.CDATA_SECTION_NODE) { // CDATA Section
         sb.append(n.getNodeValue());
       } else if (n.getNodeType() == Node.TEXT_NODE) {
         sb.append(n.getNodeValue());
       } else {
         // Print.logWarn("Unrecognized node type: " + n.getNodeType());
       }
     }
   }
   return sb.toString();
 }
Exemplo n.º 7
0
 public ResultValue(Node node) {
   NodeList list = node.getChildNodes();
   for (int i = 0; i < list.getLength(); i++) {
     Node n = list.item(i);
     if (n.getNodeName().equals("class")) {
       matlabClass = n.getTextContent();
     }
     if (n.getNodeName().equals("size")) {
       size = string2intList(n.getTextContent());
       numdims = size.size();
       numel = 1;
       for (int d : size) {
         numel *= d;
       }
     }
     if (n.getNodeName().equals("matrix")) {
       resultType = RESULT_TYPE.MATRIX;
       matrixResult = string2doubleList(n.getTextContent());
     }
     if (n.getNodeName().equals("imagMatrix")) {
       isReal = false;
       resultType = RESULT_TYPE.MATRIX;
       imagMatrixResult = string2doubleList(n.getTextContent());
     }
     if (n.getNodeName().equals("char")) {
       resultType = RESULT_TYPE.CHAR;
       charResult = n.getTextContent();
     }
     if (n.getNodeName().equals("logical")) {
       resultType = RESULT_TYPE.LOGICAL;
       logicalResult = string2booleanList(n.getTextContent());
     }
     if (n.getNodeName().equals("handle")) {
       resultType = RESULT_TYPE.HANDLE;
     }
     if (n.getNodeName().equals("struct")) {
       resultType = RESULT_TYPE.STRUCT;
       // create struct list for first occurence of struct
       if (structResult == null) {
         structResult = new ArrayList<HashMap<String, ResultValue>>();
       }
       // build struct
       HashMap<String, ResultValue> struct = new HashMap<String, ResultValue>();
       NodeList children = n.getChildNodes();
       for (int j = 0; j < children.getLength(); j++) {
         Node child = children.item(j);
         if (child.getNodeType() == Node.ELEMENT_NODE) {
           struct.put(child.getNodeName(), new ResultValue(child));
         }
       }
       structResult.add(struct);
     }
     if (n.getNodeName().equals("cell")) {
       resultType = RESULT_TYPE.CELL;
     }
   }
 }
Exemplo n.º 8
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;
  }
Exemplo n.º 9
0
 private Node getTextNode() {
   NodeList list = element.getChildNodes();
   int length = list.getLength();
   for (int i = 0; i < length; i++) {
     Node node = list.item(i);
     if (node.getNodeType() == Node.TEXT_NODE) {
       return node;
     }
   }
   return element.appendChild(element.getOwnerDocument().createTextNode(""));
 }
Exemplo n.º 10
0
  private static String getTextContent(Node n) {
    NodeList nodeList = n.getChildNodes();
    String textContent = "";
    for (int j = 0; j < nodeList.getLength(); j++) {
      Node k = nodeList.item(j);
      if (k.getNodeType() == Node.TEXT_NODE) {
        textContent = k.getNodeValue();
        break;
      }
    }

    return textContent;
  }
Exemplo n.º 11
0
  /**
   * Parse groups node
   *
   * @param node the groups node
   */
  private void handleGroups(Node node) {
    this.groupsDn = node.getAttributes().getNamedItem("dn").getNodeValue();

    node = node.getFirstChild();
    while (node != null) {
      if (node.getNodeType() == Node.ELEMENT_NODE) {
        if (node.getNodeName().equals("attribute")) handleMapping(this.groupsAttributes, node);
        else if (node.getNodeName().equals("mapping")) handleMapping(this.groupsMapping, node);
        else Logging.getLogger().warning("unexepected node : " + node.getNodeName());
      }
      node = node.getNextSibling();
    }
  }
  /**
   * Get all the properties of this resource. This implementation stores properties in an XML
   * document containing a properties root element. The properties file name is derived from the URI
   * by adding the extension PropertiesManager.propertiesSuffix. This applies to collections as well
   * as other resources.
   *
   * <p>Since the properties are stored in a file, and all methods that query and update the
   * properties must read the XML file into memory and parse it, many of the other property methods
   * are implemented by calling this method. Subclasses of ResourceImpl may want to use other
   * techniques depending on how the properties are stored.
   *
   * @return a MultiStatus containing response elements with prop elements containing the properties
   *     and their statuses.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus getProperties() throws WebDAVException {
    Document propertiesDocument = resource.loadProperties();

    // create a MultiStatus to hold the results
    MultiStatus results = new MultiStatus();

    // create a response element to hold the properties for this resource
    PropertyResponse response = null;
    String urlstring;

    if (false) {
      // I consider this to be the more correct way and the
      //    way used in the examples in the spec... but it is
      //    redundant and creates the possibility of the two
      //    redundant parts being out of synch.
      urlstring = resource.getURL().toString();
    } else {
      // this is the way that mod_dav and a few others do it. This
      //    way also makes it easier to debug clients even if
      //    redirecting through a dedicated proxy.  Without this
      //    it's inconvenient to debug IE5.  It gets confused if
      //    the host:port (if provided) don't match who it thinks
      //    it's connecting to.
      urlstring = resource.getURL().getFile();
    }

    response = new PropertyResponse(urlstring);

    // add the properties to the response
    NodeList properties = propertiesDocument.getDocumentElement().getChildNodes();
    Node temp = null;

    for (int i = 0; i < properties.getLength(); i++) {
      temp = properties.item(i);

      // Skip ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element property = (Element) temp;
      PropertyName pn = new PropertyName(property);
      response.addProperty(pn, property, WebDAVStatus.SC_OK);
    }

    results.addResponse(response);

    return results;
  }
Exemplo n.º 13
0
  public void read(Document doc) {
    try {
      Element root = doc.getDocumentElement();
      NodeList nList = doc.getElementsByTagName("user");
      for (int i = 0; i < nList.getLength(); i++) {
        Node node = nList.item(i);
        if (node.getNodeType() == Node.ELEMENT_NODE) {
          Element element = (Element) node;
        }
      }
      //			Element e1 = (Element) nList.item(0);
    } catch (Exception e) {

    }
  }
Exemplo n.º 14
0
  /**
   * Method that reads a XML-file, and returns a Model that contains the information
   *
   * @param file
   * @return
   * @return
   */
  public static Model readXML(String file) {
    // initialize table to be filled with content of XML file
    Model t = new Model();
    try {
      // Create file to be parsed by document parser
      File xmlfile = new File(file);
      // create parser
      DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      // parse the file
      Document parsedfile = parser.parse(xmlfile);
      // normalize the parsed file (make it more user-friendly)
      parsedfile.getDocumentElement().normalize();

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

    } catch (ParserConfigurationException e) {
      System.out.println("Fileparser could not be made");
    } catch (IOException f) {
      System.out.println("File could not be parsed, did you enter the correct file name?");
    } catch (SAXException g) {
      System.out.println("Something went wrong in parsing the file");
    }
    return t;
  }
Exemplo n.º 15
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;
  }
  // http://www.java-tips.org/java-se-tips/javax.xml.parsers/how-to-read-xml-file-in-java.html
  private double my_ListParser(int itIs) {

    double[] my_list = new double[3];

    try {
      File fXmlFile =
          new File("/Users/alexiaKourfali/NetBeansProjects/mav_project3_part2/web/my_list.xml");
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document doc = db.parse(fXmlFile);
      doc.getDocumentElement().normalize();

      // System.out.println("Root element " + doc.getDocumentElement().getNodeName());
      NodeList nodeLst = doc.getElementsByTagName("Entry");

      for (int s = 0; s < nodeLst.getLength(); s++) {

        Node fstNode = nodeLst.item(s);

        if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
          Element fstElmnt = (Element) fstNode;

          NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("Price");
          Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
          NodeList fstNm = fstNmElmnt.getChildNodes();
          Node nV = (Node) fstNm.item(0);
          /*not sureeeee*/
          my_list[s] = Double.parseDouble(nV.getNodeValue());
        }
      }
    } catch (Exception e) {
    }

    if (itIs == 0) return my_list[0];

    if (itIs == 1) return my_list[1];
    else return my_list[2];
  }
Exemplo n.º 17
0
    /** Возвращает список методов класса. */
    public List<MethodNode> getMethods() {
      ArrayList<MethodNode> methods = new ArrayList<MethodNode>();

      /**
       * Получаем список дочерних узлов для данного узла XML, который соответствует классу class.
       * Здесь будут располагаться все узлы Node, каждый из которых является объектным
       * представлением тега method для текущего тега class.
       */
      NodeList methodNodes = node.getChildNodes();

      for (int i = 0; i < methodNodes.getLength(); i++) {
        node = methodNodes.item(i);

        if (node.getNodeType() == Node.ELEMENT_NODE) {

          /** Создаем на основе Node узла своё объектное представление метода. */
          MethodNode methodNode = new MethodNode(node);
          methods.add(methodNode);
        }
      }

      return methods;
    }
Exemplo n.º 18
0
    public List<ClassNode> getClasses() {
      ArrayList<ClassNode> classes = new ArrayList<ClassNode>();

      /**
       * Получаем список дочерних узлов для данного узла XML, который соответствует приложению
       * application. Здесь будут располагаться все узлы Node, каждый из которых является объектным
       * представлением тега class для текущего тега application.
       */
      NodeList classNodes = node.getChildNodes();

      for (int i = 0; i < classNodes.getLength(); i++) {
        Node node = classNodes.item(i);

        if (node.getNodeType() == Node.ELEMENT_NODE) {

          /** Создаем на основе Node узла своё объектное представление класса. */
          ClassNode classNode = new ClassNode(node);
          classes.add(classNode);
        }
      }

      return classes;
    }
Exemplo n.º 19
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();
    }
  }
Exemplo n.º 20
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;
  }
  /**
   * Edit the properties of a resource. The updates must refer to a Document containing a WebDAV
   * propertyupdates element as the document root.
   *
   * @param updates an XML Document containing propertyupdate elements
   * @return the result of making the updates describing the edits to be made.
   * @exception com.ibm.webdav.WebDAVException
   */
  public MultiStatus setProperties(Document propertyUpdates) throws WebDAVException {
    // create a MultiStatus to hold the results. It will hold a MethodResponse
    // for each update, and one for the method as a whole
    MultiStatus multiStatus = new MultiStatus();
    boolean errorsOccurred = false;

    // first, load the properties so they can be edited
    Document propertiesDocument = resource.loadProperties();
    Element properties = (Element) propertiesDocument.getDocumentElement();

    // be sure the updates have at least one update
    Element propertyupdate = (Element) propertyUpdates.getDocumentElement();
    String tagName = propertyupdate.getNamespaceURI() + propertyupdate.getLocalName();

    if (!tagName.equals("DAV:propertyupdate")) {
      throw new WebDAVException(
          WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "missing propertyupdate element");
    }

    NodeList updates = propertyupdate.getChildNodes();

    if (updates.getLength() == 0) {
      throw new WebDAVException(WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no updates in request");
    }

    Vector propsGood = new Vector(); // a list of properties that

    // were patched correctly or would have been if another
    // property hadn't gone bad.
    // apply the updates
    Node temp = null;

    for (int i = 0; i < updates.getLength(); i++) {
      temp = updates.item(i);

      // skip any ignorable TXText elements
      if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
        continue;
      }

      Element update = (Element) temp;
      int updateCommand = -1;
      tagName = update.getNamespaceURI() + update.getLocalName();

      if (tagName.equals("DAV:set")) {
        updateCommand = set;
      } else if (tagName.equals("DAV:remove")) {
        updateCommand = remove;
      } else {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY,
            update.getTagName() + " is not a valid property update request");
      }

      // iterate through the props in the set or remove element and update the
      // properties as directed
      Element prop = (Element) update.getElementsByTagNameNS("DAV:", "prop").item(0);

      if (prop == null) {
        throw new WebDAVException(
            WebDAVStatus.SC_UNPROCESSABLE_ENTITY, "no propeprties in update request");
      }

      NodeList propsToUpdate = prop.getChildNodes();

      for (int j = 0; j < propsToUpdate.getLength(); j++) {
        temp = propsToUpdate.item(j);

        // skip any TXText elements??
        if (!(temp.getNodeType() == Node.ELEMENT_NODE)) {
          continue;
        }

        Element propToUpdate = (Element) temp;

        // find the property in the properties element
        Element property = null;
        PropertyName propertyName = new PropertyName(propToUpdate);

        if (((Element) propToUpdate).getNamespaceURI() != null) {
          property =
              (Element)
                  properties
                      .getElementsByTagNameNS(
                          propToUpdate.getNamespaceURI(), propToUpdate.getLocalName())
                      .item(0);
        } else {
          property = (Element) properties.getElementsByTagName(propToUpdate.getTagName()).item(0);
        }

        boolean liveone = isLive(propertyName.asExpandedString());

        if (liveone) {
          errorsOccurred = true;

          PropertyResponse response = new PropertyResponse(resource.getURL().toString());
          response.addProperty(propertyName, propToUpdate, WebDAVStatus.SC_FORBIDDEN);
          multiStatus.addResponse(response);
        }

        // do the update
        if (updateCommand == set) {
          if (property != null) {
            try {
              properties.removeChild(property);
            } catch (DOMException exc) {
            }
          }

          if (!liveone) {
            // I don't think we're allowed to update live properties
            //    here.  Doing so effects the cache.  A case in
            //    point is the lockdiscoveryproperty.  properties
            //    is actually the properites cache "document" of this
            //    resource.  Even though we don't "save" the request
            //    if it includes live properties, we don't remove
            //    it from the cache after we'd set it here, so it
            //    can affect other queries. (jlc 991002)
            properties.appendChild(propertiesDocument.importNode(propToUpdate, true));

            propsGood.addElement(propToUpdate);
          }
        } else if (updateCommand == remove) {
          try {
            if (property != null) {
              properties.removeChild(property);
              propsGood.addElement(propToUpdate);
            }
          } catch (DOMException exc) {
          }
        }
      }
    }

    {
      Enumeration els = propsGood.elements();

      for (; els.hasMoreElements(); ) {
        Object ob1 = els.nextElement();
        Element elProp = (Element) ob1;
        PropertyName pn = new PropertyName(elProp);
        PropertyResponse response = new PropertyResponse(resource.getURL().toString());
        response.addProperty(
            pn,
            (Element) elProp.cloneNode(false),
            (errorsOccurred ? WebDAVStatus.SC_FAILED_DEPENDENCY : WebDAVStatus.SC_OK));

        // todo: add code for responsedescription
        multiStatus.addResponse(response);
      }
    }

    // write out the properties
    if (!errorsOccurred) {
      resource.saveProperties(propertiesDocument);
    }

    return multiStatus;
  }
Exemplo n.º 22
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();
    }
  }