public SchematronTransformer() throws TransformerConfigurationException {
   step1 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_dsdl_include.xsl")));
   step2 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_abstract_expand.xsl")));
   step3 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_svrl_for_xslt2.xsl")));
 }
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

      // transform
      StringResult result = new StringResult();
      transformer.transform(xmlSource, result);
      FileUtils.writeToFile(
          format(result.toString(), project.getSettings().getTabSize()), configFile);
      return;
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Esempio n. 4
0
  public void saveToXml(String fileName)
      throws ParserConfigurationException, FileNotFoundException, TransformerException,
          TransformerConfigurationException {
    System.out.println("Saving network topology to file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.newDocument();

    Element root = doc.createElement("neuralNetwork");
    root.setAttribute("dateOfExport", new Date().toString());
    Element layers = doc.createElement("structure");
    layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers()));

    for (int il = 0; il < this.numberOfLayers(); il++) {
      Element layer = doc.createElement("layer");
      layer.setAttribute("index", Integer.toString(il));
      layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons()));

      for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) {
        Element neuron = doc.createElement("neuron");
        neuron.setAttribute("index", Integer.toString(in));
        neuron.setAttribute(
            "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs()));
        neuron.setAttribute(
            "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold));

        for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) {
          Element input = doc.createElement("input");
          input.setAttribute("index", Integer.toString(ii));
          input.setAttribute(
              "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight));

          neuron.appendChild(input);
        }

        layer.appendChild(neuron);
      }

      layers.appendChild(layer);
    }

    root.appendChild(layers);
    doc.appendChild(root);

    // save
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;

    fos = new FileOutputStream(xmlOutputFile);
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    transformer.setOutputProperty("encoding", "iso-8859-2");
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
  }
  /**
   * Transforms the given XML string using the XSL string.
   *
   * @param xmlString The String containg the XML to transform
   * @param xslString The XML Stylesheet String containing the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(String xmlString, String xslString) {

    String shortString = new String(xmlString);
    if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "...";

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      logger.logComment("Transforming string: " + shortString);

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(
          new StreamSource(new StringReader(xmlString)), new StreamResult(writer));

      String shortResult = writer.toString();
      if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "...";

      logger.logComment("Result: " + shortResult);

      return writer.toString();
    } catch (TransformerException e) {
      GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null);
      return null;
    }
  }
  /**
   * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute
   * formatting with xsl transformation.
   *
   * @param jaxbElement
   * @return
   */
  private String getXmlContent(Object jaxbElement) {
    StringResult jaxbContent = new StringResult();

    springBeanMarshaller.marshal(jaxbElement, jaxbContent);

    Source xsltSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream());
      Transformer transformer = transformerFactory.newTransformer(xsltSource);

      // transform
      StringResult result = new StringResult();
      transformer.transform(new StringSource(jaxbContent.toString()), result);

      if (log.isDebugEnabled()) {
        log.debug("Created bean definition:\n" + result.toString());
      }

      return result.toString();
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
  /**
   * Transforms the given XML file using the specified XSL file.
   *
   * @param origXmlFile The file containg the XML to transform
   * @param xslString The XML Stylesheet conntaining the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(File origXmlFile, String xslString) {
    if (!origXmlFile.exists()) {
      GuiUtils.showErrorMessage(
          logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null);
      return null;
    }

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer));

      return writer.toString();
    } catch (Exception e) {
      GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null);
      return null;
    }
  }
  private static Transformer getTransformer() throws TransformerException {
    if (_transformer == null) {
      TransformerFactory factory = TransformerFactory.newInstance();
      _transformer = factory.newTransformer();
    }

    return _transformer;
  }
Esempio n. 9
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  void outputDocument(Writer out) throws Exception {
    // Set up the output transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    //		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.METHOD, "html");

    // Print the DOM node
    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(this.document);
    trans.transform(source, result);
  }
Esempio n. 11
0
  private Transformer buildTransformer(String name, File xslDir, TransformerFactory tf)
      throws Exception {

    Transformer tr =
        tf.newTransformer(
            new StreamSource(
                new FileReader(xslDir.getAbsolutePath() + File.separatorChar + name + ".xsl")));
    tr.setOutputProperty(OutputKeys.INDENT, "yes");
    tr.setOutputProperty(OutputKeys.METHOD, "html");
    tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3");

    return tr;
  }
Esempio n. 12
0
  public void write(SecureItemTable tbl, char[] password) throws IOException {
    OutputStream os = new FileOutputStream(file);
    OutputStream xmlout;

    if (password.length == 0) {
      xmlout = os;
      os = null;
    } else {
      PBEKeySpec keyspec = new PBEKeySpec(password);
      Cipher c;
      try {
        SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = fac.generateSecret(keyspec);

        c = Cipher.getInstance("PBEWithMD5AndDES");
        c.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
      } catch (java.security.GeneralSecurityException exc) {
        os.close();
        IOException ioe = new IOException("Security exception during write");
        ioe.initCause(exc);
        throw ioe;
      }

      CipherOutputStream out = new CipherOutputStream(os, c);
      xmlout = out;
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer t = tf.newTransformer();

      DOMSource src = new DOMSource(tbl.getDocument());
      StringWriter writer = new StringWriter();
      StreamResult sr = new StreamResult(writer);
      t.transform(src, sr);

      OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8);
      osw.write(writer.toString());
      osw.close();
    } catch (Exception exc) {
      IOException ioe = new IOException("Unable to serialize XML");
      ioe.initCause(exc);
      throw ioe;
    } finally {
      xmlout.close();
      if (os != null) os.close();
    }

    tbl.setDirty(false);
    return;
  }
  /**
   * Method updates existing Spring bean definitions in a XML application context file. Bean
   * definition is identified by its type defining class.
   *
   * @param project
   * @param type
   * @param jaxbElement
   */
  public void updateBeanDefinitions(
      File configFile, Project project, Class<?> type, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(
              new ClassPathResource("transform/update-bean-type.xsl").getInputStream());
      xsltSource.setSystemId("update-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      LSParser parser = XMLUtils.createLSParser();
      GetSpringBeansFilter getBeanFilter = new GetSpringBeansFilter(type, null);
      parser.setFilter(getBeanFilter);

      for (File file : configFiles) {
        parser.parseURI(file.toURI().toString());
        if (!CollectionUtils.isEmpty(getBeanFilter.getBeanDefinitions())) {
          xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(file)));

          String beanElement = type.getAnnotation(XmlRootElement.class).name();
          String beanNamespace = type.getPackage().getAnnotation(XmlSchema.class).namespace();

          // create transformer
          Transformer transformer = transformerFactory.newTransformer(xsltSource);
          transformer.setParameter("bean_element", beanElement);
          transformer.setParameter("bean_namespace", beanNamespace);
          transformer.setParameter(
              "bean_content",
              getXmlContent(jaxbElement)
                  .replaceAll("(?m)^(\\s<)", getTabs(1, project.getSettings().getTabSize()) + "$1")
                  .replaceAll("(?m)^(</)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

          // transform
          StringResult result = new StringResult();
          transformer.transform(xmlSource, result);
          FileUtils.writeToFile(
              format(result.toString(), project.getSettings().getTabSize()), file);
          return;
        }
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Esempio n. 14
0
  /**
   * http://www.atmarkit.co.jp/fxml/rensai2/xmltool04/02.html
   *
   * @return
   */
  private static Transformer getTransformer() {
    if (s_transformer == null) {
      TransformerFactory transFactory = TransformerFactory.newInstance();
      try {
        s_transformer = transFactory.newTransformer();
      } catch (TransformerConfigurationException e) {
      }

      s_transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      s_transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } // if

    return s_transformer;
  }
Esempio n. 15
0
 public void toSave() {
   try {
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer transformer = tf.newTransformer();
     DOMSource source = new DOMSource(document);
     transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
     StreamResult result = new StreamResult(pw);
     transformer.transform(source, result);
   } catch (TransformerException mye) {
     mye.printStackTrace();
   } catch (IOException exp) {
     exp.printStackTrace();
   }
 }
Esempio n. 16
0
  private void message(String text, HttpServletResponse response, PublishAsType publishAs) {
    ServletOutputStream out;
    String xmlText;
    Server.logger.errorLogEntry(text);
    try {

      xmlText =
          "<?xml version = \"1.0\" encoding=\"utf-8\"?><request><error type=\""
              + type
              + "\">"
              + "<message><version>"
              + Server.serverVersion
              + "</version><errortext>"
              + XMLUtil.getAsTagValue(text)
              + "</errortext></message></error></request>";
      //		System.out.println("xml text = "+xmlText);
      response.setHeader(
          "Cache-Control", "no-cache, must-revalidate, private, no-store, s-maxage=0, max-age=0");
      response.setHeader("Pragma", "no-cache");
      response.setDateHeader("Expires", 0);

      if (publishAs == PublishAsType.HTML) {
        response.setContentType("text/html;charset=utf-8");
        out = response.getOutputStream();
        Source xmlSource = new StreamSource(new StringReader(xmlText));
        Result result = new StreamResult(out);
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(xsltSource);
        // System.out.println(PortalEnv.appID+": xsl transformation="+PortalEnv.errorXSL);
        trans.transform(xmlSource, result);
      } else {
        response.setContentType("text/xml;charset=utf-8");
        // response.sendError(550);
        out = response.getOutputStream();
        out.println(xmlText);
      }
    } catch (IOException ioe) {
      System.out.println(ioe);
      ioe.printStackTrace();
    } catch (TransformerConfigurationException tce) {
      System.out.println(tce);
      tce.printStackTrace();
    } catch (TransformerException te) {
      System.out.println(te);
      te.printStackTrace();
    }
  }
Esempio n. 17
0
  /**
   * Writes a table to a XML-file
   *
   * @param t - Output Model
   * @param destination - File Destination
   */
  public static void writeXML(Model t, String destination) {

    try {
      // Create the XML document builder, and document that will be used
      DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance();
      DocumentBuilder Builder = xmlBuilder.newDocumentBuilder();
      Document xmldoc = Builder.newDocument();

      // create Document node, and get it into the file
      Element Documentnode = xmldoc.createElement("SPREADSHEET");
      xmldoc.appendChild(Documentnode);

      // create element nodes, and their attributes (Cells, and row/column
      // data) and their content
      for (int row = 1; row < t.getRows(); row++) {
        for (int col = 1; col < t.getCols(col); col++) {
          Element cell = xmldoc.createElement("CELL");
          // set attributes
          cell.setAttribute("column", Integer.toString(col));
          cell.setAttribute("row", Integer.toString(col));
          // set content
          cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col)));
          // append node to document node
          Documentnode.appendChild(cell);
        }
      }
      // Creating a datastream for the DOM tree
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      // Indentation to make the XML file look better
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // remove the java version
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource stream = new DOMSource(xmldoc);
      StreamResult target = new StreamResult(new File(destination));
      // write the file
      transformer.transform(stream, target);

    } catch (ParserConfigurationException e) {
      System.out.println("Can't create the XML document builder");
    } catch (TransformerConfigurationException e) {
      System.out.println("Can't create transformer");
    } catch (TransformerException e) {
      System.out.println("Can't write to file");
    }
  }
