Example #1
0
  /**
   * @param source
   * @param result
   * @param outputKeys
   */
  static void transform(Source source, Result result, Map<String, String> outputKeys) {

    Assertion.assertNotNull("source", source);
    Assertion.assertNotNull("result", result);

    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();
      if (outputKeys != null && !outputKeys.isEmpty()) {
        for (String name : outputKeys.keySet()) {
          String value = outputKeys.get(name);
          if (!TextUtil.isBlank(value)) {
            transformer.setOutputProperty(name, value);
          }
        }
      }
      transformer.transform(source, result);
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }
  public String display() {
    model.write(System.out, "TURTLE");
    System.out.println("create certitifact file ");
    String certificatePath = pref.getCertificatePath();

    FileOutputStream output;
    try {
      output = new FileOutputStream(certificatePath);
      model.write(output, "RDF/XML");
      signature.signXMLData(certificatePath);

      output = new FileOutputStream(certificatePath.replace(".xml", ".ttl"));
      model.write(output, "TURTLE");
      return certificatePath;
    } catch (FileNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
  public void setupDigestTransformation() {
    // Setup XSLT source for creating the digest of HAVE work products
    xsltResource = new ClassPathResource(xsltFilePath);
    if (!xsltResource.exists()) {
      log.error("Can't find XSLT to create HAVE digest: " + xsltFilePath);
    }

    xsltSource = null;
    try {
      xsltSource = new javax.xml.transform.stream.StreamSource(xsltResource.getInputStream());
    } catch (IOException e1) {
      log.error("Error reading " + xsltFilePath + "as XSLT source.");
    }

    // create an instance of TransformerFactory
    try {
      transformerFactory = javax.xml.transform.TransformerFactory.newInstance();
    } catch (TransformerFactoryConfigurationError e) {
      log.error("Error creating TransformerFactory for HAVE: " + e.getMessage());
    }

    // create the transformer
    try {
      transformer = transformerFactory.newTransformer(xsltSource);
    } catch (TransformerConfigurationException e) {
      log.error("Error creating Transformer for HAVE: " + e.getMessage());
    }
  }
Example #4
0
  public static String format(String xmlStr) { // Instantiate transformer input
    Source xmlInput = new StreamSource(new StringReader(xmlStr));
    StreamResult xmlOutput = new StreamResult(new StringWriter());

    // Configure transformer
    Transformer transformer;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage(), e);
      return xmlStr;
    } // An identity transformer

    try {
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      transformer.transform(xmlInput, xmlOutput);
    } catch (TransformerException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    }

    return xmlOutput.getWriter().toString();
  }
  /** Creates a batch file */
  private void createCpBatFile() {

    try {

      StreamSource xsltSource = new StreamSource(new File("src/main/resources/xslt/cpbat.xslt"));
      StreamSource xmlSource = new StreamSource(new File("project.xml"));
      Transformer t = TransformerFactory.newInstance().newTransformer(xsltSource);
      StreamResult cpBatResult =
          new StreamResult(new File("src/main/config/metaz/autogeneratedcp.bat"));

      t.transform(xmlSource, cpBatResult);

    } catch (TransformerConfigurationException e) {

      e.printStackTrace();

    } catch (TransformerFactoryConfigurationError e) {

      e.printStackTrace();

    } catch (TransformerException e) {

      e.printStackTrace();
    }
  }
Example #6
0
  /**
   * Pomocnicza klasa wysyłająca dokument XML do writera
   *
   * @param doc dokument, który chcemy wysłać
   * @param out Writer, do którego chcemy pisać
   */
  private void XML2Writer(Document doc, PrintWriter out) {
    Transformer transformer = null;

    try {

      transformer = TransformerFactory.newInstance().newTransformer();

    } catch (TransformerFactoryConfigurationError e) {

      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(doc);

    try {
      if (transformer != null) {
        transformer.transform(source, result);
      }
    } catch (TransformerException e) {

      e.printStackTrace();
    }
  }
Example #7
0
  /*
   * (non-Javadoc)
   * @see addressbook.model.PersistenceAccess#save()
   */
  public void save() throws IOException {

    // Create new DOM document
    Document document = null;
    try {
      document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    // Put content to document
    final Element ab = document.createElement("AddressBook");
    document.appendChild(ab);
    for (Entry e : entries) {

      // Create new Entry element in address book element
      final Element entry = document.createElement("Entry");
      ab.appendChild(entry);

      // Add name and gender
      entry.setAttribute("FirstName", e.getFirstName());
      entry.setAttribute("SurName", e.getSurName());
      entry.setAttribute("Gender", e.isMale() ? "M" : "F");
      entry.setAttribute("DateOfBirth", Entry.dateFormatter.print(e.getDateOfBirth()));

      // Add contact information
      final Element contact = document.createElement("Contact");
      if (e.getContactInformation() instanceof PhoneNumber) {
        contact.setAttribute("type", "phone");
      } else if (e.getContactInformation() instanceof EmailAddress) {
        contact.setAttribute("type", "email");
      }
      contact.setTextContent(e.getContactInformation().toString());
      entry.appendChild(contact);
    }

    // Write document to file
    final FileOutputStream out = new FileOutputStream(dataFile);
    try {
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(
          "{http://xml.apache.org/xslt}indent-amount", "2"); // Platform specific...
      transformer.transform(new DOMSource(document), new StreamResult(out));
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    out.close();
  }
  public void write(Document doc, String fileName, Boolean swing) {

    try {
      File f = new File(".");
      String appPath = f.getAbsolutePath().substring(0, f.getAbsolutePath().length() - 1);

      File fout =
          new File(
              appPath.substring(0, appPath.length() - 16)
                  + "SwingApp"
                  + File.separator
                  + "model"
                  + File.separator
                  + fileName
                  + ".xml");
      if (!swing) {
        // F:\workspace\github\KROKI-mockup-tool\ApplicationRepository\generated\model
        fout =
            new File(
                appPath.substring(0, appPath.length() - 16)
                    + "ApplicationRepository"
                    + File.separator
                    + "generated"
                    + File.separator
                    + File.separator
                    + "model"
                    + File.separator
                    + fileName
                    + ".xml");
      }
      if (!fout.getParentFile().exists())
        if (!fout.getParentFile().mkdirs()) {
          throw new IOException("Greska pri kreiranju izlaznog direktorijuma ");
        }

      System.out.println("XML Writer writing " + fout.getAbsolutePath());

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(fout);

      transformer.transform(source, result);
      System.out.println("[XML WRITER] " + fileName + ".xml datoteka generisana");
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (IllegalArgumentException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }
  /**
   * Extracts the workflow from the plan.
   *
   * @param plan the plan to extract the workflow from.
   * @return The workflow File
   * @throws PluginException if an error occurs extracting the workflow from the plan.
   */
  private File getWorkflowFile(final Document plan) throws PluginException {

    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();

    Writer writer = null;
    try {

      xpath.setNamespaceContext(new PlanNamespaceContext());
      final XPathExpression expr = xpath.compile(xpathSelectWorkflow);
      final Element elementWorkflow = (Element) expr.evaluate(plan, XPathConstants.NODE);

      // Prepare the DOM document for writing
      final Source source = new DOMSource(elementWorkflow);
      final File workflowFile = new File(new File(RODA_HOME, "data"), WORKFLOW_FILENAME);
      writer = new OutputStreamWriter(new FileOutputStream(workflowFile));
      final Result result = new StreamResult(writer);

      // Write the DOM document to the file
      final Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.transform(source, result);

      writer.close();

      return workflowFile;

    } catch (XPathExpressionException e) {
      logger.error("Error compiling XPATH expression or evaluating the plan - " + e.getMessage());
      throw new PluginException(
          "Error compiling XPATH expression or evaluating the plan - " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
      logger.error("Error opening output file for writting - " + e.getMessage());
      throw new PluginException("Error opening output file for writting - " + e.getMessage(), e);
    } catch (TransformerFactoryConfigurationError e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (TransformerException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (IOException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } finally {

      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          logger.error("Error closing output writer - " + e.getMessage());
        }
      }
    }
  }
 public void save(File file) {
   Transformer xformer;
   try {
     xformer = TransformerFactory.newInstance().newTransformer();
     xformer.transform(new DOMSource(document), new StreamResult(file));
   } catch (TransformerConfigurationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (TransformerFactoryConfigurationError e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (TransformerException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
 }
 private List<ContributorLanguageFact> createContLangFact(NodeList nodeList) {
   List<ContributorLanguageFact> list = new ArrayList<ContributorLanguageFact>();
   for (int i = 0; i < nodeList.getLength(); i++) {
     Node node = nodeList.item(i);
     try {
       XMLParser childParser = new XMLParser(XMLParser.getXmlStringFromNode(node));
       ContributorLanguageFact contributorLangFact =
           ContributorLanguageFactImpl.createContributorLanguageFact(childParser);
       list.add(contributorLangFact);
     } catch (TransformerFactoryConfigurationError e) {
       e.printStackTrace();
     } catch (TransformerException e) {
       e.printStackTrace();
     }
   }
   return list;
 }
Example #12
0
  public void testXSLTransformation() {
    try {
      System.out.println(TransformerFactory.newInstance().toString());

      Transformer trans =
          TransformerFactory.newInstance()
              .newTransformer(
                  new StreamSource(this.getClass().getResourceAsStream("/transformation.xsl")));
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      System.out.println(e.getLocalizedMessage());
      // fail();
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
      // fail();
    }
  }
Example #13
0
 /**
  * Returns a toString of indented XML file from doc.
  *
  * @param doc
  * @param indent
  * @return String XML file
  */
 public static String documentToString(Node doc, boolean indent) {
   StringWriter sw = new StringWriter();
   try {
     TransformerFactory tFactory = TransformerFactory.newInstance();
     if (indent) {
       tFactory.setAttribute("indent-number", 2);
     }
     Transformer transformer = tFactory.newTransformer();
     transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no");
     transformer.transform(new DOMSource(doc), new StreamResult(sw));
   } catch (TransformerConfigurationException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   } catch (TransformerFactoryConfigurationError e) {
     e.printStackTrace();
   }
   return sw.toString();
 }
 public String toString() {
   Transformer xformer;
   try {
     xformer = TransformerFactory.newInstance().newTransformer();
     StreamResult st = new StreamResult(new StringWriter());
     xformer.transform(new DOMSource(document), st);
     return st.getWriter().toString();
   } catch (TransformerConfigurationException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (TransformerFactoryConfigurationError e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   } catch (TransformerException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
Example #15
0
  public static boolean saveXml(String file, Document doc) {
    if (doc == null) {
      return false;
    }
    File f = new File(file);
    BukkitLogger.info("Saving data into file: " + f.getAbsolutePath());
    try {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      // doc.setXmlStandalone(true);

      if (PluginInfo.settingsXml.xslt != null && !PluginInfo.settingsXml.xslt.isEmpty()) {
        ProcessingInstruction pi =
            doc.createProcessingInstruction(
                "xml-stylesheet", "type=\"text/xsl\" href=\"" + PluginInfo.settingsXml.xslt + "\"");
        doc.insertBefore(pi, doc.getDocumentElement());
      }

      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(f);
      transformer.transform(source, result);
      return true;
    } catch (TransformerFactoryConfigurationError ex) {
      BukkitLogger.warning(
          "Transform Configuration Exception while saving XML file "
              + file
              + ": "
              + ex.getMessage());
    } catch (TransformerException ex) {
      BukkitLogger.warning(
          "Transform Exception while saving XML file " + file + ": " + ex.getMessage());
    } catch (Exception ex) {
      BukkitLogger.warning(
          "Unknown Exception while saving XML file " + file + ": " + ex.getMessage());
    }
    return false;
  }
 public static ResponseList<ContributorFact> createContributorFactList(HttpResponse res) {
   if (null == res) {
     return null;
   }
   XMLParser parser = new XMLParser(res.asString());
   NodeList nodelist = parser.getNodeList("response/result/contributor_fact");
   ResponseList<ContributorFact> list =
       new ResponseListImpl<ContributorFact>(nodelist.getLength(), res);
   for (int i = 0; i < nodelist.getLength(); i++) {
     Node node = nodelist.item(i);
     try {
       XMLParser childParser = new XMLParser(XMLParser.getXmlStringFromNode(node));
       ContributorFact contributorFact = new ContributorFactImpl(childParser, true);
       list.add(contributorFact);
     } catch (TransformerFactoryConfigurationError e) {
       e.printStackTrace();
     } catch (TransformerException e) {
       e.printStackTrace();
     }
   }
   return list;
 }
Example #17
0
  public void save(String url, Document doc) throws IOException {

    try {
      // Write the DOM document to the file
      // Prepare the output file
      Source source = new DOMSource(doc);
      File file = new File(url);
      Result result = new StreamResult(file);
      Transformer xformer;
      xformer = TransformerFactory.newInstance().newTransformer();
      xformer.transform(source, result);

    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Example #18
0
  /** Stores the instance data on a XML file located in the workspace root. */
  public static void saveInstances() {
    File path = DevicePlugin.getDeviceXmlLocation();
    File file = new File(path, DevicePlugin.getDeviceXmlFileName());

    Document document = createDocument(file);

    if (document != null) {

      try {
        Element root = document.getDocumentElement();
        Element instancesRoot = createInstancesElement(document);
        root.appendChild(instancesRoot);

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // $NON-NLS-1$

        file.getParentFile().mkdirs();
        // initialize FileOutputStream with File object to save to file
        FileOutputStream outputStream = new FileOutputStream(file.getAbsoluteFile());
        StreamResult result = new StreamResult(outputStream);
        DOMSource source = new DOMSource(document);
        transformer.transform(source, result);
        outputStream.close();

      } catch (IOException ie) {
        ie.printStackTrace();
      } catch (TransformerConfigurationException e) {
        e.printStackTrace();
      } catch (TransformerFactoryConfigurationError e) {
        e.printStackTrace();
      } catch (TransformerException e) {
        e.printStackTrace();
      }
    }
  }
Example #19
0
  /** Test menu. */
  public void testMenu() {
    try {
      System.out.println();
      System.out.println("[BEGIN] ******* TEST --- testMenu() ");
      MenuParser parser = new MenuParser();
      InputStream is = MenuTest.class.getResourceAsStream("menu.xml");
      IMenu menu = parser.parse(is);
      // MenuVisitor visitor = new MenuVisitor(menu);
      IMenu menu2 = (IMenu) menu.find("m0.m2");
      ResourceBundle bundle = ResourceBundle.getBundle("com.code.aon.test.ui.menu.messages");
      MenuVisitor visitor = new MenuVisitor(menu2, bundle);
      SAXSource source = new SAXSource(visitor, new InputSource());
      StreamResult result = new StreamResult(System.out);
      TransformerFactory f = TransformerFactory.newInstance();
      Transformer t = f.newTransformer();
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.transform(source, result);

      System.out.println("[END] ******* TEST --- testMenu() ");
      System.out.println();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
      fail(e.getMessage());
    } catch (IOException e) {
      e.printStackTrace();
      fail(e.getMessage());
    } catch (SAXException e) {
      e.printStackTrace();
      fail(e.getMessage());
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
      fail(e.getMessage());
    } catch (TransformerException e) {
      e.printStackTrace();
      fail(e.getMessage());
    }
  }
Example #20
0
    public void save(IStorage file, org.davinci.server.review.user.IDesignerUser user) {
      OutputStream out = null;
      try {
        if (!file.exists())
          try {
            file.createNewFile();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

        try {
          out = file.getOutputStream();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();

        Element rootElement = document.createElement("user");
        document.appendChild(rootElement);

        Element latestVersionElement = document.createElement("latestVersion");
        latestVersionElement.setAttribute("id", user.getLatestVersion().getVersionID());
        latestVersionElement.setAttribute("title", user.getLatestVersion().getVersionTitle());
        latestVersionElement.setAttribute("time", user.getLatestVersion().getTime());

        rootElement.appendChild(latestVersionElement);

        for (Version version : user.getVersions()) {
          Element element = document.createElement("version");
          element.setAttribute("id", version.getVersionID());
          element.setAttribute("title", version.getVersionTitle());
          element.setAttribute("time", version.getTime());
          element.setAttribute("isDraft", version.isDraft() ? "true" : "false");
          element.setAttribute("dueDate", version.dueDateString());
          element.setAttribute("desireWidth", version.getDesireWidth() + "");
          element.setAttribute("desireHeight", version.getDesireHeight() + "");
          element.setAttribute(
              "hasClosedManually", Boolean.toString(version.isHasClosedManually()));
          element.setAttribute("restartFrom", version.getRestartFrom());
          element.setAttribute("description", version.getDescription());
          element.setAttribute("receiveEmail", version.isReceiveEmail() ? "true" : "false");
          element.setAttribute("hasRestarted", version.isHasRestarted() ? "true" : "false");
          for (Reviewer reviewer : version.getReviewers()) {
            Element reviewerElement = document.createElement("reviewer");
            reviewerElement.setAttribute("name", reviewer.getUserName());
            reviewerElement.setAttribute("email", reviewer.getEmail());

            element.appendChild(reviewerElement);
          }
          for (String resource : version.resources) {
            Element resourceElement = document.createElement("resource");
            resourceElement.setAttribute("path", resource);
            element.appendChild(resourceElement);
          }
          rootElement.appendChild(element);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(out);

        transformer.transform(source, result);

      } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } finally {
        try {
          if (out != null) {
            out.close();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
Example #21
0
  public boolean compile(
      final VoltCompiler compiler,
      final String jarPath,
      final int sitesPerHost,
      final int hostCount,
      final int replication,
      final String leaderAddress) {
    assert (jarPath != null);
    assert (sitesPerHost >= 1);
    assert (hostCount >= 1);
    assert (leaderAddress != null);

    // this stuff could all be converted to org.voltdb.compiler.projectfile.*
    // jaxb objects and (WE ARE!) marshaled to XML. Just needs some elbow grease.

    DocumentBuilderFactory docFactory;
    DocumentBuilder docBuilder;
    Document doc;
    try {
      docFactory = DocumentBuilderFactory.newInstance();
      docBuilder = docFactory.newDocumentBuilder();
      doc = docBuilder.newDocument();
    } catch (final ParserConfigurationException e) {
      e.printStackTrace();
      return false;
    }

    // <project>
    final Element project = doc.createElement("project");
    doc.appendChild(project);

    // <security>
    final Element security = doc.createElement("security");
    security.setAttribute("enabled", Boolean.valueOf(m_securityEnabled).toString());
    project.appendChild(security);

    // <database>
    final Element database = doc.createElement("database");
    database.setAttribute("name", "database");
    database.setAttribute("project", this.project_name);
    project.appendChild(database);
    buildDatabaseElement(doc, database);

    // boilerplate to write this DOM object to file.
    StreamResult result;
    try {
      final Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      result = new StreamResult(new StringWriter());
      final DOMSource domSource = new DOMSource(doc);
      transformer.transform(domSource, result);
    } catch (final TransformerConfigurationException e) {
      e.printStackTrace();
      return false;
    } catch (final TransformerFactoryConfigurationError e) {
      e.printStackTrace();
      return false;
    } catch (final TransformerException e) {
      e.printStackTrace();
      return false;
    }

    //        String xml = result.getWriter().toString();
    //        System.out.println(xml);

    final File projectFile = writeStringToTempFile(result.getWriter().toString());
    final String projectPath = projectFile.getPath();
    LOG.debug("PROJECT XML: " + projectPath);

    ClusterConfig cc =
        (this.cluster_config.isEmpty()
            ? new ClusterConfig(hostCount, sitesPerHost, replication, leaderAddress)
            : this.cluster_config);
    final boolean success =
        compiler.compile(projectPath, cc, jarPath, m_compilerDebugPrintStream, m_procInfoOverrides);

    // HACK: If we have a ParameterMappingsSet that we need to apply
    // either from a file or a fixed mappings, then we have
    // to load the catalog into this JVM, apply the mappings, and then
    // update the jar file with the new catalog
    if (m_paramMappingsFile != null || m_paramMappings.isEmpty() == false) {
      File jarFile = new File(jarPath);
      Catalog catalog = CatalogUtil.loadCatalogFromJar(jarFile);
      assert (catalog != null);
      Database catalog_db = CatalogUtil.getDatabase(catalog);

      this.applyParameterMappings(catalog_db);

      // Construct a List of prefetchable Statements
      this.applyPrefetchableFlags(catalog_db);

      // Write it out!
      try {
        CatalogUtil.updateCatalogInJar(jarFile, catalog, m_paramMappingsFile);
      } catch (Exception ex) {
        String msg = "Failed to updated Catalog in jar file '" + jarPath + "'";
        throw new RuntimeException(msg, ex);
      }
    }

    return success;
  }
Example #22
0
    public void save(IStorage file, org.davinci.server.review.user.Reviewer reviewer) {
      OutputStream out = null;
      try {
        if (!file.exists())
          try {
            file.createNewFile();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }

        try {
          out = file.getOutputStream();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();

        Element rootElement = document.createElement("reviewer");
        document.appendChild(rootElement);

        Iterator<ReviewerVersion> iterator = reviewer.getReviewerVersions();
        while (iterator.hasNext()) {
          ReviewerVersion version = iterator.next();
          Element element = document.createElement("version");
          element.setAttribute("designerID", version.getDesignerID());
          element.setAttribute("time", version.getTimeVersion());
          rootElement.appendChild(element);
        }

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // $NON-NLS-1$
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$
        DOMSource source = new DOMSource(document);
        StreamResult result = new StreamResult(out);

        transformer.transform(source, result);

      } catch (TransformerFactoryConfigurationError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (TransformerConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } finally {
        try {
          if (out != null) {
            out.close();
          }
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
Example #23
0
  /**
   * Show a "Save as" dialog.
   *
   * @param plot The plot to be exported.
   * @param width The width of the exported image (when export to JPEG/PNG).
   * @param height The height of the exported image (when export to JPEG/PNG).
   * @return Result from {@link JFileChooser#showSaveDialog}
   */
  public static int showSaveDialog(SVGPlot plot, int width, int height) {
    double quality = 1.0;
    int ret = -1;

    JFileChooser fc = new JFileChooser(new File("."));
    fc.setDialogTitle(DEFAULT_TITLE);
    // fc.setFileFilter(new ImageFilter());
    SaveOptionsPanel optionsPanel = new SaveOptionsPanel(fc, width, height);
    fc.setAccessory(optionsPanel);

    ret = fc.showSaveDialog(null);
    fc.setDialogTitle("Saving... Please wait.");
    if (ret == JFileChooser.APPROVE_OPTION) {
      File file = fc.getSelectedFile();
      String format = optionsPanel.getSelectedFormat();
      if (format == null || automagic_format.equals(format)) {
        format = guessFormat(file.getName());
      }
      try {
        if (format == null) {
          showError(fc, "Error saving image.", "File format not recognized.");
        } else if ("jpeg".equals(format) || "jpg".equals(format)) {
          quality = optionsPanel.getJPEGQuality();
          plot.saveAsJPEG(file, width, height, quality);
        } else if ("png".equals(format)) {
          plot.saveAsPNG(file, width, height);
        } else if ("ps".equals(format)) {
          plot.saveAsPS(file);
        } else if ("eps".equals(format)) {
          plot.saveAsEPS(file);
        } else if ("pdf".equals(format)) {
          plot.saveAsPDF(file);
        } else if ("svg".equals(format)) {
          plot.saveAsSVG(file);
        } else {
          showError(fc, "Error saving image.", "Unsupported format: " + format);
        }
      } catch (java.lang.IncompatibleClassChangeError e) {
        showError(
            fc,
            "Error saving image.",
            "It seems that your Java version is incompatible with this version of Batik and Jpeg writing. Sorry.");
      } catch (ClassNotFoundException e) {
        showError(
            fc,
            "Error saving image.",
            "A class was not found when saving this image. Maybe installing Apache FOP will help (for PDF, PS and EPS output).\n"
                + e.toString());
      } catch (IOException e) {
        LOG.exception(e);
        showError(fc, "Error saving image.", e.toString());
      } catch (TranscoderException e) {
        LOG.exception(e);
        showError(fc, "Error saving image.", e.toString());
      } catch (TransformerFactoryConfigurationError e) {
        LOG.exception(e);
        showError(fc, "Error saving image.", e.toString());
      } catch (TransformerException e) {
        LOG.exception(e);
        showError(fc, "Error saving image.", e.toString());
      } catch (Exception e) {
        LOG.exception(e);
        showError(fc, "Error saving image.", e.toString());
      }
    } else if (ret == JFileChooser.ERROR_OPTION) {
      showError(fc, "Error in file dialog.", "Unknown Error.");
    } else if (ret == JFileChooser.CANCEL_OPTION) {
      // do nothing - except return result
    }
    return ret;
  }
Example #24
0
  // J2SE does not support Xalan interpretive
  // main -> _main
  public static void _main(String argv[]) {

    // Runtime.getRuntime().traceMethodCalls(false); // turns Java tracing off
    boolean doStackDumpOnError = false;
    boolean setQuietMode = false;
    boolean doDiag = false;
    String msg = null;
    boolean isSecureProcessing = false;

    // Runtime.getRuntime().traceMethodCalls(false);
    // Runtime.getRuntime().traceInstructions(false);

    /** The default diagnostic writer... */
    java.io.PrintWriter diagnosticsWriter = new PrintWriter(System.err, true);
    java.io.PrintWriter dumpWriter = diagnosticsWriter;
    ResourceBundle resbundle =
        (SecuritySupport.getResourceBundle(
            com.sun.org.apache.xml.internal.utils.res.XResourceBundle.ERROR_RESOURCES));
    String flavor = "s2s";

    if (argv.length < 1) {
      printArgOptions(resbundle);
    } else {
      // J2SE does not support Xalan interpretive
      // false -> true
      boolean useXSLTC = true;
      for (int i = 0; i < argv.length; i++) {
        if ("-XSLTC".equalsIgnoreCase(argv[i])) {
          useXSLTC = true;
        }
      }

      TransformerFactory tfactory;
      if (useXSLTC) {
        String key = "javax.xml.transform.TransformerFactory";
        String value = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl";
        Properties props = System.getProperties();
        props.put(key, value);
        System.setProperties(props);
      }

      try {
        tfactory = TransformerFactory.newInstance();
        tfactory.setErrorListener(new DefaultErrorHandler());
      } catch (TransformerFactoryConfigurationError pfe) {
        pfe.printStackTrace(dumpWriter);
        //      "XSL Process was not successful.");
        msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
        diagnosticsWriter.println(msg);

        tfactory = null; // shut up compiler

        doExit(msg);
      }

      boolean formatOutput = false;
      boolean useSourceLocation = false;
      String inFileName = null;
      String outFileName = null;
      String dumpFileName = null;
      String xslFileName = null;
      String treedumpFileName = null;
      // J2SE does not support Xalan interpretive
      /*
      PrintTraceListener tracer = null;
      */
      String outputType = null;
      String media = null;
      Vector params = new Vector();
      boolean quietConflictWarnings = false;
      URIResolver uriResolver = null;
      EntityResolver entityResolver = null;
      ContentHandler contentHandler = null;
      int recursionLimit = -1;

      for (int i = 0; i < argv.length; i++) {
        if ("-XSLTC".equalsIgnoreCase(argv[i])) {
          // The -XSLTC option has been processed.
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-TT".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceTemplates = true;
          }
          else
            printInvalidXSLTCOption("-TT");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TG".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceGeneration = true;
          }
          else
            printInvalidXSLTCOption("-TG");

          // tfactory.setTraceSelect(true);
        }
        else if ("-TS".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceSelection = true;
          }
          else
            printInvalidXSLTCOption("-TS");

          // tfactory.setTraceTemplates(true);
        }
        else if ("-TTC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (null == tracer)
              tracer = new PrintTraceListener(diagnosticsWriter);

            tracer.m_traceElements = true;
          }
          else
            printInvalidXSLTCOption("-TTC");

          // tfactory.setTraceTemplateChildren(true);
        }
        */
        else if ("-INDENT".equalsIgnoreCase(argv[i])) {
          int indentAmount;

          if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
            indentAmount = Integer.parseInt(argv[++i]);
          } else {
            indentAmount = 0;
          }

          // TBD:
          // xmlProcessorLiaison.setIndent(indentAmount);
        } else if ("-IN".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') inFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-IN"})); // "Missing argument for);
        } else if ("-MEDIA".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) media = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-MEDIA"})); // "Missing argument for);
        } else if ("-OUT".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') outFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-OUT"})); // "Missing argument for);
        } else if ("-XSL".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') xslFileName = argv[++i];
          else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-XSL"})); // "Missing argument for);
        } else if ("-FLAVOR".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            flavor = argv[++i];
          } else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-FLAVOR"})); // "Missing argument for);
        } else if ("-PARAM".equalsIgnoreCase(argv[i])) {
          if (i + 2 < argv.length) {
            String name = argv[++i];

            params.addElement(name);

            String expression = argv[++i];

            params.addElement(expression);
          } else
            System.err.println(
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-PARAM"})); // "Missing argument for);
        } else if ("-E".equalsIgnoreCase(argv[i])) {

          // TBD:
          // xmlProcessorLiaison.setShouldExpandEntityRefs(false);
        } else if ("-V".equalsIgnoreCase(argv[i])) {
          diagnosticsWriter.println(
              resbundle.getString("version") // ">>>>>>> Xalan Version "
                  + Version.getVersion()
                  + ", "
                  +

                  /* xmlProcessorLiaison.getParserDescription()+ */
                  resbundle.getString("version2")); // "<<<<<<<");
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-QC".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            quietConflictWarnings = true;
          else
            printInvalidXSLTCOption("-QC");
        }
        */
        else if ("-Q".equalsIgnoreCase(argv[i])) {
          setQuietMode = true;
        } else if ("-DIAG".equalsIgnoreCase(argv[i])) {
          doDiag = true;
        } else if ("-XML".equalsIgnoreCase(argv[i])) {
          outputType = "xml";
        } else if ("-TEXT".equalsIgnoreCase(argv[i])) {
          outputType = "text";
        } else if ("-HTML".equalsIgnoreCase(argv[i])) {
          outputType = "html";
        } else if ("-EDUMP".equalsIgnoreCase(argv[i])) {
          doStackDumpOnError = true;

          if (((i + 1) < argv.length) && (argv[i + 1].charAt(0) != '-')) {
            dumpFileName = argv[++i];
          }
        } else if ("-URIRESOLVER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              uriResolver = (URIResolver) ObjectFactory.newInstance(argv[++i], true);

              tfactory.setURIResolver(uriResolver);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-URIResolver"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                    new Object[] {"-URIResolver"}); // "Missing argument for);
            System.err.println(msg);
            doExit(msg);
          }
        } else if ("-ENTITYRESOLVER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              entityResolver = (EntityResolver) ObjectFactory.newInstance(argv[++i], true);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-EntityResolver"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            //            "Missing argument for);
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-EntityResolver"});
            System.err.println(msg);
            doExit(msg);
          }
        } else if ("-CONTENTHANDLER".equalsIgnoreCase(argv[i])) {
          if (i + 1 < argv.length) {
            try {
              contentHandler = (ContentHandler) ObjectFactory.newInstance(argv[++i], true);
            } catch (ConfigurationError cnfe) {
              msg =
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_CLASS_NOT_FOUND_FOR_OPTION,
                      new Object[] {"-ContentHandler"});
              System.err.println(msg);
              doExit(msg);
            }
          } else {
            //            "Missing argument for);
            msg =
                XSLMessages.createMessage(
                    XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION, new Object[] {"-ContentHandler"});
            System.err.println(msg);
            doExit(msg);
          }
        }
        // J2SE does not support Xalan interpretive
        /*
        else if ("-L".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            tfactory.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
          else
            printInvalidXSLTCOption("-L");
        }
        else if ("-INCREMENTAL".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
            tfactory.setAttribute
              ("http://xml.apache.org/xalan/features/incremental",
               java.lang.Boolean.TRUE);
          else
            printInvalidXSLTCOption("-INCREMENTAL");
        }
        else if ("-NOOPTIMIZE".equalsIgnoreCase(argv[i]))
        {
          // Default is true.
          //
          // %REVIEW% We should have a generalized syntax for negative
          // switches...  and probably should accept the inverse even
          // if it is the default.
          if (!useXSLTC)
            tfactory.setAttribute
              ("http://xml.apache.org/xalan/features/optimize",
               java.lang.Boolean.FALSE);
          else
            printInvalidXSLTCOption("-NOOPTIMIZE");
        }
        else if ("-RL".equalsIgnoreCase(argv[i]))
        {
          if (!useXSLTC)
          {
            if (i + 1 < argv.length)
              recursionLimit = Integer.parseInt(argv[++i]);
            else
              System.err.println(
                XSLMessages.createMessage(
                  XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                  new Object[]{ "-rl" }));  //"Missing argument for);
          }
          else
          {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
             i++;

            printInvalidXSLTCOption("-RL");
          }
        }
        */
        // Generate the translet class and optionally specify the name
        // of the translet class.
        else if ("-XO".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
              tfactory.setAttribute("generate-translet", "true");
              tfactory.setAttribute("translet-name", argv[++i]);
            } else tfactory.setAttribute("generate-translet", "true");
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;
            printInvalidXalanOption("-XO");
          }
        }
        // Specify the destination directory for the translet classes.
        else if ("-XD".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
              tfactory.setAttribute("destination-directory", argv[++i]);
            else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XD"})); // "Missing argument for);

          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XD");
          }
        }
        // Specify the jar file name which the translet classes are packaged into.
        else if ("-XJ".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') {
              tfactory.setAttribute("generate-translet", "true");
              tfactory.setAttribute("jar-name", argv[++i]);
            } else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XJ"})); // "Missing argument for);
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XJ");
          }

        }
        // Specify the package name prefix for the generated translet classes.
        else if ("-XP".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-')
              tfactory.setAttribute("package-name", argv[++i]);
            else
              System.err.println(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_MISSING_ARG_FOR_OPTION,
                      new Object[] {"-XP"})); // "Missing argument for);
          } else {
            if (i + 1 < argv.length && argv[i + 1].charAt(0) != '-') i++;

            printInvalidXalanOption("-XP");
          }

        }
        // Enable template inlining.
        else if ("-XN".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("enable-inlining", "true");
          } else printInvalidXalanOption("-XN");
        }
        // Turns on additional debugging message output
        else if ("-XX".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("debug", "true");
          } else printInvalidXalanOption("-XX");
        }
        // Create the Transformer from the translet if the translet class is newer
        // than the stylesheet.
        else if ("-XT".equalsIgnoreCase(argv[i])) {
          if (useXSLTC) {
            tfactory.setAttribute("auto-translet", "true");
          } else printInvalidXalanOption("-XT");
        } else if ("-SECURE".equalsIgnoreCase(argv[i])) {
          isSecureProcessing = true;
          try {
            tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
          } catch (TransformerConfigurationException e) {
          }
        } else
          System.err.println(
              XSLMessages.createMessage(
                  XSLTErrorResources.ER_INVALID_OPTION,
                  new Object[] {argv[i]})); // "Invalid argument:);
      }

      // Print usage instructions if no xml and xsl file is specified in the command line
      if (inFileName == null && xslFileName == null) {
        msg = resbundle.getString("xslProc_no_input");
        System.err.println(msg);
        doExit(msg);
      }

      // Note that there are usage cases for calling us without a -IN arg
      // The main XSL transformation occurs here!
      try {
        long start = System.currentTimeMillis();

        if (null != dumpFileName) {
          dumpWriter = new PrintWriter(new FileWriter(dumpFileName));
        }

        Templates stylesheet = null;

        if (null != xslFileName) {
          if (flavor.equals("d2d")) {

            // Parse in the xml data into a DOM
            DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

            dfactory.setNamespaceAware(true);

            if (isSecureProcessing) {
              try {
                dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
              } catch (ParserConfigurationException pce) {
              }
            }

            DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
            Node xslDOM = docBuilder.parse(new InputSource(xslFileName));

            stylesheet = tfactory.newTemplates(new DOMSource(xslDOM, xslFileName));
          } else {
            // System.out.println("Calling newTemplates: "+xslFileName);
            stylesheet = tfactory.newTemplates(new StreamSource(xslFileName));
            // System.out.println("Done calling newTemplates: "+xslFileName);
          }
        }

        PrintWriter resultWriter;
        StreamResult strResult;

        if (null != outFileName) {
          strResult = new StreamResult(new FileOutputStream(outFileName));
          // One possible improvement might be to ensure this is
          //  a valid URI before setting the systemId, but that
          //  might have subtle changes that pre-existing users
          //  might notice; we can think about that later -sc r1.46
          strResult.setSystemId(outFileName);
        } else {
          strResult = new StreamResult(System.out);
          // We used to default to incremental mode in this case.
          // We've since decided that since the -INCREMENTAL switch is
          // available, that default is probably not necessary nor
          // necessarily a good idea.
        }

        SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;

        // J2SE does not support Xalan interpretive
        /*
                // This is currently controlled via TransformerFactoryImpl.
        if (!useXSLTC && useSourceLocation)
           stf.setAttribute(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);
        */

        // Did they pass in a stylesheet, or should we get it from the
        // document?
        if (null == stylesheet) {
          Source source =
              stf.getAssociatedStylesheet(new StreamSource(inFileName), media, null, null);

          if (null != source) stylesheet = tfactory.newTemplates(source);
          else {
            if (null != media)
              throw new TransformerException(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_NO_STYLESHEET_IN_MEDIA,
                      new Object[] {inFileName, media})); // "No stylesheet found in: "
            // + inFileName + ", media="
            // + media);
            else
              throw new TransformerException(
                  XSLMessages.createMessage(
                      XSLTErrorResources.ER_NO_STYLESHEET_PI,
                      new Object[] {inFileName})); // "No xml-stylesheet PI found in: "
            // + inFileName);
          }
        }

        if (null != stylesheet) {
          Transformer transformer = flavor.equals("th") ? null : stylesheet.newTransformer();
          transformer.setErrorListener(new DefaultErrorHandler());

          // Override the output format?
          if (null != outputType) {
            transformer.setOutputProperty(OutputKeys.METHOD, outputType);
          }

          // J2SE does not support Xalan interpretive
          /*
          if (transformer instanceof com.sun.org.apache.xalan.internal.transformer.TransformerImpl)
          {
            com.sun.org.apache.xalan.internal.transformer.TransformerImpl impl = (com.sun.org.apache.xalan.internal.transformer.TransformerImpl)transformer;
            TraceManager tm = impl.getTraceManager();

            if (null != tracer)
              tm.addTraceListener(tracer);

            impl.setQuietConflictWarnings(quietConflictWarnings);

                        // This is currently controlled via TransformerFactoryImpl.
            if (useSourceLocation)
              impl.setProperty(XalanProperties.SOURCE_LOCATION, Boolean.TRUE);

            if(recursionLimit>0)
              impl.setRecursionLimit(recursionLimit);

            // sc 28-Feb-01 if we re-implement this, please uncomment helpmsg in printArgOptions
            // impl.setDiagnosticsOutput( setQuietMode ? null : diagnosticsWriter );
          }
          */

          int nParams = params.size();

          for (int i = 0; i < nParams; i += 2) {
            transformer.setParameter(
                (String) params.elementAt(i), (String) params.elementAt(i + 1));
          }

          if (uriResolver != null) transformer.setURIResolver(uriResolver);

          if (null != inFileName) {
            if (flavor.equals("d2d")) {

              // Parse in the xml data into a DOM
              DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();

              dfactory.setCoalescing(true);
              dfactory.setNamespaceAware(true);

              if (isSecureProcessing) {
                try {
                  dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                } catch (ParserConfigurationException pce) {
                }
              }

              DocumentBuilder docBuilder = dfactory.newDocumentBuilder();

              if (entityResolver != null) docBuilder.setEntityResolver(entityResolver);

              Node xmlDoc = docBuilder.parse(new InputSource(inFileName));
              Document doc = docBuilder.newDocument();
              org.w3c.dom.DocumentFragment outNode = doc.createDocumentFragment();

              transformer.transform(new DOMSource(xmlDoc, inFileName), new DOMResult(outNode));

              // Now serialize output to disk with identity transformer
              Transformer serializer = stf.newTransformer();
              serializer.setErrorListener(new DefaultErrorHandler());

              Properties serializationProps = stylesheet.getOutputProperties();

              serializer.setOutputProperties(serializationProps);

              if (contentHandler != null) {
                SAXResult result = new SAXResult(contentHandler);

                serializer.transform(new DOMSource(outNode), result);
              } else serializer.transform(new DOMSource(outNode), strResult);
            } else if (flavor.equals("th")) {
              for (int i = 0; i < 1; i++) // Loop for diagnosing bugs with inconsistent behavior
              {
                // System.out.println("Testing the TransformerHandler...");

                XMLReader reader = null;

                // Use JAXP1.1 ( if possible )
                try {
                  javax.xml.parsers.SAXParserFactory factory =
                      javax.xml.parsers.SAXParserFactory.newInstance();

                  factory.setNamespaceAware(true);

                  if (isSecureProcessing) {
                    try {
                      factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException se) {
                    }
                  }

                  javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();

                  reader = jaxpParser.getXMLReader();
                } catch (javax.xml.parsers.ParserConfigurationException ex) {
                  throw new org.xml.sax.SAXException(ex);
                } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
                  throw new org.xml.sax.SAXException(ex1.toString());
                } catch (NoSuchMethodError ex2) {
                } catch (AbstractMethodError ame) {
                }

                if (null == reader) {
                  reader = XMLReaderFactory.createXMLReader();
                }

                // J2SE does not support Xalan interpretive
                /*
                if (!useXSLTC)
                  stf.setAttribute(com.sun.org.apache.xalan.internal.processor.TransformerFactoryImpl.FEATURE_INCREMENTAL,
                     Boolean.TRUE);
                */

                TransformerHandler th = stf.newTransformerHandler(stylesheet);

                reader.setContentHandler(th);
                reader.setDTDHandler(th);

                if (th instanceof org.xml.sax.ErrorHandler)
                  reader.setErrorHandler((org.xml.sax.ErrorHandler) th);

                try {
                  reader.setProperty("http://xml.org/sax/properties/lexical-handler", th);
                } catch (org.xml.sax.SAXNotRecognizedException e) {
                } catch (org.xml.sax.SAXNotSupportedException e) {
                }
                try {
                  reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
                } catch (org.xml.sax.SAXException se) {
                }

                th.setResult(strResult);

                reader.parse(new InputSource(inFileName));
              }
            } else {
              if (entityResolver != null) {
                XMLReader reader = null;

                // Use JAXP1.1 ( if possible )
                try {
                  javax.xml.parsers.SAXParserFactory factory =
                      javax.xml.parsers.SAXParserFactory.newInstance();

                  factory.setNamespaceAware(true);

                  if (isSecureProcessing) {
                    try {
                      factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
                    } catch (org.xml.sax.SAXException se) {
                    }
                  }

                  javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();

                  reader = jaxpParser.getXMLReader();
                } catch (javax.xml.parsers.ParserConfigurationException ex) {
                  throw new org.xml.sax.SAXException(ex);
                } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
                  throw new org.xml.sax.SAXException(ex1.toString());
                } catch (NoSuchMethodError ex2) {
                } catch (AbstractMethodError ame) {
                }

                if (null == reader) {
                  reader = XMLReaderFactory.createXMLReader();
                }

                reader.setEntityResolver(entityResolver);

                if (contentHandler != null) {
                  SAXResult result = new SAXResult(contentHandler);

                  transformer.transform(new SAXSource(reader, new InputSource(inFileName)), result);
                } else {
                  transformer.transform(
                      new SAXSource(reader, new InputSource(inFileName)), strResult);
                }
              } else if (contentHandler != null) {
                SAXResult result = new SAXResult(contentHandler);

                transformer.transform(new StreamSource(inFileName), result);
              } else {
                // System.out.println("Starting transform");
                transformer.transform(new StreamSource(inFileName), strResult);
                // System.out.println("Done with transform");
              }
            }
          } else {
            StringReader reader = new StringReader("<?xml version=\"1.0\"?> <doc/>");

            transformer.transform(new StreamSource(reader), strResult);
          }
        } else {
          //          "XSL Process was not successful.");
          msg = XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL, null);
          diagnosticsWriter.println(msg);
          doExit(msg);
        }

        // close output streams
        if (null != outFileName && strResult != null) {
          java.io.OutputStream out = strResult.getOutputStream();
          java.io.Writer writer = strResult.getWriter();
          try {
            if (out != null) out.close();
            if (writer != null) writer.close();
          } catch (java.io.IOException ie) {
          }
        }

        long stop = System.currentTimeMillis();
        long millisecondsDuration = stop - start;

        if (doDiag) {
          Object[] msgArgs = new Object[] {inFileName, xslFileName, new Long(millisecondsDuration)};
          msg = XSLMessages.createMessage("diagTiming", msgArgs);
          diagnosticsWriter.println('\n');
          diagnosticsWriter.println(msg);
        }

      } catch (Throwable throwable) {
        while (throwable instanceof com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) {
          throwable =
              ((com.sun.org.apache.xml.internal.utils.WrappedRuntimeException) throwable)
                  .getException();
        }

        if ((throwable instanceof NullPointerException)
            || (throwable instanceof ClassCastException)) doStackDumpOnError = true;

        diagnosticsWriter.println();

        if (doStackDumpOnError) throwable.printStackTrace(dumpWriter);
        else {
          DefaultErrorHandler.printLocation(diagnosticsWriter, throwable);
          diagnosticsWriter.println(
              XSLMessages.createMessage(XSLTErrorResources.ER_XSLT_ERROR, null)
                  + " ("
                  + throwable.getClass().getName()
                  + "): "
                  + throwable.getMessage());
        }

        // diagnosticsWriter.println(XSLMessages.createMessage(XSLTErrorResources.ER_NOT_SUCCESSFUL,
        // null)); //"XSL Process was not successful.");
        if (null != dumpFileName) {
          dumpWriter.close();
        }

        doExit(throwable.getMessage());
      }

      if (null != dumpFileName) {
        dumpWriter.close();
      }

      if (null != diagnosticsWriter) {

        // diagnosticsWriter.close();
      }

      // if(!setQuietMode)
      //  diagnosticsWriter.println(resbundle.getString("xsldone")); //"Xalan: done");
      // else
      // diagnosticsWriter.println("");  //"Xalan: done");
    }
  }
  /**
   * Support method for main program. This support method can also be invoked from subclasses that
   * support the same command line interface
   *
   * @param args the command-line arguments
   * @param name name of the class, to be used in error messages
   */
  protected void doQuery(String args[], String name) {
    boolean showTime = false;
    int repeat = 1;
    String sourceFileName = null;
    String queryFileName = null;
    File sourceFile;
    File outputFile;
    boolean useURLs = false;
    String outputFileName = null;
    boolean explain = false;
    boolean wrap = false;
    boolean pullMode = false;

    boolean schemaAware = false;
    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-sa")) {
        schemaAware = true;
      } else if (args[i].equals("-val")) {
        schemaAware = true;
      } else if (args[i].equals("-vlax")) {
        schemaAware = true;
      } else if (args[i].equals("-p")) {
        schemaAware = true;
      }
    }

    config = makeConfiguration(schemaAware);
    config.setHostLanguage(Configuration.XQUERY);

    StaticQueryContext staticEnv = new StaticQueryContext(config);
    DynamicQueryContext dynamicEnv = new DynamicQueryContext(config);

    Properties outputProps = new Properties();

    // Check the command-line arguments.

    try {
      int i = 0;
      while (i < args.length) {

        if (args[i].charAt(0) == '-') {

          if (args[i].equals("-cr")) {
            i++;
            if (args.length < i + 1) {
              badUsage(name, "No output file name");
            }
            String crclass = args[i++];
            Object resolver = config.getInstance(crclass, null);
            if (!(resolver instanceof CollectionURIResolver)) {
              quit(crclass + " is not a CollectionURIResolver", 2);
            }
            config.setCollectionURIResolver((CollectionURIResolver) resolver);

          } else if (args[i].equals("-ds")) {
            config.setTreeModel(Builder.LINKED_TREE);
            i++;
          } else if (args[i].equals("-dt")) {
            config.setTreeModel(Builder.TINY_TREE);
            i++;
          } else if (args[i].equals("-e")) {
            explain = true;
            i++;
          } else if (args[i].equals("-l")) {
            config.setLineNumbering(true);
            i++;
          } else if (args[i].equals("-3")) { // undocumented option: do it thrice
            i++;
            repeat = 3;
          } else if (args[i].equals("-9")) { // undocumented option: do it nine times
            i++;
            repeat = 9;
          } else if (args[i].equals("-mr")) {
            i++;
            if (args.length < i + 1) {
              badUsage(name, "No ModuleURIResolver class");
            }
            String r = args[i++];
            config.setModuleURIResolver(r);
          } else if (args[i].equals("-noext")) {
            i++;
            config.setAllowExternalFunctions(false);
          } else if (args[i].equals("-o")) {
            i++;
            if (args.length < i + 1) {
              badUsage(name, "No output file name");
            }
            outputFileName = args[i++];
          } else if (args[i].equals("-p")) {
            i++;
            setPOption(config);
            useURLs = true;
          } else if (args[i].equals("-pull")) {
            i++;
            pullMode = true;
          } else if (args[i].equals("-r")) {
            i++;
            if (args.length < i + 1) {
              badUsage(name, "No URIResolver class");
            }
            String r = args[i++];
            config.setURIResolver(config.makeURIResolver(r));
            dynamicEnv.setURIResolver(config.makeURIResolver(r));
          } else if (args[i].equals("-s")) {
            i++;
            if (args.length < i + 1) {
              badUsage(name, "No source file name");
            }
            sourceFileName = args[i++];
          } else if (args[i].equals("-sa")) {
            // already handled
            i++;
          } else if (args[i].equals("-snone")) {
            config.setStripsWhiteSpace(Whitespace.NONE);
            i++;
          } else if (args[i].equals("-sall")) {
            config.setStripsWhiteSpace(Whitespace.ALL);
            i++;
          } else if (args[i].equals("-signorable")) {
            config.setStripsWhiteSpace(Whitespace.IGNORABLE);
            i++;
          } else if (args[i].equals("-strip")) { // retained for compatibility
            config.setStripsWhiteSpace(Whitespace.ALL);
            i++;
          } else if (args[i].equals("-t")) {
            System.err.println(config.getProductTitle());
            // System.err.println("Java version " + System.getProperty("java.version"));
            System.err.println(config.getPlatform().getPlatformVersion());
            config.setTiming(true);
            showTime = true;
            i++;
          } else if (args[i].equals("-T")) {
            config.setTraceListener(new XQueryTraceListener());
            i++;
          } else if (args[i].equals("-TJ")) {
            i++;
            config.setTraceExternalFunctions(true);
          } else if (args[i].equals("-TL")) {
            if (args.length < i + 2) {
              badUsage(name, "No TraceListener class specified");
            }
            TraceListener traceListener = config.makeTraceListener(args[++i]);
            config.setTraceListener(traceListener);
            config.setLineNumbering(true);
            i++;
          } else if (args[i].equals("-u")) {
            useURLs = true;
            i++;
          } else if (args[i].equals("-untyped")) {
            // TODO: this is an experimental undocumented option. It should be checked for
            // consistency
            config.setAllNodesUntyped(true);
            i++;
          } else if (args[i].equals("-v")) {
            config.setValidation(true);
            i++;
          } else if (args[i].equals("-val")) {
            if (schemaAware) {
              config.setSchemaValidationMode(Validation.STRICT);
            } else {
              quit("The -val option requires a schema-aware processor", 2);
            }
            i++;
          } else if (args[i].equals("-vlax")) {
            if (schemaAware) {
              config.setSchemaValidationMode(Validation.LAX);
            } else {
              quit("The -vlax option requires a schema-aware processor", 2);
            }
            i++;
          } else if (args[i].equals("-vw")) {
            if (schemaAware) {
              config.setValidationWarnings(true);
            } else {
              quit("The -vw option requires a schema-aware processor", 2);
            }
            i++;
          } else if (args[i].equals("-wrap")) {
            wrap = true;
            i++;
          } else if (args[i].equals("-1.1")) {
            config.setXMLVersion(Configuration.XML11);
            i++;
          } else if (args[i].equals("-?")) {
            badUsage(name, "");
          } else if (args[i].equals("-")) {
            queryFileName = "-";
            i++;
          } else {
            badUsage(name, "Unknown option " + args[i]);
          }
        } else {
          break;
        }
      }

      if (!("-".equals(queryFileName))) {
        if (args.length < i + 1) {
          badUsage(name, "No query file name");
        }
        queryFileName = args[i++];
      }

      for (int p = i; p < args.length; p++) {
        String arg = args[p];
        int eq = arg.indexOf("=");
        if (eq < 1 || eq >= arg.length() - 1) {
          badUsage(name, "Bad param=value pair on command line: " + arg);
        }
        String argname = arg.substring(0, eq);
        if (argname.startsWith("!")) {
          // parameters starting with "!" are taken as output properties
          outputProps.setProperty(argname.substring(1), arg.substring(eq + 1));
        } else if (argname.startsWith("+")) {
          // parameters starting with "+" are taken as input documents
          Object sources = Transform.loadDocuments(arg.substring(eq + 1), useURLs, config, true);
          dynamicEnv.setParameter(argname.substring(1), sources);
        } else {
          dynamicEnv.setParameter(argname, new UntypedAtomicValue(arg.substring(eq + 1)));
        }
      }

      config.displayLicenseMessage();
      if (pullMode) {
        config.setLazyConstructionMode(true);
      }

      Source sourceInput = null;

      if (sourceFileName != null) {
        if (useURLs || sourceFileName.startsWith("http:") || sourceFileName.startsWith("file:")) {
          sourceInput = config.getURIResolver().resolve(sourceFileName, null);
          if (sourceInput == null) {
            sourceInput = config.getSystemURIResolver().resolve(sourceFileName, null);
          }
        } else if (sourceFileName.equals("-")) {
          // take input from stdin
          sourceInput = new StreamSource(System.in);
        } else {
          sourceFile = new File(sourceFileName);
          if (!sourceFile.exists()) {
            quit("Source file " + sourceFile + " does not exist", 2);
          }

          if (config.getPlatform() instanceof JavaPlatform) {
            InputSource eis = new InputSource(sourceFile.toURI().toString());
            sourceInput = new SAXSource(eis);
          } else {
            sourceInput = new StreamSource(sourceFile.toURI().toString());
          }
        }
      }

      long startTime = (new Date()).getTime();
      if (showTime) {
        System.err.println("Compiling query from " + queryFileName);
      }

      XQueryExpression exp;

      try {
        if (queryFileName.equals("-")) {
          Reader queryReader = new InputStreamReader(System.in);
          exp = staticEnv.compileQuery(queryReader);
        } else if (queryFileName.startsWith("{") && queryFileName.endsWith("}")) {
          // query is inline on the command line
          String q = queryFileName.substring(1, queryFileName.length() - 1);
          exp = staticEnv.compileQuery(q);
        } else if (useURLs
            || queryFileName.startsWith("http:")
            || queryFileName.startsWith("file:")) {
          ModuleURIResolver resolver = config.getModuleURIResolver();
          String[] locations = {queryFileName};
          Source[] sources = resolver.resolve(null, null, locations);
          if (sources.length != 1 || !(sources[0] instanceof StreamSource)) {
            quit("Module URI Resolver must return a single StreamSource", 2);
          }
          String queryText =
              QueryReader.readSourceQuery((StreamSource) sources[0], config.getNameChecker());
          exp = staticEnv.compileQuery(queryText);
        } else {
          InputStream queryStream = new FileInputStream(queryFileName);
          staticEnv.setBaseURI(new File(queryFileName).toURI().toString());
          exp = staticEnv.compileQuery(queryStream, null);
        }
        staticEnv = exp.getStaticContext(); // the original staticContext is copied

        if (showTime) {
          long endTime = (new Date()).getTime();
          System.err.println("Compilation time: " + (endTime - startTime) + " milliseconds");
          startTime = endTime;
        }

      } catch (XPathException err) {
        int line = -1;
        String module = null;
        if (err.getLocator() != null) {
          line = err.getLocator().getLineNumber();
          module = err.getLocator().getSystemId();
        }
        if (err.hasBeenReported()) {
          quit("Failed to compile query", 2);
        } else {
          if (line == -1) {
            System.err.println("Failed to compile query: " + err.getMessage());
          } else {
            System.err.println("Static error at line " + line + " of " + module + ':');
            System.err.println(err.getMessage());
          }
        }
        exp = null;
        System.exit(2);
      }

      if (explain) {
        staticEnv.getExecutable().getKeyManager().explainKeys(config);
        staticEnv.explainGlobalVariables();
        staticEnv.explainGlobalFunctions();
        exp.explain(staticEnv.getConfiguration());
      }

      OutputStream destination;
      if (outputFileName != null) {
        outputFile = new File(outputFileName);
        if (outputFile.isDirectory()) {
          quit("Output is a directory", 2);
        }
        destination = new FileOutputStream(outputFile);
      } else {
        destination = System.out;
      }

      for (int r = 0; r < repeat; r++) { // repeat is for internal testing/timing

        if (sourceInput != null) {
          if (showTime) {
            System.err.println("Processing " + sourceInput.getSystemId());
          }
          DocumentInfo doc = staticEnv.buildDocument(sourceInput);
          dynamicEnv.setContextItem(doc);
        }

        try {
          if (wrap) {
            SequenceIterator results = exp.iterator(dynamicEnv);
            DocumentInfo resultDoc = QueryResult.wrap(results, config);
            QueryResult.serialize(resultDoc, new StreamResult(destination), outputProps, config);
            destination.close();
          } else if (pullMode) {
            if (wrap) {
              outputProps.setProperty(SaxonOutputKeys.WRAP, "yes");
            }
            try {
              exp.pull(dynamicEnv, new StreamResult(destination), outputProps);
            } catch (XPathException err) {
              config.reportFatalError(err);
              throw err;
            }
          } else {
            exp.run(dynamicEnv, new StreamResult(destination), outputProps);
          }
        } catch (TerminationException err) {
          throw err;
        } catch (XPathException err) {
          if (err.hasBeenReported()) {
            throw new DynamicError("Run-time errors were reported");
          } else {
            throw err;
          }
        }

        if (showTime) {
          long endTime = (new Date()).getTime();
          System.err.println("Execution time: " + (endTime - startTime) + " milliseconds");
          startTime = endTime;
        }
      }

    } catch (TerminationException err) {
      quit(err.getMessage(), 1);
    } catch (XPathException err) {
      quit("Query processing failed: " + err.getMessage(), 2);
    } catch (TransformerFactoryConfigurationError err) {
      err.printStackTrace();
      quit("Query processing failed", 2);
    } catch (Exception err2) {
      err2.printStackTrace();
      quit("Fatal error during transformation: " + err2.getMessage(), 2);
    }
  }
  public static void delete(String definitionName) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();

      // The following allows xml parsing without access to the dtd
      EntityResolver resolver =
          new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId) {
              String empty = ""; // $NON-NLS-1$
              ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
              return new InputSource(bais);
            }
          };
      db.setEntityResolver(resolver);

      // The following catches xml parsing exceptions
      db.setErrorHandler(
          new ErrorHandler() {
            @Override
            public void error(SAXParseException saxparseexception) throws SAXException {}

            @Override
            public void warning(SAXParseException saxparseexception) throws SAXException {}

            @Override
            public void fatalError(SAXParseException saxparseexception) throws SAXException {
              throw saxparseexception;
            }
          });

      File file = new File(CUSTOM_XML_TRACE_DEFINITIONS_PATH_NAME);
      Document doc = db.parse(file);

      Element root = doc.getDocumentElement();
      if (!root.getNodeName().equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
        return;
      }

      NodeList nodeList = root.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node instanceof Element
            && node.getNodeName().equals(DEFINITION_ELEMENT)
            && definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) {
          root.removeChild(node);
        }
      }

      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$

      // initialize StreamResult with File object to save to file
      StreamResult result = new StreamResult(new StringWriter());
      DOMSource source = new DOMSource(doc);
      transformer.transform(source, result);
      String xmlString = result.getWriter().toString();

      FileWriter writer = new FileWriter(file);
      writer.write(xmlString);
      writer.close();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }
  }
  @Override
  public void save(String path) {
    try {
      DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = dbf.newDocumentBuilder();

      // The following allows xml parsing without access to the dtd
      EntityResolver resolver =
          new EntityResolver() {
            @Override
            public InputSource resolveEntity(String publicId, String systemId) {
              String empty = ""; // $NON-NLS-1$
              ByteArrayInputStream bais = new ByteArrayInputStream(empty.getBytes());
              return new InputSource(bais);
            }
          };
      db.setEntityResolver(resolver);

      // The following catches xml parsing exceptions
      db.setErrorHandler(
          new ErrorHandler() {
            @Override
            public void error(SAXParseException saxparseexception) throws SAXException {}

            @Override
            public void warning(SAXParseException saxparseexception) throws SAXException {}

            @Override
            public void fatalError(SAXParseException saxparseexception) throws SAXException {
              throw saxparseexception;
            }
          });

      Document doc = null;
      File file = new File(path);
      if (file.canRead()) {
        doc = db.parse(file);
        if (!doc.getDocumentElement()
            .getNodeName()
            .equals(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT)) {
          return;
        }
      } else {
        doc = db.newDocument();
        Node node = doc.createElement(CUSTOM_XML_TRACE_DEFINITION_ROOT_ELEMENT);
        doc.appendChild(node);
      }

      Element root = doc.getDocumentElement();

      NodeList nodeList = root.getChildNodes();
      for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node instanceof Element
            && node.getNodeName().equals(DEFINITION_ELEMENT)
            && definitionName.equals(((Element) node).getAttribute(NAME_ATTRIBUTE))) {
          root.removeChild(node);
        }
      }
      Element definitionElement = doc.createElement(DEFINITION_ELEMENT);
      root.appendChild(definitionElement);
      definitionElement.setAttribute(NAME_ATTRIBUTE, definitionName);

      Element formatElement = doc.createElement(TIME_STAMP_OUTPUT_FORMAT_ELEMENT);
      definitionElement.appendChild(formatElement);
      formatElement.appendChild(doc.createTextNode(timeStampOutputFormat));

      if (rootInputElement != null) {
        definitionElement.appendChild(createInputElementElement(rootInputElement, doc));
      }

      if (outputs != null) {
        for (OutputColumn output : outputs) {
          Element outputColumnElement = doc.createElement(OUTPUT_COLUMN_ELEMENT);
          definitionElement.appendChild(outputColumnElement);
          outputColumnElement.setAttribute(NAME_ATTRIBUTE, output.name);
        }
      }

      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$

      // initialize StreamResult with File object to save to file
      StreamResult result = new StreamResult(new StringWriter());
      DOMSource source = new DOMSource(doc);
      transformer.transform(source, result);
      String xmlString = result.getWriter().toString();

      FileWriter writer = new FileWriter(file);
      writer.write(xmlString);
      writer.close();
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerFactoryConfigurationError e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (SAXException e) {
      e.printStackTrace();
    }
  }
Example #28
0
  /** put our keywords into the XML description */
  protected static String swapKeywords(
      final DetectionEvent detection,
      final Status currentLocation,
      final String weapon,
      final TargetType theTarget) {
    // amend string template to include available parameters
    final Float brg_degs = detection.getBearing();
    final WorldDistance rng = detection.getRange();

    // take a copy of the string
    String working = new String(weapon);

    // swap the bearing
    if (brg_degs != null) {
      final String brg_val = "" + brg_degs.floatValue();
      working = replaceAll(working, "$BRG$", brg_val);
    }

    // swap the range
    if (rng != null) {
      final String rng_val = "" + rng.getValueIn(WorldDistance.YARDS);
      working = replaceAll(working, "$RNG$", rng_val);
    }

    // insert the location of the target
    if (brg_degs != null) {
      final float brg_val = brg_degs.floatValue();

      // do we know range?
      if (rng != null) {
        // yes, compute target location
        final WorldVector newVector =
            new WorldVector(
                MWC.Algorithms.Conversions.Degs2Rads(brg_val),
                rng.getValueIn(WorldDistance.DEGS),
                0);
        final WorldLocation newLoc = currentLocation.getLocation().add(newVector);

        // produce strings from this location
        final String theDepth = "" + newLoc.getDepth();
        final String theLat = "" + newLoc.getLat();
        final String theLong = "" + newLoc.getLong();

        // put these strings into the new behaviour
        working = replaceAll(working, "$TGT_DEPTH$", theDepth);
        working = replaceAll(working, "$TGT_LAT$", theLat);
        working = replaceAll(working, "$TGT_LONG$", theLong);

      } else {
        // no, send the weapon down a bearing for XXXX yds
        // compute target location
        final double TGT_RANGE = 5000;
        final WorldVector newVector =
            new WorldVector(
                MWC.Algorithms.Conversions.Degs2Rads(brg_val),
                MWC.Algorithms.Conversions.Yds2Degs(TGT_RANGE),
                0);
        final WorldLocation newLoc = currentLocation.getLocation().add(newVector);

        // produce strings from this location
        final String theDepth = "" + newLoc.getDepth();
        final String theLat = "" + newLoc.getLat();
        final String theLong = "" + newLoc.getLong();

        // put these strings into the new behaviour
        working = replaceAll(working, "$TGT_DEPTH$", theDepth);
        working = replaceAll(working, "$TGT_LAT$", theLat);
        working = replaceAll(working, "$TGT_LONG$", theLong);
      }
    }

    if (theTarget != null) {
      // output the XML header stuff
      // output the plot
      final java.io.StringWriter newString = new StringWriter();
      //      final com.sun.xml.tree.XmlDocument doc = new com.sun.xml.tree.XmlDocument();
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      Document doc = null;
      try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.newDocument();
        final org.w3c.dom.Element type =
            ASSET.Util.XML.Decisions.Util.TargetTypeHandler.getElement(theTarget, doc);
        doc.appendChild(type);
        doc.setNodeValue(type.getTagName());
        //    doc.changeNodeOwner(type);
        //   doc.setSystemId("ASSET XML Version 1.0");

        // Use a Transformer for output
        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(newString);
        transformer.transform(source, result);
      } catch (ParserConfigurationException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (DOMException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (TransformerFactoryConfigurationError transformerFactoryConfigurationError) {
        transformerFactoryConfigurationError
            .printStackTrace(); // To change body of catch statement use Options | File Templates.
      } catch (TransformerException e) {
        e.printStackTrace(); // To change body of catch statement use Options | File Templates.
      }

      //      // ok, we should be done now
      //      try
      //      {
      //        doc.write(newString);
      //      }
      //      catch(java.io.IOException e)
      //      {
      //        e.printStackTrace();
      //      }

      // try to extract the <target type portion
      if (newString != null) {
        final String val = newString.toString();
        final String startIdentifier = "<TargetType";
        final String endIdentifier = "</TargetType";
        final int start = val.indexOf(startIdentifier);
        final int end = val.lastIndexOf(endIdentifier);
        final String detail = val.substring(start, end + endIdentifier.length() + 1);

        // lastly, replace the string
        working = replaceAll(working, "<TargetType/>", detail);
      }
    }

    return working;
  }