コード例 #1
0
ファイル: Transformer.java プロジェクト: NCIP/i-spy
  /**
   * Transform the input document
   *
   * @param xml The input xml
   * @return The rendered HTML
   * @throws IOException
   */
  public Document transform(Document document) throws IOException {

    String renderedHTML = "";

    javax.xml.transform.Transformer transformer;

    Document transformedDoc = null;

    try {

      transformer = m_template.newTransformer();
      assignParameters(transformer, m_params);
      DocumentSource fileSource = new DocumentSource(document);
      // Source fileSource = new StreamSource(xml);
      // Result result = new StreamResult(renderedHTML);
      DocumentResult result = new DocumentResult();

      transformer.transform(fileSource, result);

      transformedDoc = result.getDocument();

    } catch (TransformerConfigurationException e) {
      throw new IOException(e.getMessage());
    } catch (TransformerException e) {
      throw new IOException(e.getMessage());
    }

    return transformedDoc;
  }
コード例 #2
0
 @SuppressWarnings("unchecked")
 public static ArrayList<String> getNameSpaces(String baseURL) {
   ArrayList<String> res = new ArrayList<String>();
   OAIPMHtype xmlType = null;
   ListMetadataFormats list = null;
   try {
     list = new ListMetadataFormats(baseURL);
     String xmlRec = list.toString();
     if (xmlRec.startsWith("<?")) {
       int offset = xmlRec.indexOf("?>");
       xmlRec = xmlRec.substring(offset + 2);
     }
     InputStream is = new ByteArrayInputStream(xmlRec.getBytes("UTF-8"));
     JAXBElement<OAIPMHtype> oai = (JAXBElement<OAIPMHtype>) u.unmarshal(is);
     xmlType = oai.getValue();
     ArrayList<MetadataFormatType> res0 =
         (ArrayList<MetadataFormatType>) xmlType.getListMetadataFormats().getMetadataFormat();
     Iterator<MetadataFormatType> itr = res0.iterator();
     while (itr.hasNext()) {
       MetadataFormatType typ = itr.next();
       res.add(typ.getMetadataPrefix());
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (ParserConfigurationException e) {
     e.printStackTrace();
   } catch (SAXException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   } catch (JAXBException e) {
     e.printStackTrace();
   }
   return res;
 }
コード例 #3
0
  /**
   * Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator.
   * This function will be called by the implementation of TreeWalker and NodeIterator; it is not
   * intended to be called directly from user code.
   *
   * @param n The node to check to see if it passes the filter or not.
   * @return a constant to determine whether the node is accepted, rejected, or skipped, as defined
   *     above .
   */
  public short acceptNode(int n, XPathContext xctxt) {

    try {
      xctxt.pushCurrentNode(n);
      xctxt.pushIteratorRoot(m_context);
      if (DEBUG) {
        System.out.println("traverser: " + m_traverser);
        System.out.print("node: " + n);
        System.out.println(", " + m_cdtm.getNodeName(n));
        // if(m_cdtm.getNodeName(n).equals("near-east"))
        System.out.println("pattern: " + m_pattern.toString());
        m_pattern.debugWhatToShow(m_pattern.getWhatToShow());
      }

      XObject score = m_pattern.execute(xctxt);

      if (DEBUG) {
        // System.out.println("analysis: "+Integer.toBinaryString(m_analysis));
        System.out.println("score: " + score);
        System.out.println("skip: " + (score == NodeTest.SCORE_NONE));
      }

      // System.out.println("\n::acceptNode - score: "+score.num()+"::");
      return (score == NodeTest.SCORE_NONE) ? DTMIterator.FILTER_SKIP : DTMIterator.FILTER_ACCEPT;
    } catch (javax.xml.transform.TransformerException se) {

      // TODO: Fix this.
      throw new RuntimeException(se.getMessage());
    } finally {
      xctxt.popCurrentNode();
      xctxt.popIteratorRoot();
    }
  }
コード例 #4
0
 protected WXSSchema nouveauSchemaInclu(
     final URL urlSchemaParent,
     final String schemaLocation,
     final String espaceImport,
     final WXSSchema schemaParent)
     throws JaxeException {
   try {
     final URL urls = resoudreURI(getURLParent(urlSchemaParent), schemaLocation);
     if (urls == null)
       throw new JaxeException("include/import : location not found : " + schemaLocation);
     for (WXSSchema schemaInclu : schemasInclu)
       if (schemaInclu.getURL().toURI().normalize().equals(urls.toURI().normalize())) {
         ajouterEspaces(
             schemaInclu, schemaParent, espaceImport); // une chance de plus de trouver un pr?fixe
         return (schemaInclu);
       }
     final WXSSchema schemaInclu = new WXSSchema(lireDocument(urls), urls, this, schemaParent);
     ajouterEspaces(schemaInclu, schemaParent, espaceImport);
     schemasInclu.add(schemaInclu);
     schemaInclu.inclusions();
     return (schemaInclu);
   } catch (final MalformedURLException ex) {
     throw new JaxeException("include/import : MalformedURLException: " + ex.getMessage(), ex);
   } catch (final URISyntaxException ex) {
     throw new JaxeException("include/import : URISyntaxException: " + ex.getMessage(), ex);
   } catch (final TransformerException ex) {
     throw new JaxeException("include/import : TransformerException: " + ex.getMessage(), ex);
   }
 }
コード例 #5
0
  /** 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();
    }
  }
コード例 #6
0
ファイル: XMLTransformer.java プロジェクト: adsefr/rmscode
  /**
   * @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();
    }
  }
コード例 #7
0
ファイル: Helper.java プロジェクト: crystalwm/jsnose_demo
  /**
   * Serialize the Document object.
   *
   * @param dom the document to serialize
   * @return the serialized dom String
   */
  public static byte[] getDocumentToByteArray(Document dom) {
    try {
      TransformerFactory tFactory = TransformerFactory.newInstance();

      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      transformer.setOutputProperty(OutputKeys.METHOD, "html");
      // TODO should be fixed to read doctype declaration
      // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      // "-//W3C//DTD XHTML 1.0 Transitional//EN\"
      // \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
      transformer.setOutputProperty(
          OutputKeys.DOCTYPE_PUBLIC,
          "-//W3C//DTD XHTML 1.0 Strict//EN\" "
              + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");

      // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      // "-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd");
      DOMSource source = new DOMSource(dom);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      Result result = new StreamResult(out);
      transformer.transform(source, result);

      // System.out.println("Injected Javascript!");
      return out.toByteArray();
    } catch (TransformerConfigurationException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (TransformerException e) {
      LOGGER.error(e.getMessage(), e);
    }
    return null;
  }
コード例 #8
0
ファイル: TestCreateXML.java プロジェクト: regson82/WorkSpace
  public static void main(String[] args) {

    try {

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      Document document = builder.newDocument();
      Element root = document.createElement("Languages");
      root.setAttribute("cat", "it");

      Element lan1 = document.createElement("lan");
      lan1.setAttribute("id", "1");
      Element name1 = document.createElement("name");
      name1.setTextContent("Java");
      Element ide1 = document.createElement("ide");
      ide1.setTextContent("Eclipse");
      lan1.appendChild(name1);
      lan1.appendChild(ide1);

      Element lan2 = document.createElement("lan");
      lan1.setAttribute("id", "2");
      Element name2 = document.createElement("name");
      name1.setTextContent("Swift");
      Element ide2 = document.createElement("ide");
      ide1.setTextContent("Xcode");
      lan1.appendChild(name2);
      lan1.appendChild(ide2);

      Element lan3 = document.createElement("lan");
      lan1.setAttribute("id", "1");
      Element name3 = document.createElement("name");
      name1.setTextContent("Java");
      Element ide3 = document.createElement("ide");
      ide1.setTextContent("Eclipse");
      lan1.appendChild(name3);
      lan1.appendChild(ide3);

      root.appendChild(lan1);
      root.appendChild(lan2);
      root.appendChild(lan3);
      document.appendChild(root);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      StringWriter writer = new StringWriter();
      transformer.transform(new DOMSource(document), new StreamResult(writer));
      System.out.println(writer.toString());

      transformer.transform(new DOMSource(document), new StreamResult("newXML.xml"));

    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #9
0
  protected void processDocument(Document document, PrintWriter writer) {
    String type = new StencilSetUtil().getStencilSet(document);
    SyntaxChecker checker = null;
    if (type != null) {
      if (type.equals("bpmn.json") || type.equals("bpmneec.json"))
        checker = getCheckerBPMN(document);
      else if (type.equals("bpmn1.1.json")) checker = getCheckerBPMN11(document);
      else if (type.equals("ibpmn.json")) checker = getCheckerIBPMN(document);
      else if (type.equals("interactionpetrinets.json")) checker = getCheckerIPN(document);
      else if (type.equals("epc.json")) checker = getCheckerEPC(document);
    }

    if (checker == null) { // try eRDF
      try {
        NamedNodeMap map =
            XPathAPI.selectSingleNode(document, "//a[@rel='oryx-stencilset']").getAttributes();
        type = map.getNamedItem("href").getNodeValue();
      } catch (TransformerException e) {
        e.printStackTrace();
      }
      if (type != null && type.endsWith("petrinet.json")) {
        checker = getCheckerPetriNet(document);
      }
    }

    if (checker == null) {
      writer.print("{}");
    } else {
      checker.checkSyntax();
      writer.print(checker.getErrorsAsJson().toString());
    }
  }
コード例 #10
0
ファイル: Transform.java プロジェクト: smoczyna/dsl-lib
  /**
   * Transform the passed XML string with the stated stylesheet.
   *
   * <p>Enables passing any amount of <code>parameters</code> into the stylesheet using a <code>
   * Hashtable</code> to store them as name:value pairs where the key is the name of the parameter
   * and the value is the value.<br>
   * The parameter can be matched in the XSL as follows:<br>
   * &lt;xsl:value-of select=&quot;$parameter_name&quot;&gt;.
   *
   * @return String The transformed XML
   * @param xmlString String XML input string
   * @param xslFileName String XSL stylesheet filename
   * @param parameters the list of parameters to pass to the XSL stylesheet.
   * @exception TransformerException Any exception thrown during the transform process
   */
  public static String transform(String xmlString, String xslFileName, HashMap parameters)
      throws TransformerException {
    try {
      StringWriter stringWriter = new StringWriter();
      Source xmlSource = new StreamSource(new StringReader(xmlString));
      Templates template = (Templates) xslcache.getTemplate(xslFileName);
      Transformer trans = template.newTransformer();

      if (parameters != null) {
        Set keys = parameters.keySet();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
          String name = (String) it.next();
          String value = (String) parameters.get(name);
          trans.setParameter(name, value);
        }
      }
      trans.transform(xmlSource, new StreamResult(stringWriter));
      return stringWriter.toString();

    } catch (TransformerConfigurationException e) {
      throw new TransformerException(
          "Transformer could not be created: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (TransformerException e) {
      throw new TransformerException(
          "Error during transformation: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (Exception e) {
      throw new TransformerException(
          "Unknown error during transformation: "
              + e.getClass().getName()
              + " - "
              + e.getMessage());
    }
  }
コード例 #11
0
ファイル: DomUtils.java プロジェクト: hlim/studio2
  /**
   * convert an xml document to a string
   *
   * @param node document node
   * @return a string representation of the xml document
   */
  public static String xmlToString(Node node, String encoding) {

    String retXmlAsString = "";

    try {
      Source source = new DOMSource(node);
      StringWriter stringWriter = new StringWriter();
      Result result = new StreamResult(stringWriter);
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();
      transformer.setOutputProperty(OutputKeys.ENCODING, encoding);

      transformer.transform(source, result);
      retXmlAsString = stringWriter.toString();

      // for some reason encoding is not handling entity references - need
      // to look in to the further
      retXmlAsString = retXmlAsString.replace("&nbsp;", "&#160;");

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

    return retXmlAsString;
  }
コード例 #12
0
  private NodeList load()
      throws IOException, FileNotFoundException, ParserConfigurationException, SAXException,
          TransformerException {
    InputStream fis = null;
    NodeList nl = null;
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

      fis = new FileInputStream(fileName);
      nl = XPathAPI.selectNodeList(builder.parse(fis), xpath);
      log.debug("found " + nl.getLength());

    } catch (FileNotFoundException e) {
      log.warn(e.toString());
      throw e;
    } catch (IOException e) {
      log.warn(e.toString());
      throw e;
    } catch (ParserConfigurationException e) {
      log.warn(e.toString());
      throw e;
    } catch (SAXException e) {
      log.warn(e.toString());
      throw e;
    } catch (TransformerException e) {
      log.warn(e.toString());
      throw e;
    } finally {
      JOrphanUtils.closeQuietly(fis);
    }
    return nl;
  }
コード例 #13
0
ファイル: XSLTRunner.java プロジェクト: printmiles/Odin
  private void runXsltScript() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Select XSLT script");
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == 1) {
      return;
    }
    File fXSLT = fc.getSelectedFile();

    File fXML = new File("C:/Odin/Repository/");
    boolean isDirectory = fXML.isDirectory();
    /* Code adapted from: http://blog.msbbc.co.uk/2007/06/simple-saxon-java-example.html
     * [Accessed 3rd-Sept-2010]
     */
    for (File format : fXML.listFiles()) {
      boolean isSuccessful = false;
      try {
        System.setProperty(
            "javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer tf = tFact.newTransformer(new StreamSource(fXSLT));
        tf.transform(new StreamSource(format), new StreamResult(format));
        isSuccessful = true;
      } catch (TransformerException tX) {
        tX.printStackTrace();
      } finally {
        System.out.println(
            "Change of file " + format.getName() + " was successful? " + isSuccessful);
      }
    }
  }
コード例 #14
0
 /**
  * Writes data out in XML format.
  *
  * @return A flag indicating the success of the operation.
  */
 private boolean writeXMLFile() {
   File selectedFile = model.getFile();
   try {
     FileOutputStream ow = new FileOutputStream(selectedFile);
     DriveTrainEncoder.encode(ow, model);
     ow.close();
     model.reset();
     return true;
   } catch (IOException iox) {
     JOptionPane.showMessageDialog(
         this,
         Messages.format("Main.15", iox.getLocalizedMessage()), // $NON-NLS-1$
         Messages.getString("Main.16"),
         JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$
     return false;
   } catch (ParserConfigurationException iox) {
     JOptionPane.showMessageDialog(
         this,
         Messages.format("ParserConfigurationException", iox.getLocalizedMessage()), // $NON-NLS-1$
         Messages.getString("Main.16"),
         JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$
     return false;
   } catch (TransformerException iox) {
     JOptionPane.showMessageDialog(
         this,
         Messages.format("TransformerException", iox.getLocalizedMessage()), // $NON-NLS-1$
         Messages.getString("Main.16"),
         JOptionPane.ERROR_MESSAGE); // $NON-NLS-1$
     return false;
   }
 }
コード例 #15
0
 private void soapMessage(String path, String wsName, String wsPortName) {
   try {
     URL wsdlURL = new URL(APP_SERVER + path);
     final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE;
     Service service = Service.create(wsdlURL, new QName(NS, wsName));
     Dispatch<Source> dispatcher =
         service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD);
     Source request = new StreamSource(new StringReader("<hello/>"));
     Source response = dispatcher.invoke(request);
     assertNotNull(response);
     Transformer transformer = TransformerFactory.newInstance().newTransformer();
     final StringWriter writer = new StringWriter();
     Result output = new StreamResult(writer);
     transformer.transform(response, output);
     Message message = new Message("clientMessages");
     message.dumpFormattedMessage(
         EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString());
   } catch (MalformedURLException e) {
     e.printStackTrace();
     fail(String.valueOf(e));
   } catch (TransformerConfigurationException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   }
 }
コード例 #16
0
ファイル: Utils.java プロジェクト: waghsk/i2b2-fhir
  public static String getStringFromDocument(Document doc) {
    try {
      doc.normalize();
      DOMSource domSource = new DOMSource(doc);
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      //
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      int indent = 2;
      if (indent > 0) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
      }
      //

      transformer.transform(domSource, result);
      return writer.toString();
    } catch (TransformerException ex) {
      ex.printStackTrace();
      return null;
    }
  }
コード例 #17
0
  public void write(Document doc, OutputStream outputStream) throws IOException {
    //        OutputFormat format = new OutputFormat(doc);
    //        format.setIndenting(true);
    //        format.setEncoding("UTF-8");
    //        XMLSerializer serializer = new XMLSerializer(outputStream, format);
    //        serializer.asDOMSerializer();
    //        serializer.serialize(doc);

    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      try {
        factory.setAttribute("indent-number", 4);
      } catch (Exception e) {; // guess we can't set it, that's ok
      }

      Transformer transformer = factory.newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

      // need to nest outputStreamWriter to get around JDK 5 bug.  See
      // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
      transformer.transform(
          new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8")));
    } catch (TransformerException e) {
      throw new IOException(e.getMessage());
    }
  }
コード例 #18
0
  private void writeXmlDocument(File file, Document doc) {
    try {
      // set up a transformer
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // create string from xml tree
      FileWriter writer = new FileWriter(file);
      StreamResult result = new StreamResult(writer);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);

      writer.close();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #19
0
  /**
   * Print the the trace of methods from where the error originated. This will trace all nested
   * exception objects, as well as this object.
   *
   * @param s The stream where the dump will be sent to.
   */
  public void printStackTrace(java.io.PrintStream s) {

    if (s == null) s = System.err;

    try {
      super.printStackTrace(s);
    } catch (Exception e) {
    }

    Throwable exception = m_exception;

    for (int i = 0; (i < 10) && (null != exception); i++) {
      s.println("---------");
      exception.printStackTrace(s);

      if (exception instanceof TransformerException) {
        TransformerException se = (TransformerException) exception;
        Throwable prev = exception;

        exception = se.getException();

        if (prev == exception) break;
      } else {
        exception = null;
      }
    }
  }
コード例 #20
0
ファイル: PrettyXML.java プロジェクト: pexus/PerfLog
  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();
  }
コード例 #21
0
 public void createXml(OutputStream os) throws IOException {
   try {
     getGraphicObject().createXml(os);
   } catch (TransformerException e) {
     throw new IOException(e.toString());
   }
 }
コード例 #22
0
ファイル: ECQL.java プロジェクト: Geodan/geotools
  /**
   * Command line expression tester used to try out filters and expressions.
   *
   * @param args
   */
  public static final void main(String[] args) {
    System.out.println("ECQL Filters Tester");
    System.out.println("Seperate with \";\" or \"quit\" to finish)");

    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    FilterTransformer filterTransformer = new FilterTransformer();
    filterTransformer.setIndentation(4);

    while (true) {
      System.out.print(">");

      String line = null;

      try {
        line = reader.readLine();

        if (line.equals("quit")) {
          System.out.println("Bye!");
          break;
        }

        List<Filter> filters = ECQL.toFilterList(line);
        for (Filter filter : filters) {
          System.out.println();
          filterTransformer.transform(filter, System.out);
        }
      } catch (IOException e1) {
        e1.printStackTrace();
      } catch (CQLException cqlex) {
        System.out.println(cqlex.getSyntaxError());
      } catch (TransformerException e) {
        e.printStackTrace();
      }
    }
  }
コード例 #23
0
ファイル: DomDemo.java プロジェクト: vtopqx/common
 public void createXml(String fileName) {
   Element root = this.document.createElement("employees");
   this.document.appendChild(root);
   Element employee = this.document.createElement("employee");
   Element name = this.document.createElement("name");
   name.appendChild(this.document.createTextNode("丁宏亮"));
   employee.appendChild(name);
   Element sex = this.document.createElement("sex");
   sex.appendChild(this.document.createTextNode("m"));
   employee.appendChild(sex);
   Element age = this.document.createElement("age");
   age.appendChild(this.document.createTextNode("30"));
   employee.appendChild(age);
   root.appendChild(employee);
   TransformerFactory tf = TransformerFactory.newInstance();
   try {
     Transformer transformer = tf.newTransformer();
     DOMSource source = new DOMSource(document);
     transformer.setOutputProperty(OutputKeys.ENCODING, "gb2312");
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     PrintWriter pw = new PrintWriter(new FileOutputStream(fileName));
     StreamResult result = new StreamResult(pw);
     transformer.transform(source, result);
     System.out.println("生成XML文件成功!");
   } catch (TransformerConfigurationException e) {
     System.out.println(e.getMessage());
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
   } catch (TransformerException e) {
     System.out.println(e.getMessage());
   }
 }
  /**
   * Implements javax.xml.transform.sax.TransformerHandler.setResult() Enables the user of the
   * TransformerHandler to set the to set the Result for the transformation.
   *
   * @param result A Result instance, should not be null
   * @throws IllegalArgumentException if result is invalid for some reason
   */
  public void setResult(Result result) throws IllegalArgumentException {
    _result = result;

    if (null == result) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.ER_RESULT_NULL);
      throw new IllegalArgumentException(err.toString()); // "result should not be null");
    }

    if (_isIdentity) {
      try {
        // Connect this object with output system directly
        SerializationHandler outputHandler = _transformer.getOutputHandler(result);
        _transformer.transferOutputProperties(outputHandler);

        _handler = outputHandler;
        _lexHandler = outputHandler;
      } catch (TransformerException e) {
        _result = null;
      }
    } else if (_done) {
      // Run the transformation now, if not already done
      try {
        _transformer.setDOM(_dom);
        _transformer.transform(null, _result);
      } catch (TransformerException e) {
        // What the hell are we supposed to do with this???
        throw new IllegalArgumentException(e.getMessage());
      }
    }
  }
コード例 #25
0
ファイル: EventsServlet.java プロジェクト: jsienniak/Serwer
  /**
   * 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();
    }
  }
コード例 #26
0
ファイル: cfgParser.java プロジェクト: andykuria/virtualbank
  public static void createXMLFile(Document doc, File file) {
    try {
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // 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();
      // write to file
      // Create file if it does not exist
      boolean success = file.createNewFile();
      if (success) {
        // File did not exist and was created
        boolean append = false;
        FileWriter fw = new FileWriter(file, append);
        fw.write(xmlString);
        fw.close();
      } else {
        // File already exists

        boolean append = false;
        FileWriter fw = new FileWriter(file, append);
        fw.write(xmlString); // appends the string to the file
        fw.close();
      }

    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (IOException io) {
      io.printStackTrace();
    }
  }
コード例 #27
0
ファイル: IlluminaStatus.java プロジェクト: pajanne/miso-lims
  public void parseStatusXml(String statusXml) {
    try {
      Document statusDoc = SubmissionUtils.emptyDocument();
      SubmissionUtils.transform(new StringReader(statusXml), statusDoc);

      if (statusDoc.getDocumentElement().getTagName().equals("error")) {
        String runName = statusDoc.getElementsByTagName("RunName").item(0).getTextContent();
        String runDirRegex = "(\\d{6})_([A-z0-9]+)_(\\d+)_[A-z0-9_]*";
        Matcher m = Pattern.compile(runDirRegex).matcher(runName);
        if (m.matches()) {
          setStartDate(new SimpleDateFormat("yyMMdd").parse(m.group(1)));
          setInstrumentName(m.group(2));
        }
        setRunName(runName);
        setHealth(HealthType.Unknown);
      } else {
        String runStarted = statusDoc.getElementsByTagName("RunStarted").item(0).getTextContent();
        setStartDate(new SimpleDateFormat("EEEE, MMMMM dd, yyyy h:mm aaa").parse(runStarted));
        setInstrumentName(
            statusDoc.getElementsByTagName("InstrumentName").item(0).getTextContent());
        setRunName(statusDoc.getElementsByTagName("RunName").item(0).getTextContent());
        setHealth(HealthType.Unknown);
      }
      setXml(statusXml);
    } catch (ParserConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
コード例 #28
0
  /**
   * Test whether an XPath is valid. It seems the Xalan has no easy way to check, so this creates a
   * dummy test document, then tries to evaluate the xpath against it.
   *
   * @param xpathString XPath String to validate
   * @param showDialog weather to show a dialog
   * @return returns true if valid, valse otherwise.
   */
  public static boolean validXPath(String xpathString, boolean showDialog) {
    String ret = null;
    boolean success = true;
    Document testDoc = null;
    try {
      testDoc = XPathUtil.makeDocumentBuilder(false, false, false, false).newDocument();
      Element el = testDoc.createElement("root"); // $NON-NLS-1$
      testDoc.appendChild(el);
      XPathUtil.validateXPath(testDoc, xpathString);
    } catch (IllegalArgumentException e) {
      log.warn(e.getLocalizedMessage());
      success = false;
      ret = e.getLocalizedMessage();
    } catch (ParserConfigurationException e) {
      success = false;
      ret = e.getLocalizedMessage();
    } catch (TransformerException e) {
      success = false;
      ret = e.getLocalizedMessage();
    }

    if (showDialog) {
      JOptionPane.showMessageDialog(
          null,
          (success) ? JMeterUtils.getResString("xpath_assertion_valid") : ret, // $NON-NLS-1$
          (success)
              ? JMeterUtils.getResString("xpath_assertion_valid")
              : JMeterUtils //$NON-NLS-1$
                  .getResString("xpath_assertion_failed"),
          (success)
              ? JOptionPane.INFORMATION_MESSAGE // $NON-NLS-1$
              : JOptionPane.ERROR_MESSAGE);
    }
    return success;
  }
コード例 #29
0
ファイル: Helper.java プロジェクト: europeana/metis-framework
  // taken from
  // http://www.exampledepot.com/egs/javax.xml.transform/BasicXsl.html
  // This method applies the xslFilename to inFilename and writes
  // the output to outFilename.
  public static void xsl(File inFile, File outFile, InputStream xslStream) throws Exception {
    try {
      // Create transformer factory
      TransformerFactory factory = TransformerFactory.newInstance();

      // Use the factory to create a template containing the xsl file
      Templates template = factory.newTemplates(new StreamSource(xslStream));

      // Use the template to create a transformer
      Transformer xformer = template.newTransformer();

      // Prepare the input and output files
      Source source = new StreamSource(new FileInputStream(inFile));
      Result result = new StreamResult(new FileOutputStream(outFile));

      // Apply the xsl file to the source file and write the result to the
      // output file
      xformer.transform(source, result);
    } catch (TransformerException e) {
      // An error occurred while applying the XSL file
      // Get location of error in input file
      SourceLocator locator = e.getLocator();
      int col = locator.getColumnNumber();
      int line = locator.getLineNumber();
      throw new Exception(
          String.format("XSL exception line %d col %d message: %s", line, col, e.getMessage()));
    }
  }
コード例 #30
0
  private String combineData() {
    String content = "";
    XMLBuilder builder = null;
    int index = 0;
    String[] tags;

    boolean isEntry = contentArray.size() != 2;

    if (isEntry) {
      tags =
          new String[] {
            "date-created",
            "time-created",
            "latitude",
            "longitude",
            "first-name",
            "middle-name",
            "last-name",
            "birthday",
            "age",
            "gender",
            "address",
            "slide-number",
            "region",
            "case",
            "species",
            "drugs-given",
            "exam-result",
            "remarks"
          };
    } else {
      tags = new String[] {"user", "pass"};
    }

    try {
      if (isEntry) builder = XMLBuilder.create("entry");
      else builder = XMLBuilder.create("credentials");
      Log.d("MakeTextFile", String.valueOf(contentArray.size()));
      for (String data : contentArray) {
        builder.element(tags[index++]).text(data);
        Log.v("WRITE", "CONTENT: " + data);
      }

      Properties outputProperties = new Properties();
      outputProperties.put(javax.xml.transform.OutputKeys.METHOD, "xml");
      outputProperties.put(javax.xml.transform.OutputKeys.INDENT, "yes");
      outputProperties.put("{http://xml.apache.org/xslt}indent-amount", "2");
      outputProperties.put(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");

      content = builder.asString(outputProperties);

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

    return content;
  }