Esempio n. 18
0
 public static String documentToString(Document document) {
   TransformerFactory tf = TransformerFactory.newInstance();
   Transformer transformer = null;
   try {
     transformer = tf.newTransformer();
   } catch (TransformerConfigurationException e) {
     throw new RuntimeException(e);
   }
   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
   StringWriter writer = new StringWriter();
   try {
     transformer.transform(new DOMSource(document), new StreamResult(writer));
   } catch (TransformerException e) {
     throw new RuntimeException(e);
   }
   String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
   return output;
 }
 /**
  * Writes an XML file from a Document object.
  *
  * @param doc the Document object to be written to file
  * @param file the file to be written
  * @throws IOException
  * @author Klaus Meffert
  * @since 2.0
  */
 public static void writeFile(Document doc, File file) throws IOException {
   // Use a Transformer for output
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   try {
     transformer = tFactory.newTransformer();
   } catch (TransformerConfigurationException tex) {
     throw new IOException(tex.getMessage());
   }
   DOMSource source = new DOMSource(doc);
   FileOutputStream fos = new FileOutputStream(file);
   StreamResult result = new StreamResult(fos);
   try {
     transformer.transform(source, result);
     fos.close();
   } catch (TransformerException tex) {
     throw new IOException(tex.getMessage());
   }
 }
Esempio n. 20
0
  /**
   * Save the XML description of the circuit
   *
   * @param output an output stream to write in
   * @return true if the dump was successful, false either
   */
  public boolean dumpToXml(OutputStream output) {
    Document doc;
    Element root;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (ParserConfigurationException pce) {
      System.err.println("dumpToXmlFile: unable to write XML save file.");
      return false;
    }

    root = doc.createElement("Circuit");
    root.setAttribute("name", this.getName());

    for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); )
      iterNodes.next().dumpToXml(doc, root);

    root.normalize();
    doc.appendChild(root);

    try {
      TransformerFactory tffactory = TransformerFactory.newInstance();
      Transformer transformer = tffactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);
      transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
      System.err.println("dumpToXmlFile:  Configuration Transformer exception.");
      return false;
    } catch (TransformerException te) {
      System.err.println("dumpToXmlFile: Transformer exception.");
      return false;
    }

    return true;
  }
  /**
   * Transforms the given XML string using the specified XSL file.
   *
   * @param xmlString The String containg the XML to transform
   * @param xslFile The XML Stylesheet conntaining the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(String xmlString, File xslFile) {

    if (!xslFile.exists()) {
      GuiUtils.showErrorMessage(
          logger, "Warning, XSL file: " + xslFile + " doesn't exist", null, null);
      return null;
    }

    String shortString = new String(xmlString);
    if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "...";

    try {
      logger.logComment("The xslFile is " + xslFile.getAbsolutePath() + " *************");

      TransformerFactory tFactory = TransformerFactory.newInstance();

      logger.logComment("Transforming string: " + shortString);

      StreamSource xslFileSource = new StreamSource(xslFile);

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(
          new StreamSource(new StringReader(xmlString)), new StreamResult(writer));

      String shortResult = writer.toString();
      if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "...";

      logger.logComment("Result: " + shortResult);

      return writer.toString();
    } catch (TransformerException e) {
      GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null);
      return null;
    }
  }
Esempio n. 22
0
  public StartProcess() {
    super();

    Hashtable jndiProps = new Hashtable();
    jndiProps.put(Context.PROVIDER_URL, "t3://soaps3.alfa.local:8001/soa-infra");
    jndiProps.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
    jndiProps.put(Context.SECURITY_PRINCIPAL, "weblogic");
    jndiProps.put(Context.SECURITY_CREDENTIALS, "weblogic1");
    jndiProps.put("dedicated.connection", "true");

    String inputPayload =
        "<process xmlns=\"http://xmlns.oracle.com/HelloWorld/Helloworld/BPELProcess1\">"
            + "   <input>hello</input>"
            + "</process>";

    Locator locator = null;
    try {
      // connect to the soa server
      locator = LocatorFactory.createLocator(jndiProps);
      String compositeDN = "default/Helloworld!1.0";

      // find composite
      Composite composite = locator.lookupComposite("default/Helloworld!1.0");

      System.out.println("Got Composite : " + composite.toString());

      // find exposed service of the composite
      Service service = composite.getService("ADFBindingService");
      System.out.println("Got serviceName : " + service.toString());

      // make the input request and add this to a operation of the service
      NormalizedMessage input = new NormalizedMessageImpl();
      String uuid = "uuid:" + UUID.randomUUID();
      input.addProperty(NormalizedMessage.PROPERTY_CONVERSATION_ID, uuid);

      // payload is the partname of the process operation
      input.getPayload().put("payload", inputPayload);

      // process is the operation of the employee service
      NormalizedMessage res = null;
      try {
        res = service.request("process", input);
      } catch (Exception e) {
        e.printStackTrace();
      }

      Map payload = res.getPayload();
      Element element = (Element) payload.get("payload");

      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty("indent", "yes");
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);

      DOMSource source = new DOMSource(element);

      transformer.transform(source, result);
      System.out.println("Result\n" + sw.toString());

      System.out.println("instances");

      CompositeInstanceFilter filter = new CompositeInstanceFilter();
      filter.setMinCreationDate(new java.util.Date((System.currentTimeMillis() - 2000000)));
      // get composite instances by filter ..
      List<CompositeInstance> obInstances = composite.getInstances(filter);
      // for each of the returned composite instances..
      for (CompositeInstance instance : obInstances) {
        System.out.println(
            " DN: "
                + instance.getCompositeDN()
                + " Instance: "
                + instance.getId()
                + " creation-date: "
                + instance.getCreationDate()
                + " state ("
                + instance.getState()
                + "): "
                + getStateAsString(instance.getState()));

        // setup a component filter
        ComponentInstanceFilter cInstanceFilter = new ComponentInstanceFilter();
        // get child component instances ..
        List<ComponentInstance> childComponentInstances =
            instance.getChildComponentInstances(cInstanceFilter);

        // for each child component instance (e.g. a bpel process)
        for (ComponentInstance cInstance : childComponentInstances) {
          System.out.println(
              "  -> componentinstance: "
                  + cInstance.getComponentName()
                  + " type: "
                  + cInstance.getServiceEngine().getEngineType()
                  + " state: "
                  + getStateAsString(cInstance.getState()));
          System.out.println("State: " + cInstance.getNormalizedStateAsString());
        }
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 23
0
  /**
   * Format this XML data as a String.
   *
   * @webref xml:method
   * @brief Formats XML data as a String
   * @param indent -1 for a single line (and no declaration), >= 0 for indents and newlines
   * @return the content
   * @see XML#toString()
   */
  public String format(int indent) {
    try {
      // entities = doctype.getEntities()
      boolean useIndentAmount = false;
      TransformerFactory factory = TransformerFactory.newInstance();
      if (indent != -1) {
        try {
          factory.setAttribute("indent-number", indent);
        } catch (IllegalArgumentException e) {
          useIndentAmount = true;
        }
      }
      Transformer transformer = factory.newTransformer();

      // Add the XML declaration at the top if this node is the root and we're
      // not writing to a single line (indent = -1 means single line).
      if (indent == -1 || parent == null) {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      } else {
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      }

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "sample.dtd");

      transformer.setOutputProperty(OutputKeys.METHOD, "xml");

      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes");  // huh?

      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      //          "-//W3C//DTD XHTML 1.0 Transitional//EN");
      //      transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,
      //          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");

      // For Android, because (at least 2.3.3) doesn't like indent-number
      if (useIndentAmount) {
        transformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", String.valueOf(indent));
      }

      //      transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1");
      //      transformer.setOutputProperty(OutputKeys.ENCODING,"UTF8");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      //      transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS

      // Always indent, otherwise the XML declaration will just be jammed
      // onto the first line with the XML code as well.
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");

      //      Properties p = transformer.getOutputProperties();
      //      for (Object key : p.keySet()) {
      //        System.out.println(key + " -> " + p.get(key));
      //      }

      // If you smell something, that's because this code stinks. No matter
      // the settings of the Transformer object, if the XML document already
      // has whitespace elements, it won't bother re-indenting/re-formatting.
      // So instead, transform the data once into a single line string.
      // If indent is -1, then we're done. Otherwise re-run and the settings
      // of the factory will kick in. If you know a better way to do this,
      // please contribute. I've wasted too much of my Sunday on it. But at
      // least the Giants are getting blown out by the Falcons.

      final String decl = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
      final String sep = System.getProperty("line.separator");

      StringWriter tempWriter = new StringWriter();
      StreamResult tempResult = new StreamResult(tempWriter);
      transformer.transform(new DOMSource(node), tempResult);
      String[] tempLines = PApplet.split(tempWriter.toString(), sep);
      //      PApplet.println(tempLines);
      if (tempLines[0].startsWith("<?xml")) {
        // Remove XML declaration from the top before slamming into one line
        int declEnd = tempLines[0].indexOf("?>") + 2;
        // if (tempLines[0].length() == decl.length()) {
        if (tempLines[0].length() == declEnd) {
          // If it's all the XML declaration, remove it
          //          PApplet.println("removing first line");
          tempLines = PApplet.subset(tempLines, 1);
        } else {
          //          PApplet.println("removing part of first line");
          // If the first node has been moved to this line, be more careful
          // tempLines[0] = tempLines[0].substring(decl.length());
          tempLines[0] = tempLines[0].substring(declEnd);
        }
      }
      String singleLine = PApplet.join(PApplet.trim(tempLines), "");
      if (indent == -1) {
        return singleLine;
      }

      // Might just be whitespace, which won't be valid XML for parsing below.
      // https://github.com/processing/processing/issues/1796
      // Since indent is not -1, that means they want valid XML,
      // so we'll give them the single line plus the decl... Lame? sure.
      if (singleLine.trim().length() == 0) {
        // You want whitespace? I've got your whitespace right here.
        return decl + sep + singleLine;
      }

      // Since the indent is not -1, bring back the XML declaration
      // transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

      StringWriter stringWriter = new StringWriter();
      StreamResult xmlOutput = new StreamResult(stringWriter);
      //      DOMSource source = new DOMSource(node);
      Source source = new StreamSource(new StringReader(singleLine));
      transformer.transform(source, xmlOutput);
      String outgoing = stringWriter.toString();

      // Add the XML declaration to the top if it's not there already
      if (outgoing.startsWith(decl)) {
        int declen = decl.length();
        int seplen = sep.length();
        if (outgoing.length() > declen + seplen
            && !outgoing.substring(declen, declen + seplen).equals(sep)) {
          // make sure there's a line break between the XML decl and the code
          return outgoing.substring(0, decl.length()) + sep + outgoing.substring(decl.length());
        }
        return outgoing;
      } else {
        return decl + sep + outgoing;
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 24
0
  public void CollectData(String link) {

    try {
      // Creating an empty XML Document

      DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
      Document doc = docBuilder.newDocument();
      int flag = 0;
      // create the root element and add it to the document
      Element movie = doc.createElement("movie");
      doc.appendChild(movie);
      movie.setAttribute("id", String.valueOf(n));
      n++;
      // create sub elements
      Element genres = doc.createElement("genres");
      Element actors = doc.createElement("actors");
      Element reviews = doc.createElement("reviews");

      URL movieUrl = new URL(link);
      URL reviewsURL = new URL(link + "reviews/#type=top_critics");
      BufferedWriter bw3 = new BufferedWriter(new FileWriter("movies.xml", true));
      int count = -1;
      String auth = "";
      BufferedReader br3 = new BufferedReader(new InputStreamReader(movieUrl.openStream()));
      String str2 = "";
      String info = "";
      while (null != (str2 = br3.readLine())) {
        // start reading the html document
        if (str2.isEmpty()) continue;
        if (count == 14) break;
        if (count == 12) {
          if (!str2.contains("<h3>Cast</h3>")) continue;
          else count++;
        }
        if (count == 13) {
          if (str2.contains(">ADVERTISEMENT</p>")) {
            count++;
            movie.appendChild(actors);
            continue;
          } else {
            if (str2.contains("itemprop=\"name\">")) {
              Element actor = doc.createElement("actor");
              actors.appendChild(actor);
              Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
              actor.appendChild(text);
            } else continue;
          }
        }

        if (count <= 11) {
          switch (count) {
            case -1:
              {
                if (!str2.contains("property=\"og:image\"")) continue;
                else {
                  Pattern image =
                      Pattern.compile("http://.*.jpg", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
                  Matcher match = image.matcher(str2);
                  while (match.find()) {

                    Element imageLink = doc.createElement("imageLink");
                    movie.appendChild(imageLink);
                    Text text = doc.createTextNode(match.group());
                    imageLink.appendChild(text);
                    count++;
                  }
                }
                break;
              }
            case 0:
              {
                if (str2.contains("<title>")) {

                  Element name = doc.createElement("name");
                  movie.appendChild(name);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(str2.toString().replace(" - Rotten Tomatoes", "")).text());
                  name.appendChild(text);
                  count++;
                }
                break;
              }
            case 1:
              {
                if (!str2.contains("itemprop=\"ratingValue\"")) break;
                else {
                  Element score = doc.createElement("score");
                  movie.appendChild(score);
                  Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                  score.appendChild(text);
                  count++;
                }
                break;
              }
            case 2:
              {
                if (!str2.contains("itemprop=\"description\">")) continue;
                else count++;
                break;
              }
            case 3:
              {
                if (!str2.contains("itemprop=\"duration\"")) info = info.concat(str2);
                else {
                  Element MovieInfo = doc.createElement("MovieInfo");
                  movie.appendChild(MovieInfo);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  MovieInfo.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 4:
              {
                if (!str2.contains("itemprop=\"genre\"")) info = info.concat(str2);
                else {
                  Element duration = doc.createElement("duration");
                  movie.appendChild(duration);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  duration.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 5:
              {
                if (info.contains("itemprop=\"genre\"")) {
                  Element genre = doc.createElement("genre");
                  genres.appendChild(genre);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  genre.appendChild(text);
                  info = "";
                }
                if (str2.contains(">Directed By:<")) {
                  count++;
                  movie.appendChild(genres);
                  continue;
                } else {

                  if (str2.contains("itemprop=\"genre\"")) {
                    Element genre = doc.createElement("genre");
                    genres.appendChild(genre);
                    Text text = doc.createTextNode(Jsoup.parse(str2.toString()).text());
                    genre.appendChild(text);
                  } else continue;
                }
                break;
              }
            case 6:
              {
                if (!str2.contains(">Written By:<")) {
                  if (str2.contains(">In Theaters:<")) {
                    Element director = doc.createElement("director");
                    movie.appendChild(director);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                    director.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element director = doc.createElement("director");
                  movie.appendChild(director);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("Directed By: ", "")).text());
                  director.appendChild(text);
                  info = "";
                  count++;
                }
                break;
              }
            case 7:
              {
                if (!str2.contains(">In Theaters:<")) {
                  if (str2.contains(">On DVD:<")) {
                    Element writer = doc.createElement("writer");
                    movie.appendChild(writer);
                    Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                    writer.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element writer = doc.createElement("writer");
                  movie.appendChild(writer);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  writer.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 8:
              {
                if (!str2.contains(">On DVD:<")) info = info.concat(str2);
                else {
                  Element TheatreRelease = doc.createElement("TheatreRelease");
                  movie.appendChild(TheatreRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("In Theaters:", "")).text());
                  TheatreRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 9:
              {
                if (!str2.contains(">US Box Office:<")) {
                  if (str2.contains("itemprop=\"productionCompany\"")) {
                    Element DvdRelease = doc.createElement("DvdRelease");
                    movie.appendChild(DvdRelease);
                    Text text =
                        doc.createTextNode(
                            Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                    DvdRelease.appendChild(text);
                    info = str2;
                    count += 2;
                    break;
                  }
                  info = info.concat(str2);
                } else {
                  Element DvdRelease = doc.createElement("DvdRelease");
                  movie.appendChild(DvdRelease);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("On DVD:", "")).text());
                  DvdRelease.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 10:
              {
                if (!str2.contains("itemprop=\"productionCompany\"")) info = info.concat(str2);
                else {
                  Element BOCollection = doc.createElement("BOCollection");
                  movie.appendChild(BOCollection);
                  Text text =
                      doc.createTextNode(
                          Jsoup.parse(info.toString().replace("US Box Office:", "")).text());
                  BOCollection.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }
            case 11:
              {
                if (!str2.contains(">Official Site")) info = info.concat(str2);
                else {
                  Element Production = doc.createElement("Production");
                  movie.appendChild(Production);
                  Text text = doc.createTextNode(Jsoup.parse(info.toString()).text());
                  Production.appendChild(text);
                  info = str2;
                  count++;
                }
                break;
              }

            default:
              break;
          }
        }
      }
      BufferedReader br4 = new BufferedReader(new InputStreamReader(reviewsURL.openStream()));
      String str3 = "";
      String info2 = "";
      int count2 = 0;
      while (null != (str3 = br4.readLine())) {
        if (count2 == 0) {

          if (!str3.contains("<div class=\"reviewsnippet\">")) continue;
          else count2++;
        }
        if (count2 == 1) {
          if (!str3.contains("<p class=\"small subtle\">")) info2 = info2.concat(str3);
          else {
            Element review = doc.createElement("review");
            reviews.appendChild(review);
            Text text = doc.createTextNode(Jsoup.parse(info2.toString()).text());
            review.appendChild(text);
            info2 = "";
            count2 = 0;
          }
        }
      }
      movie.appendChild(reviews);
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // create string from xml tree
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);
      String xmlString = sw.toString();
      bw3.write(xmlString);
      br3.close();
      br4.close();
      bw3.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Esempio n. 25
0
  /**
   * This is the new write method that uses XML methods to generate an XML file.
   *
   * @param location The location where the new file should be stored.
   * @param file The file that was being used to create this table.
   * @param tableID The ID of the table.
   * @param semanticFramework The semantic framework object. This contains get methods that are
   *     required for the output File.
   * @throws IOException If the given location doesn't exist.
   */
  private void write2(String location, File file, int tableID, SemanticFramework semanticFramework)
      throws IOException {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
      Document doc = docBuilder.newDocument();

      org.w3c.dom.Element rootElement = doc.createElement("TEAFile");
      doc.appendChild(rootElement);

      // provenance:
      org.w3c.dom.Element provenance = doc.createElement("provenance");
      rootElement.appendChild(provenance);

      org.w3c.dom.Element detectionID = doc.createElement("DetectionID");
      detectionID.appendChild(doc.createTextNode(tableID + ""));
      provenance.appendChild(detectionID);
      org.w3c.dom.Element fromFile = doc.createElement("fromFile");
      fromFile.appendChild(doc.createTextNode(file.getName()));
      provenance.appendChild(fromFile);
      org.w3c.dom.Element fromPath = doc.createElement("fromPath");
      fromPath.appendChild(doc.createTextNode(file.getAbsolutePath()));
      provenance.appendChild(fromPath);
      org.w3c.dom.Element fromPage = doc.createElement("fromPage");
      fromPage.appendChild(doc.createTextNode(Integer.toString(pageNumber)));
      provenance.appendChild(fromPage);

      org.w3c.dom.Element horizontalThresholdModifier =
          doc.createElement("horizontalThresholdModifier");
      horizontalThresholdModifier.appendChild(
          doc.createTextNode(this.horizontalThresholdModifier + ""));
      provenance.appendChild(horizontalThresholdModifier);
      org.w3c.dom.Element verticalThresholdModifier =
          doc.createElement("horizontalThresholdModifier");
      verticalThresholdModifier.appendChild(
          doc.createTextNode(this.verticalThresholdModifier + ""));
      provenance.appendChild(verticalThresholdModifier);

      // Results:
      org.w3c.dom.Element results = doc.createElement("results");
      rootElement.appendChild(results);

      org.w3c.dom.Element minX1 = doc.createElement("TableBoundaryX1");
      minX1.appendChild(doc.createTextNode(this.minX1 + ""));
      results.appendChild(minX1);
      org.w3c.dom.Element maxX2 = doc.createElement("TableBoundaryX2");
      maxX2.appendChild(doc.createTextNode(this.maxX2 + ""));
      results.appendChild(maxX2);
      org.w3c.dom.Element minY1 = doc.createElement("TableBoundaryY1");
      minY1.appendChild(doc.createTextNode(this.minY1 + ""));
      results.appendChild(minY1);
      org.w3c.dom.Element maxY2 = doc.createElement("TableBoundaryY2");
      maxY2.appendChild(doc.createTextNode(this.maxY2 + ""));
      results.appendChild(maxY2);

      org.w3c.dom.Element title1 = doc.createElement("title1");
      title1.appendChild(doc.createTextNode(name));
      results.appendChild(title1);
      org.w3c.dom.Element title2 = doc.createElement("title2");
      title2.appendChild(doc.createTextNode(titleAndHeaders.toString()));
      results.appendChild(title2);

      org.w3c.dom.Element columns = doc.createElement("columns");
      results.appendChild(columns);

      for (Column2 columnContent : dataInColumns) {
        org.w3c.dom.Element column = doc.createElement("column");
        column.appendChild(doc.createTextNode(columnContent.toString().replace("�", "")));
        columns.appendChild(column);
      }

      org.w3c.dom.Element lines = doc.createElement("lines");
      results.appendChild(lines);

      ArrayList<ArrayList<Cell>> table = recreateTableLines(semanticFramework);

      for (ArrayList<Cell> line : table) {
        org.w3c.dom.Element XMLLine = doc.createElement("line");
        XMLLine.appendChild(doc.createTextNode(line.toString().replace("�", "")));
        lines.appendChild(XMLLine);
      }

      /*System.out.println("table:" + table);

                  for(Line line : data){
                      if(line.getHighestY2()<=this.maxY2&&line.getLowestY1()>=this.minY1&&line.getClusterSize()>1){
                          org.w3c.dom.Element XMLLine = doc.createElement("line");
                          XMLLine.appendChild(doc.createTextNode(line.toString().replace("�", "")));
                          lines.appendChild(XMLLine);
                      }
                      else{
                          System.out.println("NO GOOD: " + line);
                      }
                  }
      */
      if (rowSpanners.size() > 0) {
        org.w3c.dom.Element rowSpanners = doc.createElement("rowSpanners");
        results.appendChild(rowSpanners);
        for (Line line : this.rowSpanners) {
          org.w3c.dom.Element rowSpanner = doc.createElement("rowSpanner");
          rowSpanner.appendChild(doc.createTextNode(line.toString()));
          rowSpanners.appendChild(rowSpanner);
        }
      }

      // Semantics:
      org.w3c.dom.Element semantics = doc.createElement("tableSemantics");
      rootElement.appendChild(semantics);
      org.w3c.dom.Element title = doc.createElement("title");
      title.appendChild(doc.createTextNode(semanticFramework.getTitle().toString()));
      semantics.appendChild(title);
      org.w3c.dom.Element titleConfidence = doc.createElement("titleConfidence");
      Double semanticFrameworkDouble = semanticFramework.getTitleConfidence();
      titleConfidence.appendChild(doc.createTextNode(semanticFrameworkDouble.toString()));
      semantics.appendChild(titleConfidence);

      if (!semanticFramework.getRowSpanners().isEmpty()) {
        org.w3c.dom.Element rowSpanners = doc.createElement("subHeaders");
        rowSpanners.appendChild(doc.createTextNode(semanticFramework.getRowSpanners().toString()));
        semantics.appendChild(rowSpanners);
        org.w3c.dom.Element IdentifiersConfidenceAlignment =
            doc.createElement("subHeadersConfidenceAlignment");
        IdentifiersConfidenceAlignment.appendChild(
            doc.createTextNode(semanticFramework.getIdentifiersConfidenceAlignment().toString()));
        semantics.appendChild(IdentifiersConfidenceAlignment);
        org.w3c.dom.Element getIdentifiersConfidenceColumnsSpanned =
            doc.createElement("subHeadersConfidenceColumnsSpanned");
        getIdentifiersConfidenceColumnsSpanned.appendChild(
            doc.createTextNode(
                semanticFramework.getIdentifiersConfidenceColumnsSpanned().toString()));
        semantics.appendChild(getIdentifiersConfidenceColumnsSpanned);
        org.w3c.dom.Element IdentifiersConfidenceLineDistance =
            doc.createElement("subHeadersConfidenceLineDistance");
        IdentifiersConfidenceLineDistance.appendChild(
            doc.createTextNode(
                semanticFramework.getIdentifiersConfidenceLineDistance().toString()));
        semantics.appendChild(IdentifiersConfidenceLineDistance);
      }
      if (!semanticFramework.getValidatedRowSpanners().isEmpty()) {
        org.w3c.dom.Element rowSpanners = doc.createElement("rowSpanners");
        rowSpanners.appendChild(
            doc.createTextNode(semanticFramework.getValidatedRowSpanners().toString()));
        semantics.appendChild(rowSpanners);
        org.w3c.dom.Element rowSpannersConfidenceAlignment =
            doc.createElement("rowSpannersConfidenceAlignment");
        rowSpannersConfidenceAlignment.appendChild(
            doc.createTextNode(semanticFramework.getRowSpannersConfidenceAlignment().toString()));
        semantics.appendChild(rowSpannersConfidenceAlignment);
        org.w3c.dom.Element rowSpannersConfidenceColumnsSpanned =
            doc.createElement("rowSpannersConfidenceColumnsSpanned");
        rowSpannersConfidenceColumnsSpanned.appendChild(
            doc.createTextNode(
                semanticFramework.getRowSpannersConfidenceColumnsSpanned().toString()));
        semantics.appendChild(rowSpannersConfidenceColumnsSpanned);
        org.w3c.dom.Element rowSpannersConfidenceLineDistance =
            doc.createElement("rowSpannersConfidenceLineDistance");
        rowSpannersConfidenceLineDistance.appendChild(
            doc.createTextNode(
                semanticFramework.getRowSpannersConfidenceLineDistance().toString()));
        semantics.appendChild(rowSpannersConfidenceLineDistance);
      }
      org.w3c.dom.Element headers = doc.createElement("headers");
      headers.appendChild(doc.createTextNode(semanticFramework.getHeaders().toString()));
      semantics.appendChild(headers);
      org.w3c.dom.Element headersConfidence = doc.createElement("headersConfidence");
      headersConfidence.appendChild(
          doc.createTextNode(semanticFramework.getHeaderConfidence().toString()));
      semantics.appendChild(headersConfidence);

      // validation:
      org.w3c.dom.Element validation = doc.createElement("validation");
      rootElement.appendChild(validation);

      org.w3c.dom.Element clusterCertainty = doc.createElement("columnConfidence");
      clusterCertainty.appendChild(
          doc.createTextNode(this.validation.getClusterCertainty().toString()));
      validation.appendChild(clusterCertainty);
      org.w3c.dom.Element mostFrequentNumberOfClusters =
          doc.createElement("mostFrequentNumberOfClusters");
      mostFrequentNumberOfClusters.appendChild(
          doc.createTextNode(this.validation.getMostFrequentNumberOfClusters() + ""));
      validation.appendChild(mostFrequentNumberOfClusters);
      org.w3c.dom.Element highestAmountOfClusters = doc.createElement("highestAmountOfClusters");
      highestAmountOfClusters.appendChild(
          doc.createTextNode(this.validation.getHighestAmountOfClusters() + ""));
      validation.appendChild(highestAmountOfClusters);
      org.w3c.dom.Element highestAmountOfClustersOccurrences =
          doc.createElement("highestAmountOfClustersOccurrences");
      highestAmountOfClustersOccurrences.appendChild(
          doc.createTextNode(this.validation.getHighestAmountOfClustersOccurrences() + ""));
      validation.appendChild(highestAmountOfClustersOccurrences);
      org.w3c.dom.Element clusterThreshold = doc.createElement("clusterThreshold");
      clusterThreshold.appendChild(doc.createTextNode(this.validation.getLineThreshold() + ""));
      validation.appendChild(clusterThreshold);
      org.w3c.dom.Element cellsWithMissingDataAdded =
          doc.createElement("cellsWithMissingDataAdded");
      cellsWithMissingDataAdded.appendChild(
          doc.createTextNode(this.validation.getCellsWithMissingDataAdded() + ""));
      validation.appendChild(cellsWithMissingDataAdded);
      if (this.validation.getCellsWithMissingDataAdded() > 0) {
        org.w3c.dom.Element cellsWithMissingDataAddedScores =
            doc.createElement("cellsWithMissingDataAddedScores");
        cellsWithMissingDataAddedScores.appendChild(
            doc.createTextNode(this.validation.getCellsWithMissingDataAddedObjects() + ""));
        validation.appendChild(cellsWithMissingDataAddedScores);
      }
      org.w3c.dom.Element averageDistanceBetweenRows =
          doc.createElement("averageDistanceBetweenRows");
      averageDistanceBetweenRows.appendChild(
          doc.createTextNode(this.validation.getAverageDistanceBetweenRows() + ""));
      validation.appendChild(averageDistanceBetweenRows);
      if (this.validation.getTitleConfidence().size() > 0) {
        org.w3c.dom.Element TitleConfidence = doc.createElement("TitleConfidence");
        TitleConfidence.appendChild(doc.createTextNode(this.validation.getTitleConfidence() + ""));
        validation.appendChild(TitleConfidence);
      }
      org.w3c.dom.Element falsePositive = doc.createElement("falsePositive");
      falsePositive.appendChild(doc.createTextNode(this.validation.getFalsePositive() + ""));
      validation.appendChild(falsePositive);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(doc);
      LOGGER.info(
          "Written file: "
              + location
              + "\\results\\"
              + file.getName().substring(0, file.getName().length() - 5)
              + "-"
              + tableID
              + ".xml");
      File file2 =
          new File(
              location
                  + "\\results\\"
                  + file.getName().substring(0, file.getName().length() - 5)
                  + "-"
                  + tableID
                  + ".xml");
      Writer output = new BufferedWriter(new FileWriter(file2));
      StreamResult result = new StreamResult(output);

      // Output to console for testing
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      transformer.transform(source, result);
      output.close();
      System.out.println("File saved.");

    } catch (ParserConfigurationException pce) {
      pce.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }